<?php
// ============================================================
//  logout.php — Admin Logout
//  Place in: /admin/logout.php
// ============================================================
require_once 'includes/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Log the logout action before destroying session
if (!empty($_SESSION['admin_id'])) {
    db_execute(
        "INSERT INTO activity_log (admin_id, action, target_type, details, ip_address)
         VALUES (?, 'admin_logout', 'system', 'Admin logged out', ?)",
        [$_SESSION['admin_id'], $_SERVER['REMOTE_ADDR']]
    );
}

// Destroy everything
session_unset();
session_destroy();

// 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']
    );
}

header('Location: login.php?logged_out=1');
exit;
