<?php
require_once __DIR__ . '/AuthMiddleware.php';

class RoleMiddleware {
    
    public static function requireRole($requiredRoles) {
        // Primero verificar autenticación
        if (!AuthMiddleware::authenticate()) {
            http_response_code(401);
            echo json_encode([
                'success' => false,
                'message' => 'Token de autenticación requerido'
            ]);
            exit;
        }

        // Convertir a array si es string
        if (!is_array($requiredRoles)) {
            $requiredRoles = [$requiredRoles];
        }

        $userRole = AuthMiddleware::getUserRole();

        if (!in_array($userRole, $requiredRoles)) {
            http_response_code(403);
            echo json_encode([
                'success' => false,
                'message' => 'No tienes permisos para acceder a este recurso'
            ]);
            exit;
        }

        return true;
    }

    public static function requireAdmin() {
        return self::requireRole(['Administrador']);
    }

    public static function requireAdminOrRegente() {
        return self::requireRole(['Administrador', 'Regente']);
    }

    public static function requireRegente() {
        return self::requireRole(['Regente']);
    }

    public static function requireTecnicoCampo() {
        return self::requireRole(['Técnico de Campo']);
    }

    public static function checkRole($requiredRoles) {
        // Versión que no termina la ejecución, solo retorna true/false
        if (!AuthMiddleware::authenticate()) {
            return false;
        }

        if (!is_array($requiredRoles)) {
            $requiredRoles = [$requiredRoles];
        }

        $userRole = AuthMiddleware::getUserRole();
        return in_array($userRole, $requiredRoles);
    }

    public static function checkRoleWithResponse($requiredRoles) {
        // Versión que retorna respuesta estructurada
        $authResult = AuthMiddleware::requireAuthWithResponse();
        
        if (!$authResult['success']) {
            return $authResult;
        }

        if (!is_array($requiredRoles)) {
            $requiredRoles = [$requiredRoles];
        }

        $userRole = AuthMiddleware::getUserRole();

        if (!in_array($userRole, $requiredRoles)) {
            return [
                'success' => false,
                'message' => 'No tienes permisos para acceder a este recurso',
                'code' => 403
            ];
        }

        return [
            'success' => true,
            'user' => $authResult['user']
        ];
    }

    public static function isAdmin() {
        return AuthMiddleware::isAdmin();
    }

    public static function isRegente() {
        return AuthMiddleware::isRegente();
    }

    public static function isTecnicoCampo() {
        return AuthMiddleware::isTecnicoCampo();
    }

    public static function canManageProjects() {
        return self::checkRole(['Administrador', 'Regente']);
    }

    public static function canManageUsers() {
        return self::checkRole(['Administrador']);
    }

    public static function canUseFieldApp() {
        return self::checkRole(['Técnico de Campo', 'Regente', 'Administrador']);
    }

    public static function canViewReports() {
        return self::checkRole(['Administrador', 'Regente']);
    }

    public static function canManageRodales() {
        return self::checkRole(['Administrador', 'Regente']);
    }

    public static function canSyncFieldData() {
        return self::checkRole(['Técnico de Campo', 'Regente', 'Administrador']);
    }

    public static function getPermissions() {
        $userRole = AuthMiddleware::getUserRole();
        
        if (!$userRole) {
            return [];
        }

        $permissions = [];

        switch ($userRole) {
            case 'Administrador':
                $permissions = [
                    'manage_users',
                    'manage_projects',
                    'manage_rodales',
                    'use_field_app',
                    'sync_field_data',
                    'view_reports',
                    'export_data',
                    'manage_system_config'
                ];
                break;

            case 'Regente':
                $permissions = [
                    'manage_projects',
                    'manage_rodales',
                    'use_field_app',
                    'sync_field_data',
                    'view_reports',
                    'export_data'
                ];
                break;

            case 'Técnico de Campo':
                $permissions = [
                    'use_field_app',
                    'sync_field_data'
                ];
                break;
        }

        return $permissions;
    }

    public static function hasPermission($permission) {
        $permissions = self::getPermissions();
        return in_array($permission, $permissions);
    }
}
?>