<?php
// CK444.COM installer / repair tool for InfinityFree.
// It creates required tables, repairs old tables, and seeds payment methods/games.
require_once __DIR__ . '/config.php';
if (session_status() === PHP_SESSION_NONE) session_start();
date_default_timezone_set(defined('APP_TIMEZONE') ? APP_TIMEZONE : 'Asia/Dhaka');
header('X-Robots-Tag: noindex, nofollow, noarchive');

$messages = [];
$errors = [];
$ran = false;

function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

// Production safety: do not expose the installer/database repair page to public visitors or crawlers.
function render_installer_lock(string $error = ''): void {
    ?>
    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><meta name="robots" content="noindex,nofollow,noarchive"><title>Protected Installer</title><style>*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;background:#080808;color:#f2f2f2;font-family:Arial,Helvetica,sans-serif;padding:18px}.box{width:min(440px,96vw);background:#111;border:1px solid #292929;border-radius:18px;padding:22px;box-shadow:0 20px 60px rgba(0,0,0,.4)}h1{margin:0 0 8px;color:#7CFC00;font-size:24px}.sub{color:#aaa;line-height:1.5;font-size:14px}.err{background:rgba(255,68,68,.08);border:1px solid rgba(255,68,68,.35);color:#ff8b8b;border-radius:10px;padding:10px;margin:12px 0}input{width:100%;height:46px;border:1px solid #333;background:#0b0b0b;color:#fff;border-radius:12px;padding:0 13px;outline:none;margin:10px 0 14px}button{width:100%;border:0;border-radius:12px;padding:14px;background:linear-gradient(135deg,#5ec900,#7CFC00);font-weight:900;color:#000;cursor:pointer}</style></head><body><div class="box"><h1>Protected Installer</h1><p class="sub">Enter your admin password to open this setup/repair page.</p><?php if($error): ?><div class="err"><?= h($error) ?></div><?php endif; ?><form method="post"><input type="password" name="installer_password" placeholder="Admin password" autocomplete="current-password" required><button type="submit">Unlock Installer</button></form></div></body></html>
    <?php
}
if (empty($_SESSION['installer_ok'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['installer_password'])) {
        if (hash_equals((string)ADMIN_PASSWORD, (string)($_POST['installer_password'] ?? ''))) {
            $_SESSION['installer_ok'] = true;
            header('Location: install.php');
            exit;
        }
        render_installer_lock('Wrong password. Use the ADMIN_PASSWORD from config.php.');
        exit;
    }
    render_installer_lock();
    exit;
}
function install_now_sql(): string { return date('Y-m-d H:i:s'); }
function install_db(): PDO {
    static $pdo = null;
    if ($pdo instanceof PDO) return $pdo;
    if (!defined('DB_HOST') || !defined('DB_NAME') || !defined('DB_USER') || !defined('DB_PASS')) {
        throw new Exception('config.php is missing DB_HOST / DB_NAME / DB_USER / DB_PASS constants.');
    }
    $charset = defined('DB_CHARSET') ? DB_CHARSET : 'utf8mb4';
    $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . $charset;
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => true,
    ]);
    $pdo->exec('SET NAMES ' . $charset);
    return $pdo;
}
function table_exists(string $table): bool {
    $stmt = install_db()->prepare('SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?');
    $stmt->execute([$table]);
    return (int)$stmt->fetchColumn() > 0;
}
function column_exists(string $table, string $column): bool {
    $stmt = install_db()->prepare('SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?');
    $stmt->execute([$table, $column]);
    return (int)$stmt->fetchColumn() > 0;
}
function ensure_column(string $table, string $column, string $definition, array &$messages): void {
    if (!table_exists($table)) return;
    if (!column_exists($table, $column)) {
        install_db()->exec('ALTER TABLE `' . str_replace('`','',$table) . '` ADD COLUMN ' . $definition);
        $messages[] = "Added missing column {$table}.{$column}";
    }
}
function run_sql_file(string $file, array &$messages): void {
    if (!file_exists($file)) throw new Exception('database.sql file not found.');
    $sql = file_get_contents($file);
    $sql = preg_replace('/^\s*--.*$/m', '', $sql);
    $sql = trim($sql);
    $statements = preg_split('/;\s*(?:\r?\n|$)/', $sql);
    $count = 0;
    foreach ($statements as $stmt) {
        $stmt = trim($stmt);
        if ($stmt === '') continue;
        install_db()->exec($stmt);
        $count++;
    }
    $messages[] = "Database tables checked ({$count} SQL statements).";
}
function setting_set(string $key, string $value): void {
    install_db()->prepare('INSERT INTO settings(setting_key,setting_value,updated_at) VALUES(?,?,?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value), updated_at=VALUES(updated_at)')
        ->execute([$key, $value, install_now_sql()]);
}
function migrate_old_tables(array &$messages): void {
    // Old CK444.COM used app_config. Copy it into new settings if available.
    if (table_exists('app_config') && table_exists('settings')) {
        install_db()->exec("INSERT INTO settings(setting_key,setting_value,updated_at)
            SELECT cfg_key,cfg_value,COALESCE(updated_at,NOW()) FROM app_config
            ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value), updated_at=VALUES(updated_at)");
        $messages[] = 'Copied old app_config values into settings.';
    }

    // Repair old users table so the new SQL app can read it.
    ensure_column('users','email',"email VARCHAR(190) DEFAULT NULL",$messages);
    ensure_column('users','password_hash',"password_hash VARCHAR(255) NULL",$messages);
    ensure_column('users','country_code',"country_code VARCHAR(10) NOT NULL DEFAULT 'BD'",$messages);
    ensure_column('users','country_name',"country_name VARCHAR(80) NOT NULL DEFAULT 'Bangladesh'",$messages);
    ensure_column('users','dial_code',"dial_code VARCHAR(10) NOT NULL DEFAULT '+880'",$messages);
    ensure_column('users','balance',"balance DECIMAL(14,2) NOT NULL DEFAULT 0",$messages);
    ensure_column('users','bonus',"bonus DECIMAL(14,2) NOT NULL DEFAULT 0",$messages);
    ensure_column('users','safe_income',"safe_income DECIMAL(14,2) NOT NULL DEFAULT 0",$messages);
    ensure_column('users','status',"status VARCHAR(30) NOT NULL DEFAULT 'active'",$messages);
    ensure_column('users','avatar',"avatar VARCHAR(20) DEFAULT ''",$messages);
    ensure_column('users','invite_code',"invite_code VARCHAR(60) DEFAULT ''",$messages);
    ensure_column('users','referral_code',"referral_code VARCHAR(60) DEFAULT ''",$messages);
    ensure_column('users','created_at',"created_at DATETIME NULL",$messages);
    ensure_column('users','last_login',"last_login DATETIME NULL",$messages);
    if (table_exists('users')) {
        if (column_exists('users','password')) {
            install_db()->exec("UPDATE users SET password_hash = password WHERE (password_hash IS NULL OR password_hash='') AND password IS NOT NULL AND password<>''");
            $messages[] = 'Migrated old users.password into users.password_hash.';
        }
        if (column_exists('users','my_invite_code')) {
            install_db()->exec("UPDATE users SET invite_code = COALESCE(NULLIF(invite_code,''), NULLIF(my_invite_code,''), id) WHERE invite_code='' OR invite_code IS NULL");
            install_db()->exec("UPDATE users SET referral_code = COALESCE(NULLIF(referral_code,''), NULLIF(my_invite_code,''), id) WHERE referral_code='' OR referral_code IS NULL");
        } else {
            install_db()->exec("UPDATE users SET invite_code = COALESCE(NULLIF(invite_code,''), id) WHERE invite_code='' OR invite_code IS NULL");
            install_db()->exec("UPDATE users SET referral_code = COALESCE(NULLIF(referral_code,''), id) WHERE referral_code='' OR referral_code IS NULL");
        }
        install_db()->exec("UPDATE users SET country_code='PK', country_name='Pakistan', dial_code='+92' WHERE phone LIKE '+92%' OR phone REGEXP '^03[0-9]{9}$' OR country_code IN ('+92','92','PK','Pakistan')");
        install_db()->exec("UPDATE users SET country_code='BD', country_name='Bangladesh', dial_code='+880' WHERE country_code NOT IN ('PK')");
        install_db()->exec("UPDATE users SET created_at=NOW() WHERE created_at IS NULL");
        $messages[] = 'Users table repaired for Bangladesh/Pakistan logic.';
    }

    // Repair payment_methods table if it exists from another version.
    ensure_column('payment_methods','country_code',"country_code VARCHAR(10) NOT NULL DEFAULT 'BD'",$messages);
    ensure_column('payment_methods','method_key',"method_key VARCHAR(60) NOT NULL DEFAULT ''",$messages);
    ensure_column('payment_methods','label',"label VARCHAR(120) NOT NULL DEFAULT ''",$messages);
    ensure_column('payment_methods','provider',"provider VARCHAR(120) DEFAULT ''",$messages);
    ensure_column('payment_methods','wallet_number',"wallet_number VARCHAR(190) NOT NULL DEFAULT ''",$messages);
    ensure_column('payment_methods','instructions',"instructions TEXT NULL",$messages);
    ensure_column('payment_methods','active',"active TINYINT(1) NOT NULL DEFAULT 1",$messages);
    ensure_column('payment_methods','sort_order',"sort_order INT NOT NULL DEFAULT 0",$messages);
    ensure_column('payment_methods','created_at',"created_at DATETIME NULL",$messages);
    if (table_exists('payment_methods')) {
        install_db()->exec("UPDATE payment_methods SET country_code='BD' WHERE country_code IN ('+880','880','Bangladesh','') OR country_code IS NULL");
        install_db()->exec("UPDATE payment_methods SET country_code='PK' WHERE country_code IN ('+92','92','Pakistan')");
        install_db()->exec("UPDATE payment_methods SET created_at=NOW() WHERE created_at IS NULL");
    }

    // Repair games table if it exists from another version.
    ensure_column('games','title',"title VARCHAR(160) NOT NULL DEFAULT ''",$messages);
    ensure_column('games','icon',"icon VARCHAR(20) DEFAULT '🎮'",$messages);
    ensure_column('games','provider',"provider VARCHAR(100) DEFAULT ''",$messages);
    ensure_column('games','category',"category VARCHAR(60) NOT NULL DEFAULT 'slots'",$messages);
    ensure_column('games','image_url',"image_url VARCHAR(500) DEFAULT ''",$messages);
    ensure_column('games','game_url',"game_url VARCHAR(500) DEFAULT ''",$messages);
    ensure_column('games','is_hot',"is_hot TINYINT(1) NOT NULL DEFAULT 1",$messages);
    ensure_column('games','active',"active TINYINT(1) NOT NULL DEFAULT 1",$messages);
    ensure_column('games','sort_order',"sort_order INT NOT NULL DEFAULT 0",$messages);
    ensure_column('games','created_at',"created_at DATETIME NULL",$messages);
    if (table_exists('games')) install_db()->exec("UPDATE games SET created_at=NOW() WHERE created_at IS NULL");

    // Repair old deposit_requests table.
    ensure_column('deposit_requests','phone',"phone VARCHAR(40) NOT NULL DEFAULT ''",$messages);
    ensure_column('deposit_requests','country_code',"country_code VARCHAR(10) NOT NULL DEFAULT 'BD'",$messages);
    ensure_column('deposit_requests','method_id',"method_id INT UNSIGNED NULL",$messages);
    ensure_column('deposit_requests','method_key',"method_key VARCHAR(60) NOT NULL DEFAULT ''",$messages);
    ensure_column('deposit_requests','method_label',"method_label VARCHAR(120) NOT NULL DEFAULT ''",$messages);
    ensure_column('deposit_requests','wallet_number',"wallet_number VARCHAR(190) NOT NULL DEFAULT ''",$messages);
    ensure_column('deposit_requests','trxid',"trxid VARCHAR(160) NOT NULL DEFAULT ''",$messages);
    ensure_column('deposit_requests','status',"status VARCHAR(40) NOT NULL DEFAULT 'pending'",$messages);
    ensure_column('deposit_requests','admin_note',"admin_note TEXT NULL",$messages);
    ensure_column('deposit_requests','reviewed_at',"reviewed_at DATETIME NULL",$messages);
    if (table_exists('deposit_requests')) {
        if (column_exists('deposit_requests','method')) install_db()->exec("UPDATE deposit_requests SET method_key = method WHERE (method_key='' OR method_key IS NULL) AND method IS NOT NULL AND method<>''");
        if (column_exists('deposit_requests','channel_label')) install_db()->exec("UPDATE deposit_requests SET method_label = channel_label WHERE (method_label='' OR method_label IS NULL) AND channel_label IS NOT NULL AND channel_label<>''");
        if (column_exists('deposit_requests','wallet')) install_db()->exec("UPDATE deposit_requests SET wallet_number = wallet WHERE (wallet_number='' OR wallet_number IS NULL) AND wallet IS NOT NULL AND wallet<>''");
        install_db()->exec("UPDATE deposit_requests d LEFT JOIN users u ON u.id=d.user_id SET d.country_code=COALESCE(u.country_code,'BD') WHERE d.country_code='' OR d.country_code IS NULL");
        install_db()->exec("UPDATE deposit_requests SET method_label=method_key WHERE method_label='' OR method_label IS NULL");
        $messages[] = 'Deposit request table repaired.';
    }

    // Repair old withdraw_requests table.
    ensure_column('withdraw_requests','country_code',"country_code VARCHAR(10) NOT NULL DEFAULT 'BD'",$messages);
    ensure_column('withdraw_requests','method_key',"method_key VARCHAR(60) NOT NULL DEFAULT ''",$messages);
    ensure_column('withdraw_requests','method_label',"method_label VARCHAR(120) NOT NULL DEFAULT ''",$messages);
    ensure_column('withdraw_requests','full_name',"full_name VARCHAR(190) NOT NULL DEFAULT ''",$messages);
    ensure_column('withdraw_requests','account_number',"account_number VARCHAR(190) NOT NULL DEFAULT ''",$messages);
    ensure_column('withdraw_requests','fee',"fee DECIMAL(14,2) NOT NULL DEFAULT 0",$messages);
    ensure_column('withdraw_requests','status',"status VARCHAR(40) NOT NULL DEFAULT 'pending'",$messages);
    ensure_column('withdraw_requests','admin_note',"admin_note TEXT NULL",$messages);
    ensure_column('withdraw_requests','reviewed_at',"reviewed_at DATETIME NULL",$messages);
    if (table_exists('withdraw_requests')) {
        if (column_exists('withdraw_requests','method')) install_db()->exec("UPDATE withdraw_requests SET method_key = method WHERE (method_key='' OR method_key IS NULL) AND method IS NOT NULL AND method<>''");
        if (column_exists('withdraw_requests','account')) install_db()->exec("UPDATE withdraw_requests SET account_number = account WHERE (account_number='' OR account_number IS NULL) AND account IS NOT NULL AND account<>''");
        install_db()->exec("UPDATE withdraw_requests w LEFT JOIN users u ON u.id=w.user_id SET w.country_code=COALESCE(u.country_code,'BD') WHERE w.country_code='' OR w.country_code IS NULL");
        install_db()->exec("UPDATE withdraw_requests SET method_label=method_key WHERE method_label='' OR method_label IS NULL");
        $messages[] = 'Withdraw request table repaired.';
    }
}
function seed_defaults(array &$messages): void {
    setting_set('site_name', defined('SITE_NAME') ? SITE_NAME : 'CK444.COM');
    setting_set('announcement', '🔥 CK444.COM এ স্লট, লাইভ ক্যাসিনো, স্পোর্টস ও Aviator খেলুন। দ্রুত ডিপোজিট, স্মুথ উইথড্র এবং ২৪/৭ সাপোর্ট।');
    setting_set('withdraw_min', '500');
    setting_set('withdraw_max', '25000');
    setting_set('withdraw_fee', '0');
    setting_set('support_url', 'service.php');
    setting_set('aviator_url', '../spribe/');

    if (table_exists('payment_methods')) {
        $seed = [
            ['BD','bkash','bKash Personal','bKash','01740742502','Send Money only',1,10],
            ['BD','nagad','Nagad Personal','Nagad','01740742502','Send Money only',1,20],
            ['BD','rocket','Rocket Personal','Rocket','01740742502','Send Money only',1,30],
            ['BD','bank_bd','Bangladesh Bank Transfer','Bank','Add bank account from admin','Send bank payment and submit transaction ID',1,40],
            ['PK','easypaisa','EasyPaisa','EasyPaisa','03000000000','Send payment and submit transaction ID',1,10],
            ['PK','jazzcash','JazzCash','JazzCash','03000000000','Send payment and submit transaction ID',1,20],
            ['PK','bank_pk','Pakistan Bank Transfer','Bank','Add bank account from admin','Send bank payment and submit transaction ID',1,30],
        ];
        foreach ($seed as $s) {
            $check = install_db()->prepare('SELECT id FROM payment_methods WHERE country_code=? AND method_key=? LIMIT 1');
            $check->execute([$s[0], $s[1]]);
            $id = $check->fetchColumn();
            if ($id) {
                install_db()->prepare('UPDATE payment_methods SET label=?,provider=?,wallet_number=?,instructions=?,active=?,sort_order=? WHERE id=?')
                    ->execute([$s[2],$s[3],$s[4],$s[5],$s[6],$s[7],$id]);
            } else {
                install_db()->prepare('INSERT INTO payment_methods(country_code,method_key,label,provider,wallet_number,instructions,active,sort_order,created_at) VALUES(?,?,?,?,?,?,?,?,?)')
                    ->execute([$s[0],$s[1],$s[2],$s[3],$s[4],$s[5],$s[6],$s[7],install_now_sql()]);
            }
        }
        $messages[] = 'Bangladesh and Pakistan payment methods checked.';
    }

    if (table_exists('games')) {
        $games = [
            ['Super Ace','🎰','JILI','slots','assets/games/super-ace.png','game.php?game=super-ace',1,10],
            ['Aviator','✈️','SPRIBE','crash','assets/games/aviator.png','../spribe/',1,20],
            ['Fortune Tiger','🐯','PG SOFT','slots','assets/games/fortune-tiger.png','game.php?game=fortune-tiger',1,30],
            ['Fortune Gems','💎','JILI','slots','assets/games/fortune-gems.png','game.php?game=fortune-gems',1,40],
            ['Money Tree','🌳','JILI','slots','assets/games/money-tree.png','game.php?game=money-tree',1,50],
            ['Boxing King','🥊','JILI','slots','assets/games/boxing-king.png','game.php?game=boxing-king',1,60],
            ['Go Rush','🚀','JILI','crash','assets/games/go-rush.png','game.php?game=go-rush',1,70],
            ['JILI Provider','🎮','JILI','slots','assets/games/provider-jili.png','game.php?provider=jili',1,80],
            ['PG Soft','🎮','PG SOFT','slots','assets/games/provider-pg-soft.png','game.php?provider=pg-soft',1,90],
            ['PG Games','🎮','PG','slots','assets/games/provider-pg.png','game.php?provider=pg',1,95],
            ['Pragmatic Play','🎮','PRAGMATIC PLAY','slots','assets/games/provider-pragmatic-play.png','game.php?provider=pragmatic-play',1,100],
            ['Evolution Live','🎥','EVOLUTION','casino','assets/games/provider-evolution.png','game.php?provider=evolution',1,110],
            ['INOUT Live','🎥','INOUT','casino','assets/games/provider-inout.png','game.php?provider=inout',1,120],
            ['BGAMING','🎲','BGAMING','casino','assets/games/provider-bgaming.png','game.php?provider=bgaming',1,130],
            ['CQ9 Arcade','🎣','CQ9','fishing','assets/games/provider-cq9.png','game.php?provider=cq9',1,140],
            ['JDB Gaming','🕹️','JDB','casino','assets/games/provider-jdb.png','game.php?provider=jdb',1,150],
            ['Turbo Sports','⚽','TURBO GAMES','sports','assets/games/provider-turbo-games.png','game.php?provider=turbo-games',1,160],
            ['MG Games','🎮','MG','slots','assets/games/provider-mg.png','game.php?provider=mg',1,170],
            ['Mega Slots','🎰','JILI','slots','','game.php?game=mega-slots',1,180],
            ['Lucky Dice','🎲','PG SOFT','casino','','game.php?game=lucky-dice',1,190],
            ['Baccarat','🃏','EVOLUTION','casino','','game.php?game=baccarat',1,200],
            ['Dragon Tiger','🐉','SA GAMING','casino','','game.php?game=dragon-tiger',1,210],
            ['Fishing War','🎣','KA GAMING','fishing','','game.php?game=fishing-war',1,220],
        ];
        foreach ($games as $g) {
            $check = install_db()->prepare('SELECT id FROM games WHERE title=? LIMIT 1');
            $check->execute([$g[0]]);
            $id = $check->fetchColumn();
            if ($id) {
                install_db()->prepare('UPDATE games SET icon=?,provider=?,category=?,image_url=?,game_url=?,is_hot=?,active=1,sort_order=? WHERE id=?')
                    ->execute([$g[1],$g[2],$g[3],$g[4],$g[5],$g[6],$g[7],$id]);
            } else {
                install_db()->prepare('INSERT INTO games(title,icon,provider,category,image_url,game_url,is_hot,sort_order,created_at) VALUES(?,?,?,?,?,?,?,?,?)')
                    ->execute([$g[0],$g[1],$g[2],$g[3],$g[4],$g[5],$g[6],$g[7],install_now_sql()]);
            }
        }
        $messages[] = 'Game list and images checked.';
    }
}
function count_table(string $table): int {
    if (!table_exists($table)) return 0;
    return (int)install_db()->query('SELECT COUNT(*) FROM `' . str_replace('`','',$table) . '`')->fetchColumn();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['run_install'])) {
    $ran = true;
    try {
        install_db()->query('SELECT 1');
        $messages[] = 'Database connection successful.';
        run_sql_file(__DIR__ . '/database.sql', $messages);
        migrate_old_tables($messages);
        seed_defaults($messages);
        $messages[] = 'Install/repair completed successfully.';
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$connectionStatus = 'Not tested yet';
try {
    install_db()->query('SELECT 1');
    $connectionStatus = 'Connected';
} catch (Throwable $e) {
    $connectionStatus = 'Failed: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Install CK444.COM</title>
<meta name="robots" content="noindex,nofollow,noarchive">
<style>
*{box-sizing:border-box}body{margin:0;background:#080808;color:#f2f2f2;font-family:Arial,Helvetica,sans-serif;padding:20px}.box{max-width:900px;margin:0 auto;background:#111;border:1px solid #292929;border-radius:18px;padding:22px;box-shadow:0 20px 60px rgba(0,0,0,.4)}h1{margin:0 0 8px;color:#7CFC00}.sub{color:#999;line-height:1.6}.grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:16px 0}.card{background:#171717;border:1px solid #2b2b2b;border-radius:12px;padding:14px}.k{color:#777;font-size:12px;text-transform:uppercase}.v{margin-top:6px;font-weight:700;word-break:break-all}.ok{background:rgba(124,252,0,.08);border:1px solid rgba(124,252,0,.35);color:#aaff70;border-radius:10px;padding:10px;margin:8px 0}.err{background:rgba(255,68,68,.08);border:1px solid rgba(255,68,68,.35);color:#ff8b8b;border-radius:10px;padding:10px;margin:8px 0}button{width:100%;border:0;border-radius:12px;padding:15px;background:linear-gradient(135deg,#5ec900,#7CFC00);font-weight:900;color:#000;font-size:16px;cursor:pointer}.small{font-size:12px;color:#aaa;line-height:1.7}code{background:#202020;padding:2px 6px;border-radius:5px;color:#7CFC00}@media(max-width:700px){.grid{grid-template-columns:1fr}.box{padding:16px}body{padding:10px}}
</style>
</head>
<body>
<div class="box">
  <h1>CK444.COM Install / Repair</h1>
  <p class="sub">This page connects to the database, creates or repairs tables, and adds payment methods plus games.</p>

  <div class="grid">
    <div class="card"><div class="k">Database config</div><div class="v">Loaded from config.php</div></div>
    <div class="card"><div class="k">Connection status</div><div class="v"><?= h($connectionStatus) ?></div></div>
  </div>

  <?php foreach ($messages as $m): ?><div class="ok">✅ <?= h($m) ?></div><?php endforeach; ?>
  <?php foreach ($errors as $e): ?><div class="err">❌ <?= h($e) ?></div><?php endforeach; ?>

  <form method="post">
    <input type="hidden" name="run_install" value="1">
    <button type="submit">Install / Repair Site Tables</button>
  </form>

  <?php if ($ran && !$errors): ?>
    <div class="ok">Next: open <code>index.php</code>. For security, delete <code>install.php</code> after everything works.</div>
  <?php endif; ?>

  <div class="card" style="margin-top:16px">
    <div class="k">Current table counts</div>
    <p class="small">
      users: <?= h(count_table('users')) ?> / deposit_requests: <?= h(count_table('deposit_requests')) ?> / withdraw_requests: <?= h(count_table('withdraw_requests')) ?> / payment_methods: <?= h(count_table('payment_methods')) ?> / games: <?= h(count_table('games')) ?>
    </p>
    <p class="small">If connection fails, check <code>config.php</code>. If your password changed in InfinityFree, update <code>DB_PASS</code>.</p>
  </div>
</div>
</body>
</html>
