<?php
/**
 * ASISMA CRM - Middleware de Autenticación
 */
class AuthMiddleware {

    public static function handle() {
        if (!SessionHelper::checkSession()) {
            SessionHelper::destroySession();

            $xrw    = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) : '';
            $accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : '';
            $isAjax = (!empty($xrw) && $xrw == 'xmlhttprequest')
                      || (strpos($accept, 'application/json') !== false);

            if ($isAjax) {
                header('HTTP/1.1 401 Unauthorized');
                header('Content-Type: application/json; charset=utf-8');
                echo json_encode(array(
                    'success' => false,
                    'error'   => true,
                    'message' => 'Sesión expirada o no autorizada. Por favor, inicie sesión nuevamente.'
                ));
                exit;
            }

            $returnUrl = urlencode(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '');
            header("Location: " . APP_URL . "/login?return_url=" . $returnUrl);
            exit;
        }
    }
}
