<?php
// api/v1/markets/free-guessing.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');
$response = ["success" => true, "data" => []];

try {
    $activeMarketsQ = "SELECT title, game_id, time_open FROM games WHERE is_active=1 AND guess_status=1 ORDER BY time_open ASC";
    $activeMarkets = $db->query($activeMarketsQ);
    
    $stmtFree = $db->prepare("SELECT * FROM free_game WHERE market=? ORDER BY STR_TO_DATE(date, '%Y-%m-%d') DESC LIMIT 1");
    
    $counter = 0;
    while ($game = $activeMarkets->fetch_assoc()) {
        $marketName = trim($game['title']);
        
        $stmtFree->bind_param("s", $marketName);
        $stmtFree->execute();
        $freeData = $stmtFree->get_result()->fetch_assoc();
        
        if (!$freeData) continue;
        
        // Time Lock Logic
        $openTimeStr = $today . ' ' . $game['time_open'];
        $openTimeObj = new DateTime($openTimeStr);
        $postTime = (clone $openTimeObj)->modify('-40 minutes');
        $currentTime = new DateTime();
        
        $isVisible = ($currentTime >= $postTime);
        
        // Left / Right Column distribution
        $column = ($counter % 2 == 0) ? "left" : "right";
        
        $response['data'][] = [
            "marketId" => $game['game_id'],
            "name" => $marketName,
            "showTime" => $postTime->format('H:i'), // When guessing opens
            "isVisible" => $isVisible,
            "open" => $isVisible ? $freeData['open'] : "",
            "jodi" => $isVisible ? $freeData['jodi'] : "",
            "panel" => $isVisible ? $freeData['panel'] : "",
            "column" => $column
        ];
        $counter++;
    }
    
    $stmtFree->close();
    echo json_encode($response);

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