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

$hostname = "localhost";
$username = "atrmarke_FHS_HARD";
$password = "FHS_HARD123";
$database = "atrmarke_FHS_HARD";

// Create a new MySQLi connection
$connection = mysqli_connect($hostname, $username, $password, $database);

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Set MySQL timezone
if (!mysqli_query($connection, "SET time_zone = '+05:00'")) {
    die("Error setting MySQL timezone: " . mysqli_error($connection));
}

// Select the database
if (!mysqli_select_db($connection, $database)) {
    die("Database selection failed: " . mysqli_error($connection));
}

// Calculate the time remaining until midnight
$current_time = time();
$midnight = strtotime('tomorrow midnight');
$seconds_until_midnight = $midnight - $current_time;

// Set session cookie lifetime to expire at midnight
ini_set('session.cookie_lifetime', $seconds_until_midnight);
ini_set('session.gc_maxlifetime', $seconds_until_midnight);

// Start the session
session_start();

// Check if the session has crossed midnight
if (isset($_SESSION['session_start_time'])) {
    $session_start_time = $_SESSION['session_start_time'];
    $midnight_today = strtotime('today midnight');
    
    if ($session_start_time < $midnight_today) {
        session_unset();
        session_destroy();
        // Redirect to login page or any other page
        header("Location:log/logout.php");
        exit();
    }
} else {
    // Store the session start time
    $_SESSION['session_start_time'] = $current_time;
}
?>