<?php
/**
 * Maintenance mode helpers
 */

if (!function_exists('is_maintenance_mode_enabled')) {
    function is_maintenance_mode_enabled(?mysqli $connection = null): bool
    {
        static $cached = null;
        if ($cached !== null) {
            return $cached;
        }

        if (!$connection) {
            $cached = false;
            return false;
        }

        $tableCheck = $connection->query("SHOW TABLES LIKE 'site_settings'");
        if (!$tableCheck || $tableCheck->num_rows === 0) {
            $cached = false;
            return false;
        }

        $result = $connection->query("SELECT setting_value FROM site_settings WHERE setting_key = 'maintenance_mode' LIMIT 1");
        if (!$result || $result->num_rows === 0) {
            $cached = false;
            return false;
        }

        $row = $result->fetch_assoc();
        $cached = ((string)($row['setting_value'] ?? '0') === '1');
        return $cached;
    }
}

if (!function_exists('enforce_maintenance_mode')) {
    function enforce_maintenance_mode(?mysqli $connection = null): void
    {
        if (PHP_SAPI === 'cli') {
            return;
        }

        $scriptName = basename($_SERVER['SCRIPT_NAME'] ?? '');
        $requestUri = $_SERVER['REQUEST_URI'] ?? '';
        $allowedScripts = [
            'maintenance.php',
            'admin-dashboard.php',
            'staff-dashboard.php',
            'staff-login.php',
            'admin-login.php',
            'login.php',
            'logout.php'
        ];

        // Always allow these paths/scripts
        if (in_array($scriptName, $allowedScripts, true) || str_contains($requestUri, '/assets/') || str_contains($requestUri, '/api/')) {
            return;
        }

        // Allow admins/staff to access dashboard while maintenance mode is on
        $role = '';
        if (session_status() === PHP_SESSION_ACTIVE) {
            $role = (string)($_SESSION['user_role'] ?? '');
        }
        if ($role === 'admin' || $role === 'staff') {
            return;
        }

        if (is_maintenance_mode_enabled($connection)) {
            header('Location: maintenance.php', true, 302);
            exit;
        }
    }
}
