<?php
// /api/v1/markets/index.php
declare(strict_types=1);
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, x-api-key, x-ts, x-sign");

require_once '../../../db.php';
require_once '../../../middleware.php';

// Verify Security
verifyApiRequest();

$today = date('Y-m-d');
$response = ["success" => true, "data" => []];

try {
    // 🎯 Fetch All Active Games
    $gamesQuery = "SELECT * FROM games WHERE is_active = 1 ORDER BY time_open ASC";
    $gamesResult = $db->query($gamesQuery);
    
    $stmtToday = $db->prepare("SELECT open_digits, close_digits FROM results WHERE game_id = ? AND draw_date = ? LIMIT 1");
    $stmtLatest = $db->prepare("SELECT open_digits, close_digits FROM results WHERE game_id = ? AND draw_date < ? ORDER BY draw_date DESC LIMIT 1");
    
    while ($game = $gamesResult->fetch_assoc()) {
        $gameId = (int)$game['game_id'];
        $title = $game['title'] ?? '';
        $alias = $game['alias'] ?? str_replace(' ', '-', strtolower(trim($title)));
        
        // Default empty structure
        $openPanel = "";
        $jodi = "";
        $closePanel = "";
        
        if ($game['is_holiday'] == 0) {
            // Check today's result
            $stmtToday->bind_param("is", $gameId, $today);
            $stmtToday->execute();
            $resToday = $stmtToday->get_result()->fetch_assoc();
            
            if (!$resToday) {
                // Fallback to latest previous result
                $stmtLatest->bind_param("is", $gameId, $today);
                $stmtLatest->execute();
                $resToday = $stmtLatest->get_result()->fetch_assoc();
            }
            
            // Apply exact SAME logic from result.php
            if ($resToday && ($resToday['open_digits'] || $resToday['close_digits'])) {
                $open = $resToday['open_digits'] ?? '';
                $close = $resToday['close_digits'] ?? '';
                
                $sumOpen = $open ? (array_sum(str_split($open)) % 10) : '';
                $sumClose = $close ? (array_sum(str_split($close)) % 10) : '';
                
                $openPanel = $open;
                $closePanel = $close;
                $jodi = $sumOpen !== '' || $sumClose !== '' ? $sumOpen . $sumClose : '';
            }
        }
        
        // Push to array formatting exactly for Frontend JS
        $response['data'][] = [
            "marketId" => $gameId,
            "name" => $title,
            "slug" => $alias,
            "isImportant" => (bool)$game['highlight'],
            "openTime" => $game['time_open'],
            "closeTime" => $game['time_close'],
            "chart" => [
                [
                    "openPanel" => $openPanel,
                    "jodi" => $jodi,
                    "closePanel" => $closePanel
                ]
            ]
        ];
    }
    
    $stmtToday->close();
    $stmtLatest->close();
    
    echo json_encode($response);

} catch (Exception $e) {
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(["success" => false, "message" => "Server Error"]);
}
?>