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

$timeout = 9000000; // 15 minutes

if (!isset($_SESSION['user_id']) || !isset($_SESSION['session_id'])) {
    header("Location: app-user-login.php");
    exit();
}

/* ==============================
   CHECK IF SESSION EXISTS IN DB
============================== */
$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();
    header("Location: app-user-login.php?forced_logout=1");
    exit();
}

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

    // 🔴 Mark DB session inactive BEFORE destroying PHP session
    $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();

    header("Location: app-user-login.php?timeout=1");
    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();

