<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../utils/JWT.php';

class AuthMiddleware {
    private static $currentUser = null;

    public static function authenticate() {
        try {
            // Obtener token del header Authorization
            $headers = getallheaders();
            $authHeader = isset($headers['Authorization']) ? $headers['Authorization'] : 
                         (isset($headers['authorization']) ? $headers['authorization'] : null);

            if (!$authHeader) {
                return false;
            }

            // Extraer token del header Bearer
            if (!preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
                return false;
            }

            $token = $matches[1];

            // Decodificar y validar token
            $payload = JWT::decode($token, JWT_SECRET, JWT_ALGORITHM);

            // Verificar que el token no haya expirado
            if (isset($payload['exp']) && $payload['exp'] < time()) {
                return false;
            }

            // Almacenar datos del usuario actual
            self::$currentUser = $payload;

            return true;

        } catch (Exception $e) {
            error_log("Error en autenticación: " . $e->getMessage());
            return false;
        }
    }

    public static function getCurrentUser() {
        return self::$currentUser;
    }

    public static function requireAuth() {
        if (!self::authenticate()) {
            http_response_code(401);
            echo json_encode([
                'success' => false,
                'message' => 'Token de autenticación requerido'
            ]);
            exit;
        }

        return true;
    }

    public static function requireAuthWithResponse() {
        if (!self::authenticate()) {
            return [
                'success' => false,
                'message' => 'Token de autenticación requerido',
                'code' => 401
            ];
        }

        return [
            'success' => true,
            'user' => self::$currentUser
        ];
    }

    public static function getUserId() {
        if (self::$currentUser && isset(self::$currentUser['user_id'])) {
            return self::$currentUser['user_id'];
        }
        return null;
    }

    public static function getUserRole() {
        if (self::$currentUser && isset(self::$currentUser['rol'])) {
            return self::$currentUser['rol'];
        }
        return null;
    }

    public static function getUserEmail() {
        if (self::$currentUser && isset(self::$currentUser['email'])) {
            return self::$currentUser['email'];
        }
        return null;
    }

    public static function isAdmin() {
        return self::getUserRole() === 'Administrador';
    }

    public static function isRegente() {
        return self::getUserRole() === 'Regente';
    }

    public static function isTecnicoCampo() {
        return self::getUserRole() === 'Técnico de Campo';
    }

    public static function hasRole($roles) {
        if (!is_array($roles)) {
            $roles = [$roles];
        }

        $userRole = self::getUserRole();
        return in_array($userRole, $roles);
    }

    public static function validateTokenOnly($token) {
        try {
            $payload = JWT::decode($token, JWT_SECRET, JWT_ALGORITHM);
            
            // Verificar que el token no haya expirado
            if (isset($payload['exp']) && $payload['exp'] < time()) {
                return false;
            }

            return $payload;

        } catch (Exception $e) {
            return false;
        }
    }
}
?>