<?php
session_start();
if (!defined('BASE_PATH')) { define('BASE_PATH', __DIR__); }
require_once BASE_PATH . '/database/connection.php';

$pdo = getDB()->getConnection();
$current_user_id = (int)($_SESSION['user_id'] ?? 0);

function userHasPermissionByName($pdo, $permName, $userId) {
    if (empty($userId)) return false;
    $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
    $stmt->execute([$userId, $permName]);
    return (bool)$stmt->fetchColumn();
}

echo "<h2>Debug de Permisos</h2>";
echo "<p>Usuario ID: " . $current_user_id . "</p>";
echo "<p>Usuario logueado: " . (isset($_SESSION['user_id']) ? 'Sí' : 'No') . "</p>";

if ($current_user_id > 0) {
    // Verificar permisos específicos
    $permissions = ['payments.configure', 'big4pay.configure', 'big4pay.view', 'voiso.configure'];
    
    foreach ($permissions as $perm) {
        $hasPermission = userHasPermissionByName($pdo, $perm, $current_user_id);
        echo "<p>Permiso '$perm': " . ($hasPermission ? 'SÍ' : 'NO') . "</p>";
    }
    
    // Mostrar todos los permisos del usuario
    echo "<h3>Todos los permisos del usuario:</h3>";
    $stmt = $pdo->prepare("
        SELECT p.name, p.display_name, r.name as role_name 
        FROM role_permissions rp 
        INNER JOIN permissions p ON rp.permission_id = p.id 
        INNER JOIN user_roles ur ON rp.role_id = ur.role_id 
        INNER JOIN roles r ON ur.role_id = r.id
        WHERE ur.user_id = ?
        ORDER BY p.name
    ");
    $stmt->execute([$current_user_id]);
    $userPermissions = $stmt->fetchAll();
    
    echo "<ul>";
    foreach ($userPermissions as $perm) {
        echo "<li>{$perm['name']} ({$perm['display_name']}) - Rol: {$perm['role_name']}</li>";
    }
    echo "</ul>";
} else {
    echo "<p>No hay usuario logueado</p>";
}
?>