<?php
declare(strict_types=1);
require_once __DIR__ . '/api/bootstrap.php';

// Ensure this is only run by admin or via CLI
if (php_sapi_name() !== 'cli') {
    $u = current_user();
    if (!$u || ($u['role_name'] ?? '') !== 'super_admin') {
        die('Unauthorized. Must be run from CLI or as super_admin.');
    }
}

echo "Starting Database Performance Optimization Patch...\n\n";

$pdo = db();
$queries = [
    // Bookings indexes
    "ALTER TABLE bookings ADD INDEX idx_property_dates (property_id, check_in, check_out);",
    "ALTER TABLE bookings ADD INDEX idx_status (status);",
    "ALTER TABLE bookings ADD INDEX idx_checkout (check_out);",
    
    // Calendar blocks indexes
    "ALTER TABLE calendar_blocks ADD INDEX idx_cal_property_dates (property_id, start_date, end_date);",
    
    // Reservation locks
    "ALTER TABLE reservation_locks ADD INDEX idx_res_lock_property_dates (property_id, check_in, check_out);",
    
    // OTA Connections webhook secret (used heavily in ota_webhook.php)
    "ALTER TABLE ota_connections ADD INDEX idx_webhook_secret (webhook_secret);"
];

$successCount = 0;
foreach ($queries as $sql) {
    try {
        echo "Executing: $sql\n";
        $pdo->exec($sql);
        echo " -> OK\n";
        $successCount++;
    } catch (Throwable $e) {
        $msg = $e->getMessage();
        if (strpos($msg, 'Duplicate key name') !== false) {
            echo " -> Skipped (Index already exists)\n";
        } else {
            echo " -> Error: " . $msg . "\n";
        }
    }
}

echo "\nOptimization complete. Applied/Verified $successCount indexes.\n";
