<?php
declare(strict_types=1);
date_default_timezone_set('Asia/Kolkata');
include "db.php";

$today = date('Y-m-d');

// ✅ STEP 1: Check if today's data already generated
$stmt = $db->prepare("SELECT COUNT(*) AS cnt FROM daily_results WHERE date = ?");
$stmt->execute([$today]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

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

    // 🏷 Fetch all markets at once
    $markets = $db->query("SELECT title FROM games")->fetchAll(PDO::FETCH_COLUMN);

    // ✅ Prepare statements outside loop for speed
    $stmtCheck = $db->prepare("SELECT id FROM daily_results WHERE market = ? AND date = ? LIMIT 1");
    $stmtInsert = $db->prepare("INSERT INTO daily_results (date, market, final_ank, golden_ank) VALUES (?, ?, ?, ?)");
    $stmtUpdate = $db->prepare("UPDATE daily_results SET date = ?, final_ank = ?, golden_ank = ? WHERE market = ? AND date = ?");

    foreach ($markets as $market) {
        $finalAnk = rand(0, 9);

        // Check if record exists
        $stmtCheck->execute([$market, $today]);
        $exists = $stmtCheck->fetch(PDO::FETCH_ASSOC);

        if ($exists) {
            // 🔄 Update existing record
            $stmtUpdate->execute([$today, $finalAnk, $goldenAnk, $market, $today]);
        } else {
            // ➕ Insert new record
            $stmtInsert->execute([$today, $market, $finalAnk, $goldenAnk]);
        }
    }
}

// ✅ STEP 2: Fetch results for display
$goldenRes = $db->prepare("SELECT DISTINCT golden_ank FROM daily_results WHERE date = ? LIMIT 1");
$goldenRes->execute([$today]);
$goldenRow = $goldenRes->fetch(PDO::FETCH_ASSOC);
$goldenAnk = $goldenRow['golden_ank'] ?? '';

// Fetch all final results at once
$finalRes = $db->prepare("SELECT market, final_ank FROM daily_results WHERE date = ? ORDER BY market ASC");
$finalRes->execute([$today]);
$finalRows = $finalRes->fetchAll(PDO::FETCH_ASSOC);

$finalAnkList = [];
foreach ($finalRows as $r) {
    $finalAnkList[] = strtoupper($r['market']) . " - " . $r['final_ank'];
}
$finalAnkString = implode("<br>", $finalAnkList);
?>

<div class="lucky-box">
  <div class="title-head" style="margin:0; border-radius:0;">Today Lucky Number</div>
  <div class="lucky-flex">
    <div>
      <h4>Golden Ank</h4>
      <p><?php echo $goldenAnk; ?></p>
    </div>
    <div>
      <h4>Final Ank</h4>
      <div class="scroll-wrap">
    <div class="lucky-scroll">
        <p><?php echo $finalAnkString; ?></p>
      </div></div>
    </div>
  </div>
</div> 

  