<?php
// Start the session
session_start();

require_once 'config.php';
require_once 'app/classes/UserLoginTracker.php';

use App\classes\UserLoginTracker;

// Check if user is an agent before destroying session (need to check store_id)
$agentStoreSlug = null;

if (isset($_SESSION['user_id']) && isset($_SESSION['role']) && $_SESSION['role'] === 'agent') {
    // Check if agent belongs to a store (primary source - most reliable)
    if (isset($conn)) {
        $stmt = $conn->prepare("SELECT a.store_id, s.store_slug FROM agents a LEFT JOIN stores s ON a.store_id = s.id WHERE a.id = ? AND a.role = 'agent' AND a.is_store_owner = 0 LIMIT 1");
        $stmt->bind_param("i", $_SESSION['user_id']);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $agentData = $result->fetch_assoc();
            if (!empty($agentData['store_id']) && !empty($agentData['store_slug'])) {
                $agentStoreSlug = $agentData['store_slug'];
            }
        }
        $stmt->close();
    }
    
    // Fallback: Use session-stored store slug if database check didn't find one
    // This handles cases where agent visited their store page and slug was stored
    if (empty($agentStoreSlug) && isset($_SESSION['agent_store_slug'])) {
        $agentStoreSlug = $_SESSION['agent_store_slug'];
    }
}

// Log logout if user was logged in
if (isset($_SESSION['user_id']) && isset($_SESSION['login_time'])) {
    $loginTracker = new UserLoginTracker($conn);
    $loginTracker->logLogout($_SESSION['user_id'], date('Y-m-d H:i:s', $_SESSION['login_time']));
}

// Destroy all session data
session_destroy();

// Clear any session cookies
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time() - 3600, '/');
}

// Redirect: Agents go to their store's public page, others go to home page
if (!empty($agentStoreSlug)) {
    header('Location: store.php?slug=' . urlencode($agentStoreSlug));
} else {
    header('Location: index.php');
}
exit();
?>
