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

/* ==============================
   IF SESSION EXISTS, CLOSE IT
============================== */
if (isset($_SESSION['session_id'])) {

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

/* ==============================
   DESTROY SESSION
============================== */
$_SESSION = [];
session_unset();
session_destroy();

/* ==============================
   OPTIONAL: CLEAR SESSION COOKIE
============================== */
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(),
        '',
        time() - 42000,
        $params["path"],
        $params["domain"],
        $params["secure"],
        $params["httponly"]
    );
}

/* ==============================
   REDIRECT
============================== */
//header("Location: ../view/app-login.php?logged_out=1");
//exit();
echo json_encode(["status" => "logged_out"]);
?>
