<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/functions.php';

date_default_timezone_set("Asia/Kolkata");

$gameCode       = 'D5_1M';
$intervalMinute = 1.00;           // 1 minute
$intervalMs     = 60000;          // 60,000 ms
$currentTime    = (int)(microtime(true) * 1000);

// 1) Try to get current period from DB
$current = getCurrentPeriodFromDB_D5($conn, $gameCode, $currentTime);

// 2) If not found, seed from Official API once
if (!$current) {
    $officialData = fetchOfficialCurrent_D5();
    if ($officialData) {
        // Sync previous/current/next into DB
        syncOfficialPeriod_D5($conn, $gameCode, $officialData['previous']);
        syncOfficialPeriod_D5($conn, $gameCode, $officialData['current']);
        syncOfficialPeriod_D5($conn, $gameCode, $officialData['next']);
        // Use official current
        $current = [
            'issue_number' => $officialData['current']['issueNumber'],
            'start_time'   => (int)$officialData['current']['startTime'],
            'end_time'     => (int)$officialData['current']['endTime'],
        ];
    } else {
        // Emergency fallback – no DB, no API
        $start     = $currentTime;
        $end       = $start + $intervalMs;
        // D5 1M format example: 20260304102010254
        $currIssue = date('Ymd') . '10201' . '00001'; 
        $current = [
            'issue_number' => $currIssue,
            'start_time'   => $start,
            'end_time'     => $end,
        ];
    }
}

// 3) Get previous & next from DB based on current
$previous = getPreviousPeriodFromDB_D5($conn, $gameCode, $current);
$next     = getNextPeriodFromDB_D5($conn, $gameCode, $current, $intervalMs);

// 4) If previous/next missing in DB, compute logically from current
if (!$previous) {
    $prevIssue = is_numeric($current['issue_number']) ? (string)bcsub($current['issue_number'], '1') : $current['issue_number'];
    $previous = [
        'issue_number' => $prevIssue,
        'start_time'   => (int)$current['start_time'] - $intervalMs,
        'end_time'     => (int)$current['start_time'],
    ];
}
if (!$next) {
    $nextIssue = is_numeric($current['issue_number']) ? (string)bcadd($current['issue_number'], '1') : $current['issue_number'];
    $next = [
        'issue_number' => $nextIssue,
        'start_time'   => (int)$current['end_time'],
        'end_time'     => (int)$current['end_time'] + $intervalMs,
    ];
}

// 5) Build Response (EXACT original format)
$response = [
    "gameCode"       => $gameCode,
    "intervalMinute" => $intervalMinute,
    "state"          => 1,
    "previous"       => [
        "issueNumber" => $previous['issue_number'],
        "startTime"   => (int)$previous['start_time'],
        "endTime"     => (int)$previous['end_time'],
    ],
    "current"        => [
        "issueNumber" => $current['issue_number'],
        "startTime"   => (int)$current['start_time'],
        "endTime"     => (int)$current['end_time'],
    ],
    "next"           => [
        "issueNumber" => $next['issue_number'],
        "startTime"   => (int)$next['start_time'],
        "endTime"     => (int)$next['end_time'],
    ],
];

echo json_encode($response, JSON_UNESCAPED_SLASHES);
exit();

/* ===========================================================
   HELPER FUNCTIONS - LOCAL TO THIS FILE (D5 VERSION)
   =========================================================== */

function getCurrentPeriodFromDB_D5($conn, $gameCode, $nowMs) {
    $sql = "SELECT issue_number, start_time, end_time 
            FROM aks_game_periods 
            WHERE game_code = '$gameCode'
              AND start_time <= $nowMs
              AND end_time   >  $nowMs
            LIMIT 1";
    $res = $conn->query($sql);
    if ($res && $res->num_rows > 0) {
        $r = $res->fetch_assoc();
        return [
            'issue_number' => $r['issue_number'],
            'start_time'   => (int)$r['start_time'],
            'end_time'     => (int)$r['end_time'],
        ];
    }
    return null;
}

function getPreviousPeriodFromDB_D5($conn, $gameCode, $current) {
    $currIssue = $current['issue_number'];
    if (!is_numeric($currIssue)) return null;
    
    $sql = "SELECT issue_number, start_time, end_time 
            FROM aks_game_periods 
            WHERE game_code = '$gameCode'
              AND CAST(issue_number AS UNSIGNED) < " . (int)$currIssue . "
            ORDER BY CAST(issue_number AS UNSIGNED) DESC
            LIMIT 1";
    $res = $conn->query($sql);
    if ($res && $res->num_rows > 0) {
        $r = $res->fetch_assoc();
        return [
            'issue_number' => $r['issue_number'],
            'start_time'   => (int)$r['start_time'],
            'end_time'     => (int)$r['end_time'],
        ];
    }
    return null;
}

function getNextPeriodFromDB_D5($conn, $gameCode, $current, $intervalMs) {
    $currIssue = $current['issue_number'];
    if (!is_numeric($currIssue)) return null;
    
    $sql = "SELECT issue_number, start_time, end_time 
            FROM aks_game_periods 
            WHERE game_code = '$gameCode'
              AND CAST(issue_number AS UNSIGNED) > " . (int)$currIssue . "
            ORDER BY CAST(issue_number AS UNSIGNED) ASC
            LIMIT 1";
    $res = $conn->query($sql);
    if ($res && $res->num_rows > 0) {
        $r = $res->fetch_assoc();
        return [
            'issue_number' => $r['issue_number'],
            'start_time'   => (int)$r['start_time'],
            'end_time'     => (int)$r['end_time'],
        ];
    }
    return null;
}

function fetchOfficialCurrent_D5() {
    $url = "https://draw.ar-lottery01.com/5D/D5_1M.json"; // Note: Path is /5D/ not /D5/ on official server mostly
    $ch  = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $resp = curl_exec($ch);
    curl_close($ch);
    if (!$resp) return null;
    $data = json_decode($resp, true);
    if (!isset($data['current'])) return null;
    return $data;
}

function syncOfficialPeriod_D5($conn, $gameCode, $period) {
    if (!$period || !isset($period['issueNumber'])) return;
    $issue = $period['issueNumber'];
    $start = (int)$period['startTime'];
    $end   = (int)$period['endTime'];
    $sql   = "INSERT IGNORE INTO aks_game_periods 
              (game_code, issue_number, start_time, end_time, is_settled)
              VALUES ('$gameCode', '$issue', $start, $end, 0)";
    $conn->query($sql);
}
?>