<?php
/**
 * Migration: Smart Doctor - التطوير الكامل
 */
$baseDir = dirname(__DIR__);
$config = require $baseDir . '/config/config.php';

try {
    $pdo = new PDO(
        'mysql:host=' . ($config['db']['host'] ?? 'localhost') . ';port=' . ($config['db']['port'] ?? 3306) . ';dbname=' . ($config['db']['name'] ?? 'lab_lims') . ';charset=' . ($config['db']['charset'] ?? 'utf8mb4'),
        $config['db']['user'] ?? 'root',
        $config['db']['pass'] ?? '',
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    $addCol = function ($table, $col, $def) use ($pdo) {
        try {
            $pdo->exec("ALTER TABLE $table ADD COLUMN $col $def");
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate column') === false) throw $e;
        }
    };

    // 2FA وأعمدة doctor_accounts
    $addCol('doctor_accounts', 'two_factor_enabled', 'TINYINT(1) NOT NULL DEFAULT 0');
    $addCol('doctor_accounts', 'two_factor_secret', 'VARCHAR(64) NULL');
    $addCol('doctor_accounts', 'two_factor_verified_at', 'DATETIME NULL');
    $addCol('doctor_accounts', 'phone', 'VARCHAR(30) NULL');
    $addCol('doctor_accounts', 'whatsapp_notify_critical', 'TINYINT(1) NOT NULL DEFAULT 0');

    // تشغيل SQL المتبقي
    $sqlFile = __DIR__ . '/028_smart_doctor_full.sql';
    if (file_exists($sqlFile)) {
        $sql = file_get_contents($sqlFile);
        $statements = array_filter(array_map('trim', preg_split('/;\s*\n/', $sql)));
        foreach ($statements as $stmt) {
            $stmt = trim($stmt);
            if ($stmt === '' || strpos($stmt, '--') === 0) continue;
            try {
                $pdo->exec($stmt);
            } catch (PDOException $e) {
                if (strpos($e->getMessage(), 'already exists') === false &&
                    strpos($e->getMessage(), 'Duplicate') === false) {
                    echo "Warning: " . $e->getMessage() . "\n";
                }
            }
        }
    }

    echo "✅ تم تشغيل migration Smart Doctor بنجاح!\n";
} catch (Exception $e) {
    die("Error: " . $e->getMessage() . "\n");
}
