<?php
date_default_timezone_set('Asia/Kolkata');

function waitForSecond($desiredSecond) {
    while (true) {
        $currentSecond = date('s');
        if ((int)$currentSecond === (int)$desiredSecond) {  // Type casting for proper comparison
            break;
        }
        usleep(100000); // 0.1 second sleep
    }
}

// Wait for the start of a minute
waitForSecond('00');

// Database connection files
include("serive/samparka.php");
include("nayakaphalitansa_mulaka_unohs.php");

$currentDate = date('Ymd');
$timeInSeconds = time() % 86400; // Seconds since midnight
$sequenceNumber = floor($timeInSeconds / 60); // Minutes since midnight
$uniqueSequence = str_pad($sequenceNumber, 4, '0', STR_PAD_LEFT);

$bartamankalakrama = $currentDate . "10001" . $uniqueSequence;
$bartamankalakrama = (int)$bartamankalakrama + 1; // Convert to integer and increment
$prathama = $bartamankalakrama;
$sesa = $currentDate . "10001" . sprintf("%04d", ceil(86400 / 60)); // Max minutes in a day (1440)

$tarika = date('Y-m-d H:i:s');

// Check last sequence
$dekhakalakrama = mysqli_query($conn, "SELECT atadaaidi FROM `gelluonduhogu` ORDER BY kramasankhye DESC LIMIT 1");
$kaladhadi = mysqli_num_rows($dekhakalakrama);
$kalakramadhadi = mysqli_fetch_array($dekhakalakrama);

try {
    if ($kaladhadi === 0) {  // Changed null check to proper zero check
        $tathya = mysqli_query($conn, "INSERT INTO `gelluonduhogu` (`atadaaidi`, `dinankavannuracisi`) VALUES ('$bartamankalakrama', '$tarika')");
    } else if ($prathama > (int)$kalakramadhadi['atadaaidi']) {
        $katiba = mysqli_query($conn, "TRUNCATE TABLE `gelluonduhogu`");
        $tathya = mysqli_query($conn, "INSERT INTO `gelluonduhogu` (`atadaaidi`, `dinankavannuracisi`) VALUES ('$prathama', '$tarika')");
    } else {
        $parabartikrama = (int)$kalakramadhadi['atadaaidi'] + 1;
        $tathya = mysqli_query($conn, "INSERT INTO `gelluonduhogu` (`atadaaidi`, `dinankavannuracisi`) VALUES ('$parabartikrama', '$tarika')");
    }

    // Clean up operation
    $safa_shonu = mysqli_query($conn, "DELETE FROM gelluonduhogu_zehn_zehn_1");

    // Error checking
    if (!$tathya || !$safa_shonu) {
        throw new Exception("Database operation failed: " . mysqli_error($conn));
    }
} catch (Exception $e) {
    error_log("Error: " . $e->getMessage());
    // Handle error appropriately
}
?>