<?php
/* ========================
   LOGOUT HANDLER
   Path: /auth/logout.php
   Updated: 2026-02-05
======================== */

session_start();

/* ========================
   LOG AKTIVITAS LOGOUT
======================== */
if (isset($_SESSION['user_id']) && isset($_SESSION['login']) && $_SESSION['login'] === true) {
    try {
        // Include koneksi database untuk logging
        require_once __DIR__ . '/../DataBase/koneksi.php';
        
        $userId = $_SESSION['user_id'];
        $userName = $_SESSION['full_name'] ?? $_SESSION['username'] ?? 'Unknown User';
        $userIP = $_SERVER['REMOTE_ADDR'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? 'Unknown';
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
        
        // Log ke activity log jika function tersedia
        if (function_exists('logActivity')) {
            logActivity(
                $userId, 
                'Logout', 
                'users', 
                $userId, 
                "Logout dari IP: {$userIP}, Browser: " . substr($userAgent, 0, 100)
            );
        }
        
        // Alternatif: Log langsung ke database jika table activity_log ada
        $checkTable = $conn->query("SHOW TABLES LIKE 'activity_log'");
        if ($checkTable && $checkTable->num_rows > 0) {
            $stmt = $conn->prepare("
                INSERT INTO activity_log 
                (user_id, action, table_name, record_id, description, ip_address, created_at) 
                VALUES (?, 'Logout', 'users', ?, ?, ?, NOW())
            ");
            
            if ($stmt) {
                $description = "User {$userName} logged out";
                $stmt->bind_param("iiss", $userId, $userId, $description, $userIP);
                $stmt->execute();
                $stmt->close();
            }
        }
        
        // Update last_activity di users table
        $updateStmt = $conn->prepare("UPDATE users SET updated_at = NOW() WHERE id = ?");
        if ($updateStmt) {
            $updateStmt->bind_param("i", $userId);
            $updateStmt->execute();
            $updateStmt->close();
        }
        
        $conn->close();
        
    } catch (Exception $e) {
        // Logging gagal, tapi tetap lanjut logout
        error_log("Logout logging failed: " . $e->getMessage());
    }
}

/* ========================
   DESTROY SESSION
======================== */
// Store logout message before destroying session
$logoutMessage = isset($_SESSION['full_name']) ? "Berhasil logout, " . $_SESSION['full_name'] : "Berhasil logout";

// Unset all session variables
$_SESSION = array();

// Destroy the session cookie
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time() - 3600, '/');
    setcookie(session_name(), '', time() - 3600, '/', '', false, true); // HttpOnly
}

// Also clear any other auth cookies (if exists)
$authCookies = ['remember_token', 'user_id', 'auth_token'];
foreach ($authCookies as $cookie) {
    if (isset($_COOKIE[$cookie])) {
        setcookie($cookie, '', time() - 3600, '/');
    }
}

// Destroy the session
session_destroy();

/* ========================
   PREVENT CACHE
   (Mencegah user tekan tombol Back)
======================== */
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

/* ========================
   REDIRECT TO LOGIN
   Path: /auth/logout.php -> /index.html
======================== */
header("Location: ../index.html?logout=success");
exit;
?>