<?php
declare(strict_types=1);
/**
 * install.php — One-time database setup for LudoKing Bot Panel
 * Visit: https://ludoking.gamingserver.win/ludoking/install.php
 * Delete or password-protect this file after running!
 */

define('INSTALL_GUARD', true);

// Simple access protection — change this before deploying!
define('INSTALL_PASSWORD', 'lk_install_2024');

$auth  = false;
$msg   = '';
$msgType = 'info';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pass = (string)($_POST['pass'] ?? '');
    if (!hash_equals(INSTALL_PASSWORD, $pass)) {
        $msg = 'Wrong install password.';
        $msgType = 'bad';
    } else {
        $auth = true;
    }
}

// Run install
$results = [];
if ($auth && isset($_POST['run_install'])) {
    require_once __DIR__ . '/db.php';
    $pdo = lk_pdo();

    $tables = [
        'admins' => "
            CREATE TABLE IF NOT EXISTS `admins` (
              `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
              `username` VARCHAR(100) NOT NULL,
              `password_hash` VARCHAR(255) NOT NULL,
              `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
              PRIMARY KEY (`id`),
              UNIQUE KEY `uniq_username` (`username`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ",
        'admin_tokens' => "
            CREATE TABLE IF NOT EXISTS `admin_tokens` (
              `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
              `admin_id` INT UNSIGNED NOT NULL,
              `selector` VARCHAR(64) NOT NULL,
              `token_hash` VARCHAR(128) NOT NULL,
              `ua_hash` VARCHAR(128) NOT NULL DEFAULT '',
              `expires_at` DATETIME NOT NULL,
              `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
              PRIMARY KEY (`id`),
              UNIQUE KEY `uniq_selector` (`selector`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ",
        'users' => "
            CREATE TABLE IF NOT EXISTS `users` (
              `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
              `username` VARCHAR(100) NOT NULL,
              `email` VARCHAR(255) NOT NULL DEFAULT '',
              `password_hash` VARCHAR(255) NOT NULL DEFAULT '',
              `api_key` VARCHAR(64) NOT NULL DEFAULT '',
              `api_secret` VARCHAR(128) NOT NULL DEFAULT '',
              `balance` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
              `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
              PRIMARY KEY (`id`),
              UNIQUE KEY `uniq_api_key` (`api_key`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ",
        'rooms' => "
            CREATE TABLE IF NOT EXISTS `rooms` (
              `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
              `room_code` VARCHAR(50) NOT NULL,
              `instance_id` VARCHAR(100) DEFAULT NULL,
              `host_name` VARCHAR(100) DEFAULT NULL,
              `screenshot_path` VARCHAR(300) DEFAULT NULL,
              `screenshot_expires_at` DATETIME DEFAULT NULL,
              `is_assigned` TINYINT(1) NOT NULL DEFAULT 0,
              `assigned_user_id` INT UNSIGNED DEFAULT NULL,
              `lock_user_id` INT UNSIGNED DEFAULT NULL,
              `lock_until` DATETIME DEFAULT NULL,
              `reserved_user_id` INT UNSIGNED DEFAULT NULL,
              `reserved_until` DATETIME DEFAULT NULL,
              `assigned_at` DATETIME DEFAULT NULL,
              `started_at` DATETIME DEFAULT NULL,
              `closed_at` DATETIME DEFAULT NULL,
              `expires_at` DATETIME DEFAULT NULL,
              `last_assigned_by` VARCHAR(100) DEFAULT NULL,
              `assigned_to` VARCHAR(200) DEFAULT NULL,
              `status` ENUM('waiting','assigned','started','closed') NOT NULL DEFAULT 'waiting',
              `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
              `updated_at` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
              PRIMARY KEY (`id`),
              KEY `idx_status_assigned` (`status`,`is_assigned`),
              KEY `idx_instance` (`instance_id`),
              KEY `idx_expires` (`expires_at`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ",
        'settings' => "
            CREATE TABLE IF NOT EXISTS `settings` (
              `key` VARCHAR(100) NOT NULL,
              `value` TEXT NOT NULL DEFAULT '',
              `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
              PRIMARY KEY (`key`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ",
        'transactions' => "
            CREATE TABLE IF NOT EXISTS `transactions` (
              `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
              `user_id` INT UNSIGNED NOT NULL,
              `type` VARCHAR(50) NOT NULL DEFAULT '',
              `amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
              `balance_before` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
              `balance_after` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
              `note` VARCHAR(500) DEFAULT NULL,
              `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
              PRIMARY KEY (`id`),
              KEY `idx_user` (`user_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ",
    ];

    foreach ($tables as $name => $sql) {
        try {
            $pdo->exec($sql);
            $results[] = ['name' => $name, 'ok' => true, 'msg' => 'Created / already exists'];
        } catch (Throwable $e) {
            $results[] = ['name' => $name, 'ok' => false, 'msg' => $e->getMessage()];
        }
    }

    // Seed default admin if none exists
    try {
        $adminCount = (int)$pdo->query("SELECT COUNT(*) FROM admins")->fetchColumn();
        if ($adminCount === 0) {
            $defaultUser = 'admin';
            $defaultPass = 'admin' . rand(1000, 9999);
            $hash = password_hash($defaultPass, PASSWORD_DEFAULT);
            $pdo->prepare("INSERT INTO admins (username, password_hash) VALUES (?,?)")->execute([$defaultUser, $hash]);
            $results[] = ['name' => 'DEFAULT ADMIN', 'ok' => true, 'msg' => "Username: $defaultUser | Password: $defaultPass  ← SAVE THIS!"];
        }
    } catch (Throwable $e) {
        $results[] = ['name' => 'DEFAULT ADMIN', 'ok' => false, 'msg' => $e->getMessage()];
    }

    // Insert default cron secret
    try {
        $cronSecret = bin2hex(random_bytes(16));
        $pdo->prepare("INSERT IGNORE INTO settings (`key`,`value`) VALUES ('cron_secret',?)")->execute([$cronSecret]);
        $results[] = ['name' => 'CRON SECRET', 'ok' => true, 'msg' => "Cron secret: $cronSecret"];
    } catch (Throwable $e) {}

    // Create default API user (TopGamingBD)
    try {
        $existingUser = $pdo->prepare("SELECT id FROM users WHERE username='TopGamingBD' LIMIT 1");
        $existingUser->execute();
        if (!$existingUser->fetchColumn()) {
            $apiKey    = 'XpY2GAXeKJwxSqF87BbPzD68Woy5trj8iKS1PPM';
            $apiSecret = '182ae519c6143236c8e071579986195fe94e4d267c4390c767c78d58496a6c34';
            $passHash  = password_hash(bin2hex(random_bytes(16)), PASSWORD_DEFAULT);
            $pdo->prepare("INSERT INTO users (username, api_key, api_secret, balance, password_hash) VALUES (?,?,?,1000.00,?)")
                ->execute(['TopGamingBD', $apiKey, $apiSecret, $passHash]);
            $results[] = ['name' => 'API USER TopGamingBD', 'ok' => true, 'msg' => "Key: $apiKey | Secret: $apiSecret"];
        } else {
            $results[] = ['name' => 'API USER TopGamingBD', 'ok' => true, 'msg' => 'Already exists'];
        }
    } catch (Throwable $e) {
        $results[] = ['name' => 'API USER TopGamingBD', 'ok' => false, 'msg' => $e->getMessage()];
    }

    $msg = 'Install complete! See results below.';
    $msgType = 'ok';
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>LudoKing Bot — Install</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{min-height:100dvh;display:flex;align-items:center;justify-content:center;background:#0b1120;font-family:'Inter',sans-serif;color:#e2e8f0;padding:20px;}
.card{background:#111c35;border:1px solid rgba(255,255,255,.08);border-radius:24px;padding:36px 32px;width:100%;max-width:600px;box-shadow:0 32px 80px rgba(0,0,0,.55);}
h1{font-size:22px;font-weight:900;color:#10b981;margin-bottom:8px;}
p{font-size:13px;color:rgba(226,232,240,.6);margin-bottom:24px;line-height:1.6;}
label{display:block;font-size:12px;font-weight:700;color:rgba(226,232,240,.6);margin-bottom:6px;}
input[type=password]{width:100%;padding:12px 16px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);border-radius:12px;color:#e2e8f0;font-size:14px;font-family:inherit;outline:none;}
input[type=password]:focus{border-color:#10b981;}
.btn{width:100%;padding:13px;border:none;border-radius:14px;background:linear-gradient(135deg,#10b981,#059669);color:#fff;font-size:15px;font-weight:900;cursor:pointer;margin-top:18px;}
.msg{padding:12px 16px;border-radius:12px;font-size:13px;font-weight:700;margin-bottom:18px;}
.msg-ok{background:rgba(16,185,129,.12);color:#a7f3d0;border:1px solid rgba(16,185,129,.28);}
.msg-bad{background:rgba(239,68,68,.12);color:#fca5a5;border:1px solid rgba(239,68,68,.28);}
.msg-info{background:rgba(251,191,36,.10);color:#fde68a;border:1px solid rgba(251,191,36,.25);}
.result{margin-top:18px;}
.result-row{display:flex;align-items:flex-start;gap:10px;padding:10px 0;border-bottom:1px solid rgba(255,255,255,.05);font-size:13px;}
.result-row:last-child{border-bottom:none;}
.result-ok{color:#34d399;}
.result-bad{color:#fca5a5;}
.result-name{font-weight:700;min-width:180px;flex-shrink:0;}
.warn{background:rgba(239,68,68,.12);border:1px solid rgba(239,68,68,.25);border-radius:12px;padding:12px 16px;font-size:12px;color:#fca5a5;margin-top:18px;}
</style>
</head>
<body>
<div class="card">
  <h1>♟ LudoKing Bot — Install</h1>
  <p>This will create all required database tables and seed a default admin account. Run once, then delete or restrict access to this file.</p>

  <div class="warn">⚠ Delete or rename this file after installation!</div>

  <?php if ($msg !== ''): ?>
    <div class="msg msg-<?= $msgType ?>" style="margin-top:18px;"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></div>
  <?php endif; ?>

  <?php if (!empty($results)): ?>
  <div class="result">
    <?php foreach ($results as $r): ?>
    <div class="result-row">
      <span class="result-name"><?= htmlspecialchars($r['name'], ENT_QUOTES, 'UTF-8') ?></span>
      <span class="<?= $r['ok'] ? 'result-ok' : 'result-bad' ?>" style="word-break:break-all;">
        <?= $r['ok'] ? '✓' : '✗' ?> <?= htmlspecialchars($r['msg'], ENT_QUOTES, 'UTF-8') ?>
      </span>
    </div>
    <?php endforeach; ?>
  </div>
  <?php if (!empty($results)): ?>
    <div style="margin-top:20px;text-align:center;">
      <a href="/login.php" style="color:#10b981;font-weight:700;font-size:14px;">→ Go to Login</a>
    </div>
  <?php endif; ?>
  <?php endif; ?>

  <?php if (!$auth || empty($results)): ?>
  <form method="post" style="margin-top:20px;">
    <label>Install Password</label>
    <input type="password" name="pass" placeholder="Enter install password" required>
    <?php if ($auth): ?>
      <input type="hidden" name="pass" value="<?= htmlspecialchars((string)($_POST['pass'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
      <button class="btn" name="run_install" value="1" type="submit">Run Install</button>
    <?php else: ?>
      <button class="btn" type="submit">Unlock</button>
    <?php endif; ?>
  </form>
  <?php endif; ?>
</div>
</body>
</html>
