<?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: Meta Channel Integration ===\n";

    // 1. Create meta_sessions table
    $createSessionsTableSql = "
        CREATE TABLE IF NOT EXISTS `meta_sessions` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `company_id` INT NOT NULL,
          `channel_type` ENUM('messenger', 'instagram') NOT NULL,
          `page_id` VARCHAR(255) NOT NULL,
          `page_name` VARCHAR(255) NOT NULL,
          `page_access_token` TEXT NOT NULL,
          `status` ENUM('connected', 'disconnected') DEFAULT 'connected',
          `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          FOREIGN KEY (`company_id`) REFERENCES `companies`(`id`) ON DELETE CASCADE,
          UNIQUE KEY `page_channel_unique` (`page_id`, `channel_type`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    ";
    Database::execute($createSessionsTableSql);
    echo "✅ Table 'meta_sessions' verified/created.\n";

    // 2. Make session_id column in messages_log nullable
    Database::execute("ALTER TABLE `messages_log` MODIFY COLUMN `session_id` INT NULL");
    echo "✅ Modified 'session_id' in 'messages_log' to be nullable.\n";

    // 3. Add meta_session_id column if not exists
    $columns = Database::select("SHOW COLUMNS FROM `messages_log` LIKE 'meta_session_id'");
    if (empty($columns)) {
        Database::execute("ALTER TABLE `messages_log` ADD COLUMN `meta_session_id` INT NULL AFTER `session_id`");
        Database::execute("ALTER TABLE `messages_log` ADD CONSTRAINT `fk_msg_meta_session` FOREIGN KEY (`meta_session_id`) REFERENCES `meta_sessions`(`id`) ON DELETE CASCADE");
        echo "✅ Added 'meta_session_id' column and foreign key constraint to 'messages_log'.\n";
    } else {
        echo "ℹ️ Column 'meta_session_id' already exists in 'messages_log'. Skipping.\n";
    }

    echo "Migration completed successfully!\n";
} catch (\Exception $e) {
    echo "❌ Migration error: " . $e->getMessage() . "\n";
}
