<?php
/**
 * Game Launch Handler
 * Production Ready — With Full Logging
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);
session_start();

require '../includes/db.php';

// ============================================================
// LOGGING SETUP
// ============================================================

define('LAUNCH_LOG', __DIR__ . '/../logs/launch_log.txt');

function launch_log(string $level, string $message, array $context = []): void
{
    $dir = dirname(LAUNCH_LOG);
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }

    $time    = date('Y-m-d h:i:s A');
    $context = !empty($context) ? ' | ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
    $line    = "[$time] [$level] $message$context" . PHP_EOL;

    file_put_contents(LAUNCH_LOG, $line, FILE_APPEND | LOCK_EX);
}

// ============================================================
// Authentication
// ============================================================

if (!isset($_SESSION['user_id'])) {
    launch_log('WARN', 'Unauthenticated access attempt', [
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
    ]);
    header("Location: /login.php");
    exit;
}

if (empty($_GET['game_id'])) {
    launch_log('WARN', 'Game ID missing in request', [
        'user_id' => $_SESSION['user_id'],
        'ip'      => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
    ]);
    http_response_code(400);
    die("Game ID missing.");
}

$user_id  = (int) $_SESSION['user_id'];
$game_uid = trim($_GET['game_id']);

launch_log('INFO', 'Game launch initiated', [
    'user_id'  => $user_id,
    'game_uid' => $game_uid,
    'ip'       => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
]);

// ============================================================
// Fetch Game Details
// ============================================================

$stmt = $conn->prepare("SELECT game_uid, name FROM games WHERE game_uid = ? LIMIT 1");
$stmt->bind_param("s", $game_uid);
$stmt->execute();
$game = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$game) {
    launch_log('ERROR', 'Game not found in DB', [
        'user_id'  => $user_id,
        'game_uid' => $game_uid,
    ]);
    http_response_code(404);
    die("Game not found.");
}

launch_log('INFO', 'Game found', ['game_name' => $game['name'], 'game_uid' => $game['game_uid']]);

// ============================================================
// Fetch User Balance
// ============================================================

$stmt = $conn->prepare("SELECT balance FROM users WHERE id = ? LIMIT 1");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$user) {
    launch_log('ERROR', 'User not found in DB', ['user_id' => $user_id]);
    http_response_code(403);
    die("User not found. Please login again.");
}

$real_balance = bcadd((string)$user['balance'], '0', 2);
launch_log('INFO', 'User balance fetched', ['user_id' => $user_id, 'balance' => (string)$real_balance]);

// ============================================================
// Load API Settings
// ============================================================

$settings = [];
$result   = $conn->query("SELECT setting_key, setting_value FROM game_settings");
while ($row = $result->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$TOKEN      = trim($settings['api_token']     ?? '');
$SECRET     = trim($settings['secret_key']    ?? '');
$SERVER_URL = rtrim($settings['api_endpoint'] ?? '', '/');

if (empty($TOKEN) || empty($SECRET) || empty($SERVER_URL)) {
    launch_log('ERROR', 'API settings missing or incomplete', [
        'has_token'    => !empty($TOKEN),
        'has_secret'   => !empty($SECRET),
        'has_endpoint' => !empty($SERVER_URL),
    ]);
    http_response_code(500);
    die("Game configuration error. Please contact support.");
}

// ============================================================
// Build URLs
// ============================================================

$protocol     = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host         = $_SERVER['HTTP_HOST'];
$RETURN_URL   = "$protocol://$host/index.php";
$CALLBACK_URL = "$protocol://$host/api/callback.php";

// ============================================================
// Build Payload
// ============================================================

$payload = [
    'user_id'       => (string) $user_id,
    'balance' => $real_balance,
    'game_uid'      => $game['game_uid'],
    'token'         => $TOKEN,
    'timestamp'     => (int) round(microtime(true) * 1000),
    'return'        => $RETURN_URL,
    'return_url'    => $RETURN_URL,
    'callback'      => $CALLBACK_URL,
    'callback_url'  => $CALLBACK_URL,
    'currency_code' => 'BDT',
    'language'      => 'en',
];

launch_log('INFO', 'Payload built', [
    'user_id'      => $user_id,
    'game_uid'     => $game['game_uid'],
    'balance'      => $real_balance,
    'callback_url' => $CALLBACK_URL,
]);

// ============================================================
// Encrypt Payload — AES-256-ECB
// ============================================================

function encrypt_payload(array $data, string $key): string
{
    $json      = json_encode($data);
    $encrypted = openssl_encrypt($json, 'AES-256-ECB', $key, OPENSSL_RAW_DATA);
    return base64_encode($encrypted);
}

$encrypted_payload = encrypt_payload($payload, $SECRET);
$request_url       = $SERVER_URL . '?payload=' . urlencode($encrypted_payload) . '&token=' . urlencode($TOKEN);

launch_log('INFO', 'Sending request to API', ['endpoint' => $SERVER_URL]);

// ============================================================
// Call Game API
// ============================================================

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $request_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_USERAGENT      => 'Mozilla/5.0',
]);

$start_time = microtime(true);
$response   = curl_exec($ch);
$elapsed    = round((microtime(true) - $start_time) * 1000); // ms
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
$http_code  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($curl_errno) {
    launch_log('ERROR', 'cURL request failed', [
        'user_id'    => $user_id,
        'game_uid'   => $game_uid,
        'curl_errno' => $curl_errno,
        'curl_error' => $curl_error,
        'elapsed_ms' => $elapsed,
    ]);
    http_response_code(502);
    die("Game server connection failed. Please try again.");
}

launch_log('INFO', 'API response received', [
    'http_code'  => $http_code,
    'elapsed_ms' => $elapsed,
    'response'   => $response,
]);

// ============================================================
// Parse API Response
// ============================================================

$api_response = json_decode($response, true);

if (isset($api_response['code']) && $api_response['code'] == 0 && !empty($api_response['data']['url'])) {
    $game_url = $api_response['data']['url'];
} elseif (!empty($api_response['url'])) {
    $game_url = $api_response['url'];
} else {
    launch_log('ERROR', 'Invalid API response — game URL missing', [
        'user_id'      => $user_id,
        'game_uid'     => $game_uid,
        'http_code'    => $http_code,
        'api_response' => $api_response,
    ]);
    http_response_code(502);
    die("Failed to launch game. Please try again later.");
}

launch_log('INFO', 'Game launched successfully', [
    'user_id'  => $user_id,
    'game_uid' => $game_uid,
    'game_url' => $game_url,
]);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Playing <?php echo htmlspecialchars($game['name']); ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        html, body { width: 100%; height: 100%; overflow: hidden; background: #000; font-family: sans-serif; }
        iframe { display: block; width: 100%; height: 100%; border: none; }

        /* ── Assistive Touch ── */
        #assistive-touch {
            position: fixed;
            top: 20px;
            right: 20px;
            width: 50px;
            height: 50px;
            z-index: 10000;
            touch-action: none;
        }
        .float-btn {
            width: 100%; height: 100%;
            border-radius: 50%;
            background: #3b4c46;
            border: 2px solid #ffdf1b;
            color: #ffdf1b;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22px;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(0,0,0,0.5);
            transition: all 0.3s ease;
        }
        .float-btn:active { transform: scale(0.9); }
        .menu-options {
            position: absolute;
            top: 60px;
            left: 50%;
            transform: translateX(-50%) scale(0);
            display: flex;
            flex-direction: column;
            gap: 10px;
            transition: all 0.3s cubic-bezier(0.68, -0.55, 0.27, 1.55);
            transform-origin: top center;
            opacity: 0;
            pointer-events: none;
        }
        #assistive-touch.active .menu-options {
            transform: translateX(-50%) scale(1);
            opacity: 1;
            pointer-events: auto;
        }
        #assistive-touch.active .float-btn {
            background: #ffdf1b;
            color: #123628;
            transform: rotate(45deg);
        }
        .sub-btn {
            width: 40px; height: 40px;
            border-radius: 50%;
            border: none;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            cursor: pointer;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
            transition: transform 0.2s;
        }
        .sub-btn:hover { transform: scale(1.1); }
        .btn-home   { background: #ef4444; }
        .btn-full   { background: #137a5a; }
        .btn-reload { background: #3b82f6; }

        /* ── Exit Modal ── */
        #exitModal {
            display: none;
            position: fixed;
            inset: 0;
            z-index: 10002;
            background: rgba(0,0,0,0.8);
            backdrop-filter: blur(4px);
            align-items: center;
            justify-content: center;
            padding: 16px;
        }
        #exitModal.show { display: flex; }
        .modal-box {
            background: #273832;
            width: 100%;
            max-width: 360px;
            border-radius: 16px;
            border: 1px solid #137a5a;
            box-shadow: 0 20px 60px rgba(0,0,0,0.5);
            padding: 28px 24px 24px;
            position: relative;
            text-align: center;
        }
        .modal-close {
            position: absolute;
            top: 12px; right: 14px;
            background: none; border: none;
            color: #137a5a; font-size: 18px;
            cursor: pointer; transition: color 0.2s;
        }
        .modal-close:hover { color: #ffdf1b; }
        .modal-icon {
            width: 64px; height: 64px;
            background: #3b4c46;
            border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            margin: 0 auto 16px;
            border: 1px solid #137a5a;
            font-size: 28px; color: #ffdf1b;
        }
        .modal-title { color: #fff; font-size: 20px; font-weight: 700; margin-bottom: 8px; }
        .modal-desc  { color: #9ca3af; font-size: 13px; margin-bottom: 24px; }
        .modal-actions { display: flex; gap: 12px; }
        .btn-cancel {
            flex: 1; padding: 10px;
            border-radius: 10px;
            border: 1px solid #137a5a;
            background: transparent;
            color: #d1d5db; font-weight: 700; font-size: 14px;
            cursor: pointer; transition: background 0.2s;
        }
        .btn-cancel:hover { background: #3b4c46; }
        .btn-exit {
            flex: 1; padding: 10px;
            border-radius: 10px;
            border: none;
            background: #ffdf1b;
            color: #123628; font-weight: 700; font-size: 14px;
            cursor: pointer; transition: background 0.2s, transform 0.2s;
        }
        .btn-exit:hover { background: #eacb15; transform: translateY(-1px); }
    </style>
</head>
<body>

    <iframe id="game-frame"
        src="<?php echo htmlspecialchars($game_url); ?>"
        allowfullscreen
        allow="autoplay; fullscreen">
    </iframe>

    <!-- Floating Menu -->
    <div id="assistive-touch">
        <div class="float-btn" id="main-btn">
            <i class="fas fa-plus"></i>
        </div>
        <div class="menu-options">
            <button class="sub-btn btn-full"   onclick="toggleFullscreen()" title="Fullscreen">
                <i class="fas fa-expand"></i>
            </button>
            <button class="sub-btn btn-reload" onclick="reloadGame()" title="Reload">
                <i class="fas fa-sync-alt"></i>
            </button>
            <button class="sub-btn btn-home"   onclick="openExitModal()" title="Exit">
                <i class="fas fa-sign-out-alt"></i>
            </button>
        </div>
    </div>

    <!-- Exit Modal -->
    <div id="exitModal">
        <div class="modal-box">
            <button class="modal-close" onclick="closeExitModal()">
                <i class="fas fa-times"></i>
            </button>
            <div class="modal-icon">
                <i class="fas fa-sign-out-alt"></i>
            </div>
            <p class="modal-title">Exit Game?</p>
            <p class="modal-desc">Are you sure you want to leave? Your progress is saved automatically.</p>
            <div class="modal-actions">
                <button class="btn-cancel" onclick="closeExitModal()">Cancel</button>
                <button class="btn-exit"   onclick="confirmExit()">Yes, Exit</button>
            </div>
        </div>
    </div>

    <script>
        // ── Draggable Floating Button ──
        const dragEl  = document.getElementById('assistive-touch');
        const mainBtn = document.getElementById('main-btn');

        let isDragging = false;
        let startX, startY, origX, origY;

        function getPos(e) {
            return e.touches ? { x: e.touches[0].clientX, y: e.touches[0].clientY }
                             : { x: e.clientX,             y: e.clientY };
        }

        dragEl.addEventListener('mousedown',  onStart, false);
        dragEl.addEventListener('touchstart', onStart, { passive: false });
        document.addEventListener('mousemove', onMove, false);
        document.addEventListener('touchmove', onMove, { passive: false });
        document.addEventListener('mouseup',  onEnd, false);
        document.addEventListener('touchend', onEnd, false);

        function onStart(e) {
            const pos  = getPos(e);
            const rect = dragEl.getBoundingClientRect();
            startX = pos.x;
            startY = pos.y;
            origX  = rect.left;
            origY  = rect.top;
            isDragging = false;
        }

        function onMove(e) {
            if (startX === undefined) return;
            const pos = getPos(e);
            const dx  = pos.x - startX;
            const dy  = pos.y - startY;

            if (Math.abs(dx) > 5 || Math.abs(dy) > 5) {
                isDragging = true;
                e.preventDefault();
                const newX = Math.min(Math.max(origX + dx, 0), window.innerWidth  - dragEl.offsetWidth);
                const newY = Math.min(Math.max(origY + dy, 0), window.innerHeight - dragEl.offsetHeight);
                dragEl.style.left   = newX + 'px';
                dragEl.style.top    = newY + 'px';
                dragEl.style.right  = 'auto';
                dragEl.style.bottom = 'auto';
            }
        }

        function onEnd() { startX = undefined; }

        mainBtn.addEventListener('click', () => {
            if (!isDragging) dragEl.classList.toggle('active');
            isDragging = false;
        });

        document.addEventListener('click', (e) => {
            if (!dragEl.contains(e.target)) dragEl.classList.remove('active');
        });

        // ── Game Actions ──
        function reloadGame()      { document.getElementById('game-frame').src += ''; }
        function toggleFullscreen() {
            if (!document.fullscreenElement) document.documentElement.requestFullscreen().catch(() => {});
            else document.exitFullscreen().catch(() => {});
        }
        function openExitModal()  { document.getElementById('exitModal').classList.add('show'); }
        function closeExitModal() { document.getElementById('exitModal').classList.remove('show'); }
        function confirmExit()    { window.location.href = '/index.php'; }

        document.getElementById('exitModal').addEventListener('click', function(e) {
            if (e.target === this) closeExitModal();
        });

        window.addEventListener('resize', () => {
            dragEl.style.cssText = 'top: 20px; right: 20px; left: auto; bottom: auto;';
        });
    </script>

</body>
</html>