<?php
/**
 * EasyStream Settings Initialization Script
 * Run this once to initialize all admin settings in the database
 */

declare(strict_types=1);

// Include database configuration
require_once __DIR__ . '/f_core/config.database.php';
require_once __DIR__ . '/admin/includes/bootstrap.php';

// Check if running from command line or web
$isCLI = php_sapi_name() === 'cli';

if (!$isCLI) {
    // Web access - check admin authentication
    session_start();
    if (empty($_SESSION['admin_logged_in'])) {
        die('Access denied. Please log in as administrator.');
    }

    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><head><title>Settings Initialization</title>';
    echo '<style>body{font-family:monospace;padding:20px;background:#f5f5f5;}';
    echo 'h1{color:#333;}.success{color:green;}.error{color:red;}.info{color:blue;}</style>';
    echo '</head><body>';
    echo '<h1>EasyStream Settings Initialization</h1>';
}

try {
    // Read SQL file
    $sqlFile = __DIR__ . '/__install/add_admin_settings.sql';

    if (!file_exists($sqlFile)) {
        throw new Exception("SQL file not found: $sqlFile");
    }

    $sql = file_get_contents($sqlFile);

    if ($sql === false) {
        throw new Exception("Failed to read SQL file");
    }

    output('Reading SQL migration file...', 'info');

    // Split SQL into individual statements
    $statements = array_filter(
        array_map('trim', explode(';', $sql)),
        function($stmt) {
            return !empty($stmt) &&
                   !preg_match('/^--/', $stmt) &&
                   !preg_match('/^\/\*/', $stmt);
        }
    );

    output('Found ' . count($statements) . ' SQL statements', 'info');

    // Execute each statement
    $successCount = 0;
    $errorCount = 0;

    foreach ($statements as $statement) {
        $statement = trim($statement);

        if (empty($statement)) {
            continue;
        }

        // Skip comments
        if (preg_match('/^(--|\/\*)/', $statement)) {
            continue;
        }

        try {
            $pdo->exec($statement);
            $successCount++;
        } catch (PDOException $e) {
            // Ignore duplicate key errors (settings already exist)
            if ($e->getCode() !== '23000') {
                output('Error executing statement: ' . $e->getMessage(), 'error');
                $errorCount++;
            } else {
                $successCount++;
            }
        }
    }

    output("\nSettings initialization completed!", 'success');
    output("Successful statements: $successCount", 'success');

    if ($errorCount > 0) {
        output("Errors encountered: $errorCount", 'error');
    }

    // Get total settings count
    $stmt = $pdo->query("SELECT COUNT(*) FROM db_settings");
    $totalSettings = $stmt->fetchColumn();

    output("\nTotal settings in database: $totalSettings", 'info');

    // Show sample settings
    output("\nSample settings:", 'info');
    $stmt = $pdo->query("SELECT cfg_name, cfg_data, cfg_info FROM db_settings LIMIT 10");
    $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($settings as $setting) {
        output("  - {$setting['cfg_name']}: {$setting['cfg_data']} ({$setting['cfg_info']})", 'info');
    }

    output("\nYou can now access the settings panel at: /admin_settings.php", 'success');
    output("\nInitialization completed successfully!", 'success');

    if (!$isCLI) {
        echo '<br><br><a href="/admin_settings.php" style="padding:10px 20px;background:#4CAF50;color:white;text-decoration:none;border-radius:4px;">Go to Settings Panel</a>';
        echo '<br><br><a href="/admin.php" style="padding:10px 20px;background:#2196F3;color:white;text-decoration:none;border-radius:4px;">Back to Dashboard</a>';
    }

} catch (Exception $e) {
    output('FATAL ERROR: ' . $e->getMessage(), 'error');
    output('Trace: ' . $e->getTraceAsString(), 'error');
    exit(1);
}

if (!$isCLI) {
    echo '</body></html>';
}

/**
 * Output formatted message
 */
function output(string $message, string $type = 'info'): void
{
    global $isCLI;

    if ($isCLI) {
        // CLI output
        $prefix = match($type) {
            'success' => '[SUCCESS] ',
            'error' => '[ERROR] ',
            'info' => '[INFO] ',
            default => ''
        };
        echo $prefix . $message . "\n";
    } else {
        // HTML output
        $class = match($type) {
            'success' => 'success',
            'error' => 'error',
            'info' => 'info',
            default => ''
        };
        echo '<div class="' . $class . '">' . htmlspecialchars($message) . '</div>';
    }
}
