<?php
declare(strict_types=1);
/**
 * fix_db.php — FINAL FIX
 * https://ludoking.gamingserver.win/fix_db.php
 * DELETE after running!
 */
require_once __DIR__ . '/db.php';

header('Content-Type: application/json; charset=utf-8');

$pdo = lk_pdo();
$results = [];
$allOk = true;

$apiKey    = 'XpY2GAXeKJwxSqF87BbPzD68Woy5trj8iKS1PPM';
$apiSecret = '182ae519c6143236c8e071579986195fe94e4d267c4390c767c78d58496a6c34';
$passHash  = '$2y$10$bMN.b/PHA3m2pcAvQG7cT.HYBOuY2TzPUQ85UcNIzAzWrPMyJGTsS';

// 1. Update TopGamingBD user's api_secret_hash
try {
    $st = $pdo->prepare("SELECT id, api_key, api_secret_hash FROM users WHERE api_key=? LIMIT 1");
    $st->execute([$apiKey]);
    $user = $st->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        $pdo->prepare("UPDATE users SET api_secret_hash=?, api_secret_last4=? WHERE api_key=?")
            ->execute([$apiSecret, substr($apiSecret,-4), $apiKey]);
        $results[] = '✅ Updated TopGamingBD api_secret_hash';
    } else {
        // Try first user
        $first = $pdo->query("SELECT id FROM users ORDER BY id ASC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($first) {
            $pdo->prepare("UPDATE users SET api_key=?, api_secret_hash=?, api_secret_last4=? WHERE id=?")
                ->execute([$apiKey, $apiSecret, substr($apiSecret,-4), (int)$first['id']]);
            $results[] = '✅ Updated user id='.$first['id'].' with TopGamingBD credentials';
        } else {
            $results[] = '⚠ No users found in DB!';
            $allOk = false;
        }
    }
} catch (Throwable $e) {
    $results[] = '❌ Update failed: ' . $e->getMessage();
    $allOk = false;
}

// 2. Verify auth
try {
    $st = $pdo->prepare("SELECT id, api_secret_hash FROM users WHERE api_key=? AND is_active=1 LIMIT 1");
    $st->execute([$apiKey]);
    $v = $st->fetch(PDO::FETCH_ASSOC);
    if ($v && hash_equals((string)$v['api_secret_hash'], $apiSecret)) {
        $results[] = '✅ AUTH VERIFY: PASS — room assignment will work!';
    } else {
        $stored = $v ? substr((string)$v['api_secret_hash'], -8) : 'null';
        $results[] = '❌ AUTH VERIFY: FAIL — stored ends: '.$stored.' | expected ends: '.substr($apiSecret,-8);
        $allOk = false;
    }
} catch (Throwable $e) {
    $results[] = '❌ Verify error: ' . $e->getMessage();
    $allOk = false;
}

// 3. Waiting rooms
$waiting = (int)$pdo->query("SELECT COUNT(*) FROM rooms WHERE status='waiting' AND is_assigned=0")->fetchColumn();
$results[] = ($waiting > 0 ? '✅' : '⚠') . " Waiting rooms: $waiting";

// 4. Dry-run assign test
try {
    $pdo->beginTransaction();
    $room = $pdo->query("SELECT id, room_code FROM rooms WHERE is_assigned=0 AND status='waiting' ORDER BY id ASC LIMIT 1 FOR UPDATE")->fetch(PDO::FETCH_ASSOC);
    $pdo->rollBack();
    $results[] = $room
        ? '✅ Assign dry-run OK — would assign: '.$room['room_code']
        : '⚠ No rooms to assign';
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $results[] = '❌ Assign test error: ' . $e->getMessage();
}

echo json_encode([
    'all_ok'  => $allOk,
    'summary' => $allOk ? '🎉 All fixed! DELETE this file now.' : '⚠ Issues remain.',
    'results' => $results,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
