<?php
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

if ($method === 'GET') {
    handleGet();
} elseif ($method === 'POST') {
    handlePost($input);
} elseif ($method === 'PUT') {
    handlePut($input);
} elseif ($method === 'DELETE') {
    handleDelete($input);
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

function handleGet() {
    $db = getDB();
    $action = $_GET['action'] ?? 'list';
    
    try {
        if ($action === 'list') {
            // Obtener todos los roles con conteo de usuarios
            $stmt = $db->query("
                SELECT r.*, 
                       COUNT(DISTINCT au.id) as user_count,
                       COUNT(DISTINCT rp.permission_id) as permission_count
                FROM roles r
                LEFT JOIN admin_users au ON r.id = au.role_id
                LEFT JOIN role_permissions rp ON r.id = rp.role_id
                GROUP BY r.id
                ORDER BY r.id
            ");
            $roles = $stmt->fetchAll();
            
            echo json_encode([
                'success' => true,
                'data' => $roles
            ]);
            
        } elseif ($action === 'permissions') {
            // Obtener todos los permisos agrupados por módulo
            $stmt = $db->query("
                SELECT * FROM permissions 
                ORDER BY module, name
            ");
            $permissions = $stmt->fetchAll();
            
            // Agrupar por módulo
            $grouped = [];
            foreach ($permissions as $perm) {
                $module = $perm['module'];
                if (!isset($grouped[$module])) {
                    $grouped[$module] = [];
                }
                $grouped[$module][] = $perm;
            }
            
            echo json_encode([
                'success' => true,
                'data' => $grouped
            ]);
            
        } elseif ($action === 'role_permissions') {
            $roleId = $_GET['role_id'] ?? 0;
            
            $stmt = $db->prepare("
                SELECT p.* 
                FROM permissions p
                JOIN role_permissions rp ON p.id = rp.permission_id
                WHERE rp.role_id = ?
            ");
            $stmt->execute([$roleId]);
            $permissions = $stmt->fetchAll();
            
            echo json_encode([
                'success' => true,
                'data' => $permissions
            ]);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Error del servidor: ' . $e->getMessage()
        ]);
    }
}

function handlePost($input) {
    $db = getDB();
    $action = $input['action'] ?? '';
    
    try {
        if ($action === 'create_role') {
            $name = $input['name'] ?? '';
            $displayName = $input['display_name'] ?? '';
            $description = $input['description'] ?? '';
            
            if (empty($name) || empty($displayName)) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Nombre y nombre de visualización son requeridos'
                ]);
                return;
            }
            
            $stmt = $db->prepare("
                INSERT INTO roles (name, display_name, description)
                VALUES (?, ?, ?)
                RETURNING id
            ");
            $stmt->execute([$name, $displayName, $description]);
            $result = $stmt->fetch();
            
            echo json_encode([
                'success' => true,
                'message' => 'Rol creado exitosamente',
                'role_id' => $result['id']
            ]);
            
        } elseif ($action === 'update_permissions') {
            $roleId = $input['role_id'] ?? 0;
            $permissions = $input['permissions'] ?? [];
            
            // Eliminar permisos actuales
            $stmt = $db->prepare("DELETE FROM role_permissions WHERE role_id = ?");
            $stmt->execute([$roleId]);
            
            // Insertar nuevos permisos
            if (!empty($permissions)) {
                $stmt = $db->prepare("
                    INSERT INTO role_permissions (role_id, permission_id)
                    VALUES (?, ?)
                ");
                
                foreach ($permissions as $permId) {
                    $stmt->execute([$roleId, $permId]);
                }
            }
            
            echo json_encode([
                'success' => true,
                'message' => 'Permisos actualizados exitosamente'
            ]);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Error del servidor: ' . $e->getMessage()
        ]);
    }
}

function handlePut($input) {
    $db = getDB();
    $roleId = $input['id'] ?? 0;
    $displayName = $input['display_name'] ?? '';
    $description = $input['description'] ?? '';
    
    try {
        $stmt = $db->prepare("
            UPDATE roles 
            SET display_name = ?, description = ?
            WHERE id = ?
        ");
        $stmt->execute([$displayName, $description, $roleId]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Rol actualizado exitosamente'
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Error del servidor: ' . $e->getMessage()
        ]);
    }
}

function handleDelete($input) {
    $db = getDB();
    $roleId = $input['id'] ?? 0;
    
    try {
        // Verificar que no haya usuarios con este rol
        $stmt = $db->prepare("SELECT COUNT(*) as count FROM admin_users WHERE role_id = ?");
        $stmt->execute([$roleId]);
        $result = $stmt->fetch();
        
        if ($result['count'] > 0) {
            echo json_encode([
                'success' => false,
                'message' => 'No se puede eliminar el rol porque tiene usuarios asignados'
            ]);
            return;
        }
        
        $stmt = $db->prepare("DELETE FROM roles WHERE id = ?");
        $stmt->execute([$roleId]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Rol eliminado exitosamente'
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Error del servidor: ' . $e->getMessage()
        ]);
    }
}
