<?php
// api/v1/markets/todaysMarket.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';

verifyApiRequest();

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

try {
    // 🕒 Time Window Logic: -30 mins to +15 mins
    $query = "SELECT * FROM games 
              WHERE (
                  (TIME(time_open) BETWEEN SUBTIME(?, '00:30:00') AND ADDTIME(?, '00:15:00'))
                  OR
                  (TIME(time_close) BETWEEN SUBTIME(?, '00:30:00') AND ADDTIME(?, '00:15:00'))
              ) AND is_holiday = 0 AND is_active = 1";
              
    $stmtLive = $db->prepare($query);
    $stmtLive->bind_param("ssss", $currentTime, $currentTime, $currentTime, $currentTime);
    $stmtLive->execute();
    $liveGames = $stmtLive->get_result();
    
    $stmtResult = $db->prepare("SELECT * FROM results WHERE game_id = ? AND draw_date = ? LIMIT 1");
    
    while ($game = $liveGames->fetch_assoc()) {
        $gameId = (int)$game['game_id'];
        
        $stmtResult->bind_param("is", $gameId, $today);
        $stmtResult->execute();
        $result = $stmtResult->get_result()->fetch_assoc();
        
        $open = $result['open_digits'] ?? '';
        $close = $result['close_digits'] ?? '';
        
        if ($open || $close) {
            $sumOpen = $open ? (array_sum(str_split($open)) % 10) : '';
            $sumClose = $close ? (array_sum(str_split($close)) % 10) . '-' : '';
            $resultText = "$open-$sumOpen$sumClose$close";
        } else {
            $resultText = "⏳ Loading...";
        }
        
        $response['data'][] = [
            "marketId" => $gameId,
            "name" => strtoupper($game['title']),
            "resultText" => $resultText,
            "passing" => $result['passing'] ?? '',
            "noteOpen" => $result['note_open'] ?? '',
            "noteClose" => $result['note_close'] ?? ''
        ];
    }
    
    $stmtLive->close();
    $stmtResult->close();
    
    echo json_encode($response);

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