<?php
require_once __DIR__ . '/../config/config.php';
$db = Database::getInstance();

try {
    $col = $db->fetch("SHOW COLUMNS FROM users LIKE 'in_service'");
    if ($col) {
        echo "Column in_service already exists\n";
    } else {
        $db->query("ALTER TABLE users ADD COLUMN in_service TINYINT(1) DEFAULT 0 AFTER advisor_requested");
        echo "Added in_service column\n";
    }

    $col = $db->fetch("SHOW COLUMNS FROM users LIKE 'in_service_by'");
    if ($col) {
        echo "Column in_service_by already exists\n";
    } else {
        $db->query("ALTER TABLE users ADD COLUMN in_service_by INT NULL AFTER in_service");
        echo "Added in_service_by column\n";
    }

    $col = $db->fetch("SHOW COLUMNS FROM users LIKE 'in_service_at'");
    if ($col) {
        echo "Column in_service_at already exists\n";
    } else {
        $db->query("ALTER TABLE users ADD COLUMN in_service_at DATETIME NULL AFTER in_service_by");
        echo "Added in_service_at column\n";
    }

    // Crear tabla operator_activity si no existe
    $check = $db->fetch("SHOW TABLES LIKE 'operator_activity'");
    if ($check) {
        echo "Table operator_activity already exists\n";
    } else {
        $sql = "CREATE TABLE operator_activity (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NULL,
            operator_id INT NULL,
            action VARCHAR(50) NOT NULL,
            details TEXT NULL,
            created_at DATETIME NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
        $db->query($sql);
        echo "Created table operator_activity\n";
    }

    echo "Done.\n";
} catch (Exception $e) {
    echo "Migration failed: " . $e->getMessage() . "\n";
}
