<?php
require_once __DIR__ . '/config/config.php';
if (!defined('MIGRATION_TOKEN') || ($_GET['token'] ?? '') !== MIGRATION_TOKEN) {
    http_response_code(403); die('Acceso denegado');
}

$pdo = Database::getInstance()->getConnection();

$steps = [
    "ALTER TABLE lab_pacientes ADD COLUMN IF NOT EXISTS origen VARCHAR(20) NOT NULL DEFAULT 'manual' COMMENT 'Origen: manual | lab | whatsapp' AFTER notas_admin",
    "UPDATE lab_pacientes SET origen = 'whatsapp' WHERE user_id IS NOT NULL AND origen = 'manual'",
    "CREATE INDEX IF NOT EXISTS idx_pac_origen ON lab_pacientes (origen)",
];

echo '<pre>';
foreach ($steps as $sql) {
    echo htmlspecialchars(substr($sql, 0, 80)) . "...\n";
    try {
        $pdo->exec($sql);
        echo "  ✓ OK\n\n";
    } catch (\Throwable $e) {
        echo "  ✗ ERROR: " . htmlspecialchars($e->getMessage()) . "\n\n";
    }
}
echo "Listo.\n</pre>";
