<?php
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit('Access denied.');
}

require_once __DIR__ . '/app/bootstrap.php';

use App\Core\Database;

try {
    $pdo = Database::getConnection();
    
    echo "=== Running Database Migrations: Adding whatsapp_session_id ===\n";
    
    // Check if the column already exists
    $stmt = $pdo->prepare("
        SELECT COLUMN_NAME 
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'users' 
          AND COLUMN_NAME = 'whatsapp_session_id'
    ");
    $stmt->execute();
    $columnExists = $stmt->fetch();
    
    if (!$columnExists) {
        echo "Adding column 'whatsapp_session_id' to 'users' table...\n";
        
        // Add column
        $pdo->exec("ALTER TABLE `users` ADD COLUMN `whatsapp_session_id` INT NULL DEFAULT NULL");
        
        // Add foreign key constraint
        $pdo->exec("
            ALTER TABLE `users` 
            ADD CONSTRAINT `fk_users_whatsapp_session` 
            FOREIGN KEY (`whatsapp_session_id`) 
            REFERENCES `whatsapp_sessions` (`id`) 
            ON DELETE SET NULL
        ");
        
        echo "✅ Column 'whatsapp_session_id' and foreign key created successfully!\n";
    } else {
        echo "ℹ️ Column 'whatsapp_session_id' already exists in 'users' table. Skipping.\n";
    }
    
} catch (\Exception $e) {
    echo "❌ Migration failed: " . $e->getMessage() . "\n";
}
