<?php
// Database connection and functions
include("serive/samparka.php");
include("nayakaphalitansa_mulaka_unohs_kemuru_zehn.php");

// Get current date in YYYYMMDD format
$currentDate = date('Ymd');

// Calculate the 10-minute period number for today
$timeInSeconds = time() % 86400; // seconds since midnight
$sequenceNumber = intval($timeInSeconds / 600); // each period = 600 sec (10 min)
$uniqueSequence = str_pad($sequenceNumber, 4, '0', STR_PAD_LEFT);

// Generate game ID: YYYYMMDD10104####
$gameID = $currentDate . "10104" . $uniqueSequence;
$gameID++;

// Get current timestamp
$currentTime = date('Y-m-d H:i:s');

// Get the latest entry from the table
$result = mysqli_query($conn, "SELECT atadaaidi FROM `gelluonduhogu_kemuru_zehn` ORDER BY kramasankhye DESC LIMIT 1");
$rowCount = mysqli_num_rows($result);
$latestRow = mysqli_fetch_array($result);

if ($rowCount == 0 || empty($latestRow)) {
    // First time inserting
    mysqli_query($conn, "INSERT INTO `gelluonduhogu_kemuru_zehn` (`atadaaidi`, `dinankavannuracisi`) VALUES ('$gameID', '$currentTime')");
} elseif ($gameID > $latestRow['atadaaidi']) {
    // New game cycle, reset table and insert new game ID
    mysqli_query($conn, "TRUNCATE TABLE `gelluonduhogu_kemuru_zehn`");
    mysqli_query($conn, "INSERT INTO `gelluonduhogu_kemuru_zehn` (`atadaaidi`, `dinankavannuracisi`) VALUES ('$gameID', '$currentTime')");
} else {
    // Continue to next sequence
    $nextGameID = $latestRow['atadaaidi'] + 1;
    mysqli_query($conn, "INSERT INTO `gelluonduhogu_kemuru_zehn` (`atadaaidi`, `dinankavannuracisi`) VALUES ('$nextGameID', '$currentTime')");
}

// Reset all game status
mysqli_query($conn, "UPDATE hastacalita_phalitansa_kemeru_zehn SET sthiti='0'");
?>
