<?php
declare(strict_types=1);

require_once __DIR__ . '/core.php';



function aviator_generator_state_path(): string
{
    return aviator_path('generator_state.json');
}

function aviator_generator_json(array $data, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

function aviator_generator_format($value): string
{
    $n = (float)($value ?? 1.00);
    if ($n < 1.00) {
        $n = 1.00;
    }
    return number_format($n, 2, '.', '');
}

function aviator_generator_read_state(): array
{
    $path = aviator_generator_state_path();
    if (!is_file($path)) {
        return [];
    }
    $data = json_decode((string)file_get_contents($path), true);
    return is_array($data) ? $data : [];
}

function aviator_generator_write_state(array $state): void
{
    $path = aviator_generator_state_path();
    $dir = dirname($path);
    if (!is_dir($dir)) {
        @mkdir($dir, 0777, true);
    }

    $fp = fopen($path, 'c+');
    if (!$fp) {
        throw new RuntimeException('Cannot write generator_state.json. Check data folder permission.');
    }

    flock($fp, LOCK_EX);
    ftruncate($fp, 0);
    rewind($fp);
    fwrite($fp, json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    fflush($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
}

function aviator_generator_game_state(): array
{
    $round = aviator_current_round(true);
    if (!$round) {
        $round = aviator_create_round(true);
    }

    $state = aviator_round_state($round, true);

    return [
        'round_id' => (string)($state['round_id'] ?? ''),
        'raw_status' => (string)($state['status'] ?? 'loading'),
        'server_time' => (int)($state['server_time'] ?? time()),
        'starts_at' => (int)($state['starts_at'] ?? time()),
        'ends_at' => (int)($state['ends_at'] ?? time()),
        'seconds_left' => (int)($state['seconds_left'] ?? 0),
        'crash_value' => aviator_generator_format($state['crash_value'] ?? 1.00),
        'round' => $state,
    ];
}

function aviator_generator_lock_current(): array
{
    $game = aviator_generator_game_state();
    $saved = aviator_generator_read_state();

    $roundId = (string)$game['round_id'];
    $value = aviator_generator_format($game['crash_value'] ?? 1.00);

    if (!$saved || (string)($saved['round_id'] ?? '') !== $roundId) {
        $saved = [
            'round_id' => $roundId,
            'value' => $value,
            'phase' => 'locked_current_round',
            'created_at' => time(),
            'updated_at' => time(),
        ];
        aviator_generator_write_state($saved);
    }

    return [
        'ok' => true,
        'value' => aviator_generator_format($saved['value'] ?? $value),
        'phase' => (string)($saved['phase'] ?? 'locked_current_round'),
        'message' => 'Current signal',
        'game' => $game,
    ];
}

function aviator_generator_create_after_front_crash(string $frontRoundId, $frontCrashPoint = null): array
{
    $game = aviator_generator_game_state();
    $saved = aviator_generator_read_state();

    $savedRoundId = (string)($saved['round_id'] ?? '');
    $currentRoundId = (string)($game['round_id'] ?? '');

    if ($frontRoundId === '') {
        return [
            'ok' => true,
            'value' => aviator_generator_format($saved['value'] ?? $game['crash_value'] ?? 1.00),
            'phase' => 'ignored_empty_round',
            'message' => 'Visual crash ignored: missing round ID.',
            'game' => $game,
        ];
    }

    if ($savedRoundId !== '' && $frontRoundId !== $savedRoundId && $frontRoundId !== $currentRoundId) {
        return [
            'ok' => true,
            'value' => aviator_generator_format($saved['value'] ?? $game['crash_value'] ?? 1.00),
            'phase' => 'ignored_wrong_round',
            'message' => 'Visual crash ignored: round ID does not match current signal.',
            'game' => $game,
        ];
    }

    $lastCrash = aviator_generator_format($frontCrashPoint ?? $game['crash_value'] ?? 1.00);
    aviator_push_history((float)$lastCrash, $frontRoundId);

    $newRound = aviator_create_round(true);
    $newState = aviator_round_state($newRound, true);
    $newValue = aviator_generator_format($newState['crash_value'] ?? 1.00);
    $newRoundId = (string)($newState['round_id'] ?? '');

    $newSaved = [
        'round_id' => $newRoundId,
        'value' => $newValue,
        'phase' => 'new_signal_after_front_visual_crash',
        'created_at' => time(),
        'updated_at' => time(),
        'previous_round_id' => $frontRoundId,
        'previous_crash' => $lastCrash,
    ];
    aviator_generator_write_state($newSaved);

    return [
        'ok' => true,
        'value' => $newValue,
        'phase' => 'new_signal_after_front_visual_crash',
        'message' => 'New signal generated after index.php visual crash.',
        'game' => [
            'round_id' => $newRoundId,
            'raw_status' => (string)($newState['status'] ?? 'loading'),
            'server_time' => (int)($newState['server_time'] ?? time()),
            'starts_at' => (int)($newState['starts_at'] ?? time()),
            'ends_at' => (int)($newState['ends_at'] ?? time()),
            'seconds_left' => (int)($newState['seconds_left'] ?? 0),
            'crash_value' => $newValue,
            'round' => $newState,
        ],
    ];
}

if (isset($_GET['json'])) {
    try {
        if (isset($_GET['reset'])) {
            @unlink(aviator_generator_state_path());
        }

        if (isset($_GET['front_crash'])) {
            aviator_generator_json(aviator_generator_create_after_front_crash(
                (string)($_GET['round_id'] ?? ''),
                $_GET['crash_point'] ?? null
            ));
        }

        aviator_generator_json(aviator_generator_lock_current());
    } catch (Throwable $e) {
        aviator_generator_json([
            'ok' => false,
            'message' => 'Generator error.',
            'error' => $e->getMessage(),
        ], 500);
    }
}

try {
    $initial = aviator_generator_lock_current();
    $initialValue = (string)($initial['value'] ?? '1.00');
    $initialPhase = (string)($initial['phase'] ?? 'waiting');
    $initialMessage = (string)($initial['message'] ?? '');
    $initialGame = is_array($initial['game'] ?? null) ? $initial['game'] : [];
} catch (Throwable $e) {
    $initialValue = '1.00';
    $initialPhase = 'error';
    $initialMessage = $e->getMessage();
    $initialGame = [];
}
?>
<!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>Aviator Signal </title>
<style>
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}body{margin:0;min-height:100vh;background:radial-gradient(circle at top,rgba(225,5,18,.18),transparent 35%),linear-gradient(180deg,#070707,#000);color:#fff;font-family:Arial,sans-serif;display:flex;align-items:center;justify-content:center;padding:18px}.card{width:100%;max-width:560px;background:radial-gradient(circle at 20% 0%,rgba(225,5,18,.16),transparent 38%),#121317;border:1px solid rgba(255,255,255,.08);border-radius:22px;padding:22px;box-shadow:0 20px 60px rgba(0,0,0,.55)}h1{margin:0 0 8px;font-size:24px}.sub{color:#a8adb7;font-size:14px;line-height:1.5;margin:0 0 16px}.signal-box{background:radial-gradient(circle,rgba(225,5,18,.22),rgba(0,0,0,.78) 62%),#050505;border:1px solid rgba(225,5,18,.32);border-radius:20px;text-align:center;padding:28px 14px;margin:16px 0;box-shadow:inset 0 0 28px rgba(0,0,0,.8),0 0 26px rgba(225,5,18,.18)}.label{color:#9ca3af;font-size:13px;margin-bottom:8px}#signalValue{font-size:56px;line-height:1;font-weight:900;color:#fff;text-shadow:0 0 6px rgba(255,255,255,.8),0 0 16px rgba(225,5,18,.8),0 0 36px rgba(225,5,18,.45)}#signalValue.pop{animation:pop .42s ease}@keyframes pop{0%{transform:scale(.86);filter:blur(3px) brightness(1.8)}65%{transform:scale(1.1);filter:blur(0) brightness(1.35)}100%{transform:scale(1);filter:blur(0) brightness(1)}}.status{padding:12px;border-radius:14px;background:rgba(0,0,0,.32);border:1px solid rgba(255,255,255,.07);color:#d1d5db;font-size:14px;line-height:1.45;margin-bottom:10px}.row{display:flex;justify-content:space-between;gap:10px;background:rgba(0,0,0,.28);border-radius:12px;padding:11px 12px;margin-top:8px;font-size:14px}.row span:first-child{color:#8d95a3}.row span:last-child{color:#fff;font-weight:700;text-align:right;word-break:break-all}.links{margin-top:16px;display:flex;gap:10px;flex-wrap:wrap}.links a{color:#fff;background:#e10512;padding:11px 14px;border-radius:12px;text-decoration:none;font-weight:800;font-size:14px}.links a.secondary{background:#24262d;color:#d1d5db}
</style>
</head>
<body>
<div class="card">
    <h1>KING AI</h1>
    <p class="sub"></p>

    <div class="signal-box">
        <div class="label">Current Signal</div>
        <div id="signalValue"><?= aviator_h($initialValue) ?>x</div>
    </div>

    <div class="status" id="statusText"><?= aviator_h($initialMessage) ?></div>

    <div class="row"><span>Phase</span><span id="phaseText"><?= aviator_h($initialPhase) ?></span></div>
    <div class="row"><span>Round ID</span><span id="roundText"><?= aviator_h((string)($initialGame['round_id'] ?? '')) ?></span></div>
    <div class="row"><span>Status</span><span id="statusRoundText"><?= aviator_h((string)($initialGame['raw_status'] ?? '')) ?></span></div>
    <div class="row"><span>Seconds left</span><span id="secondsText"><?= aviator_h((string)($initialGame['seconds_left'] ?? 0)) ?>s</span></div>

    <div class="links">
      
       
        <a class="secondary" href="generator.php?json=1&reset=1" target="_blank">Reset Generator</a>
    </div>
</div>

<script>
(function(){
    const API = "generator.php?json=1";
    const signalValue = document.getElementById("signalValue");
    const statusText = document.getElementById("statusText");
    const phaseText = document.getElementById("phaseText");
    const roundText = document.getElementById("roundText");
    const statusRoundText = document.getElementById("statusRoundText");
    const secondsText = document.getElementById("secondsText");
    let lastValue = signalValue.textContent.replace("x", "").trim();
    let busy = false;

    function fmt(v){
        const n = Number(v);
        return Number.isFinite(n) ? Math.max(1, n).toFixed(2) : "1.00";
    }
    function pop(){
        signalValue.classList.remove("pop");
        void signalValue.offsetWidth;
        signalValue.classList.add("pop");
    }
    async function poll(){
        if (busy) return;
        busy = true;
        try {
            const res = await fetch(API + "&_=" + Date.now(), {cache:"no-store"});
            const data = await res.json();
            if (!data || !data.ok) {
                statusText.textContent = data && data.message ? data.message : "Generator error.";
                busy = false;
                return;
            }
            const value = fmt(data.value);
            if (value !== lastValue) {
                lastValue = value;
                signalValue.textContent = value + "x";
                pop();
            } else {
                signalValue.textContent = lastValue + "x";
            }
            const game = data.game || {};
            statusText.textContent = data.message || "";
            phaseText.textContent = data.phase || "";
            roundText.textContent = game.round_id || "";
            statusRoundText.textContent = game.raw_status || "";
            secondsText.textContent = String(game.seconds_left || 0) + "s";
        } catch (e) {
            statusText.textContent = "Connection lost.";
        }
        busy = false;
    }
    poll();
    setInterval(poll, 900);
})();
</script>
</body>
</html>
