<?php
/**
 * lib/installer.php — Clean install. Creates full schema, default admin, sports ON.
 */

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/themes.php';

function column_exists(PDO $pdo, string $table, string $column): bool
{
    $stmt = $pdo->query('PRAGMA table_info(' . $table . ')');
    foreach ($stmt->fetchAll() as $col) {
        if (($col['name'] ?? '') === $column) {
            return true;
        }
    }
    return false;
}

const CORE_TABLES = [
    'admins', 'devices', 'dns', 'playlists', 'settings',
    'languages', 'activation_codes', 'credentials',
    'leagues', 'sport_events', 'menu_ads', 'vpn_servers',
];

function is_installed(PDO $pdo): bool
{
    $placeholders = implode(',', array_fill(0, count(CORE_TABLES), '?'));
    $stmt = $pdo->prepare(
        "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ($placeholders)"
    );
    $stmt->execute(CORE_TABLES);
    return (int) $stmt->fetchColumn() === count(CORE_TABLES);
}

function run_install(PDO $pdo): array
{
    $log = [];
    $step = function (string $msg) use (&$log): void {
        $log[] = $msg;
    };

    $schemaPath = __DIR__ . '/schema.sql';
    if (!is_readable($schemaPath)) {
        throw new RuntimeException('Cannot read lib/schema.sql');
    }
    $schema = file_get_contents($schemaPath);
    if ($schema === false) {
        throw new RuntimeException('Cannot read schema content');
    }
    $pdo->exec($schema);
    $step('Schema applied.');

    // Safety migrations if an older partial DB already exists
    $migrations = [
        ['devices', 'registered',    'INTEGER NOT NULL DEFAULT 0'],
        ['devices', 'locked',        'INTEGER NOT NULL DEFAULT 0'],
        ['devices', 'created_at',    'TEXT'],
        ['devices', 'account_name',  'TEXT'],
        ['leagues', 'created_at',    'TEXT'],
        ['leagues', 'sport_type',    "TEXT NOT NULL DEFAULT 'soccer'"],
        ['sport_events', 'created_at',   'TEXT'],
        ['sport_events', 'sport_type',   "TEXT NOT NULL DEFAULT 'soccer'"],
        ['sport_events', 'sort',         'INTEGER NOT NULL DEFAULT 0'],
        ['sport_events', 'home_badge',   "TEXT DEFAULT ''"],
        ['sport_events', 'away_badge',   "TEXT DEFAULT ''"],
        ['sport_events', 'league_badge', "TEXT DEFAULT ''"],
        ['sport_events', 'status',       "TEXT DEFAULT ''"],
        ['sport_events', 'score',        "TEXT DEFAULT ''"],
        ['sport_events', 'category',     'TEXT'],
        ['sport_events', 'source',       'TEXT'],
        ['sport_events', 'ext_id',       'TEXT'],
        ['dns', 'created_at', 'TEXT'],
        ['menu_ads', 'created_at', 'TEXT'],
    ];
    foreach ($migrations as [$table, $col, $type]) {
        if (!column_exists($pdo, $table, $col)) {
            try {
                $pdo->exec("ALTER TABLE $table ADD COLUMN $col $type");
                $step("Added $table.$col");
            } catch (Throwable $e) {
                $step("Skip $table.$col: " . $e->getMessage());
            }
        }
    }

    $pdo->exec('CREATE INDEX IF NOT EXISTS idx_playlists_userpass ON playlists(username, password)');

    // Default admin
    $count = (int) $pdo->query('SELECT COUNT(*) FROM admins')->fetchColumn();
    if ($count === 0) {
        $stmt = $pdo->prepare(
            'INSERT INTO admins (username, password_hash, created_at) VALUES (?, ?, ?)'
        );
        $stmt->execute(['admin', password_hash('admin', PASSWORD_DEFAULT), now_iso()]);
        $step('Default admin: admin / admin');
        $step('⚠ Change this password after first login.');
    } else {
        $step('Admin already exists.');
    }

    // Defaults — sports ENABLED
    $defaultSettings = [
        'default_theme'       => '5',
        'default_login_theme' => '5',
        'app_version'         => '1.0',
        'apk_url'             => '',
        'def_login_title'     => 'Welcome',
        'def_login_content'   => 'Upload your playlist to start',
        'def_noti_title'      => '',
        'def_noti_content'    => '',
        'tmdb_api_key'        => 'b24683ba85cd4503335347d3785ddab7',
        'demo_dns_id'         => '0',
        'demo_url'            => '',
        'demo_username'       => '',
        'demo_password'       => '',
        'demo_name'           => 'Demo',
        'support_message_one' => '',
        'support_message_two' => '',
        'sport_enabled'       => '1',
        'sport_header'        => 'Sports',
        'sport_border'        => '#000000',
        'sport_background'    => '#000000',
        'sport_text'          => '#ffffff',
        'sport_days'          => '270',
        'sport_last_import'   => '0',
    ];
    $ins = $pdo->prepare('INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)');
    $seeded = 0;
    foreach ($defaultSettings as $key => $value) {
        $ins->execute([$key, $value]);
        if ($ins->rowCount() > 0) {
            $seeded++;
        }
    }
    $step("Settings seeded ($seeded new).");
    $pdo->prepare("UPDATE settings SET value = '1' WHERE key = 'sport_enabled'")->execute();
    $pdo->prepare("UPDATE settings SET value = '270' WHERE key = 'sport_days'")->execute();
    $step('Sports enabled (sport_enabled=1, sport_days=270).');

    $languages = [
        'en' => 'English', 'es' => 'Español', 'fr' => 'Français',
        'pt' => 'Português', 'ar' => 'العربية', 'de' => 'Deutsch', 'it' => 'Italiano',
    ];
    $insLang = $pdo->prepare('INSERT OR IGNORE INTO languages (code, name, enabled) VALUES (?, ?, 1)');
    $langSeeded = 0;
    foreach ($languages as $code => $name) {
        $insLang->execute([$code, $name]);
        if ($insLang->rowCount() > 0) {
            $langSeeded++;
        }
    }
    $step("Languages seeded ($langSeeded new).");

    $step('');
    $step('✔ Clean install complete.');
    $step('Next: add leagues in sports.php, then open api/sports.php a few times to import events.');
    return $log;
}

function ensure_installed(PDO $pdo): bool
{
    if (is_installed($pdo)) {
        return false;
    }
    run_install($pdo);
    return true;
}
