<?php
// api/v1/markets/lucky-numbers.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 {
    // ✅ STEP 1: Check if today's data already generated
    $stmtCheck = $db->prepare("SELECT COUNT(*) AS cnt FROM daily_results WHERE date = ?");
    $stmtCheck->bind_param("s", $today);
    $stmtCheck->execute();
    $row = $stmtCheck->get_result()->fetch_assoc();
    $stmtCheck->close();

    if ((int)$row['cnt'] === 0) {
        // 🎯 Generate new results (Golden Ank & Final Ank)
        $digits = range(0, 9);
        shuffle($digits);
        $goldenAnk = implode('-', array_slice($digits, 0, 4));

        $marketsQuery = $db->query("SELECT title FROM games");
        
        $stmtInsert = $db->prepare("INSERT INTO daily_results (date, market, final_ank, golden_ank) VALUES (?, ?, ?, ?)");
        
        while ($m = $marketsQuery->fetch_assoc()) {
            $market = $m['title'];
            $finalAnk = rand(0, 9);
            $stmtInsert->bind_param("ssis", $today, $market, $finalAnk, $goldenAnk);
            $stmtInsert->execute();
        }
        $stmtInsert->close();
    }

    // ✅ STEP 2: Fetch results for display
    $goldenRes = $db->prepare("SELECT golden_ank FROM daily_results WHERE date = ? LIMIT 1");
    $goldenRes->bind_param("s", $today);
    $goldenRes->execute();
    $goldenRow = $goldenRes->get_result()->fetch_assoc();
    $goldenAnk = $goldenRow['golden_ank'] ?? '';
    $goldenRes->close();

    $finalRes = $db->prepare("SELECT market, final_ank FROM daily_results WHERE date = ? ORDER BY market ASC");
    $finalRes->bind_param("s", $today);
    $finalRes->execute();
    $finalRows = $finalRes->get_result();
    
    $finalAnkList = [];
    while ($r = $finalRows->fetch_assoc()) {
        $finalAnkList[] = strtoupper($r['market']) . " - " . $r['final_ank'];
    }
    $finalRes->close();

    $response['data'] = [
        "goldenAnk" => $goldenAnk,
        "finalAnks" => $finalAnkList // Array format me bhej rahe hain taaki JS easily scroll me map kar sake
    ];
    
    echo json_encode($response);

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