<?php
session_start();
require 'db.php';

header('Content-Type: application/json');

$timeout = 900; // 15 minutes

if (!isset($_SESSION['user_id']) || !isset($_SESSION['session_id'])) {
    echo json_encode(["status" => "expired", "reason" => "no_session"]);
    exit();
}

/* CHECK DB SESSION */
$stmt = $pdo->prepare("SELECT is_active FROM login_sessions WHERE session_id=?");
$stmt->execute([$_SESSION['session_id']]);
$dbSession = $stmt->fetch();

if (!$dbSession || $dbSession['is_active'] == 0) {
    session_destroy();
    echo json_encode(["status" => "expired", "reason" => "forced_logout"]);
    exit();
}

/* IDLE TIMEOUT */
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {

    $stmt = $pdo->prepare("UPDATE login_sessions 
        SET is_active=0, logout_time=NOW() + INTERVAL 8 HOUR
        WHERE session_id=?");
    $stmt->execute([$_SESSION['session_id']]);

    session_unset();
    session_destroy();

    echo json_encode(["status" => "expired", "reason" => "timeout"]);
    exit();
}

/* ==============================
   UPDATE LAST ACTIVITY
============================== */
// Update last activity in DB
$stmt = $pdo->prepare("UPDATE login_sessions SET last_activity = NOW() + INTERVAL 8 HOUR WHERE session_id=?");
$stmt->execute([$_SESSION['session_id']]);

$_SESSION['last_activity'] = time();
