<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
function checkAuth() {
    if (!isset($_SESSION['user_id'])) {
        // Determine the base path for redirects
        $base_path = '/malshanlast/';
        $current_path = $_SERVER['REQUEST_URI'];
        
        // If this is an AJAX request, send JSON response
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
            strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            http_response_code(401);
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Session expired', 'redirect' => $base_path . 'login.php']);
            exit;
        }
        
        // For API requests (check if path contains 'api/')
        if (strpos($current_path, '/api/') !== false) {
            http_response_code(401);
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Unauthorized access']);
            exit;
        }
        
        // Regular page request - redirect to login
        // Calculate relative path based on current directory depth
        $path_parts = explode('/', trim($current_path, '/'));
        $depth = count($path_parts) - 1;
        $relative_prefix = str_repeat('../', max(0, $depth - 1));
        
        header('Location: ' . $relative_prefix . 'login.php');
        exit;
    }
}

// Check if user has required role
function checkRole($required_role) {
    checkAuth();
    $user_role = $_SESSION['role'];
    
    $role_hierarchy = ['cashier' => 1, 'manager' => 2, 'admin' => 3];
    
    if ($role_hierarchy[$user_role] < $role_hierarchy[$required_role]) {
        header('Location: unauthorized.php');
        exit;
    }
}

// Get current user info
function getCurrentUser() {
    return [
        'id' => $_SESSION['user_id'] ?? null,
        'username' => $_SESSION['username'] ?? null,
        'full_name' => $_SESSION['full_name'] ?? null,
        'role' => $_SESSION['role'] ?? null
    ];
}

// Logout function
function logout() {
    session_destroy();
    header('Location: login.php');
    exit;
}
?>
