<?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 de Usuario - Leads</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) {
    // Información del usuario
    echo "<h3>1. Información del Usuario</h3>";
    $user = $pdo->prepare("SELECT id, username, email, first_name, last_name FROM users WHERE id = ?");
    $user->execute([$current_user_id]);
    $userData = $user->fetch();
    
    if ($userData) {
        echo "<pre>";
        echo "ID: {$userData['id']}\n";
        echo "Username: {$userData['username']}\n";
        echo "Email: {$userData['email']}\n";
        echo "Nombre: {$userData['first_name']} {$userData['last_name']}\n";
        echo "</pre>";
    } else {
        echo "<p style='color: red;'>Usuario no encontrado en la base de datos!</p>";
    }
    
    // Roles del usuario
    echo "<h3>2. Roles del Usuario</h3>";
    $roles = $pdo->prepare("SELECT r.id, r.name, r.display_name FROM user_roles ur INNER JOIN roles r ON ur.role_id = r.id WHERE ur.user_id = ?");
    $roles->execute([$current_user_id]);
    $userRoles = $roles->fetchAll();
    
    if ($userRoles) {
        echo "<ul>";
        foreach ($userRoles as $role) {
            echo "<li>ID: {$role['id']}, Nombre: {$role['name']}, Título: {$role['display_name']}</li>";
        }
        echo "</ul>";
    } else {
        echo "<p style='color: red;'>El usuario no tiene roles asignados!</p>";
    }
    
    // Permisos específicos de leads
    echo "<h3>3. Permisos de Leads</h3>";
    $leadPermissions = ['leads.view', 'leads.view_all', 'leads.create', 'leads.edit', 'leads.edit_all', 'leads.delete'];
    
    foreach ($leadPermissions as $perm) {
        $hasPermission = userHasPermissionByName($pdo, $perm, $current_user_id);
        $color = $hasPermission ? 'green' : 'red';
        echo "<p style='color: $color;'>Permiso '$perm': " . ($hasPermission ? 'SÍ' : 'NO') . "</p>";
    }
    
    // Todos los permisos del usuario
    echo "<h3>4. 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();
    
    if ($userPermissions) {
        echo "<ul>";
        foreach ($userPermissions as $perm) {
            echo "<li>{$perm['name']} ({$perm['display_name']}) - Rol: {$perm['role_name']}</li>";
        }
        echo "</ul>";
    } else {
        echo "<p style='color: red;'>El usuario no tiene permisos asignados!</p>";
    }
    
    // Verificar leads en la base de datos
    echo "<h3>5. Leads en la Base de Datos</h3>";
    $totalLeads = $pdo->query("SELECT COUNT(*) FROM leads")->fetchColumn();
    echo "<p>Total de leads: $totalLeads</p>";
    
    // Leads asignados al usuario
    $assignedLeads = $pdo->prepare("SELECT COUNT(*) FROM leads WHERE assigned_to = ?");
    $assignedLeads->execute([$current_user_id]);
    $assignedCount = $assignedLeads->fetchColumn();
    echo "<p>Leads asignados al usuario: $assignedCount</p>";
    
    // Leads sin asignar
    $unassignedLeads = $pdo->query("SELECT COUNT(*) FROM leads WHERE assigned_to IS NULL")->fetchColumn();
    echo "<p>Leads sin asignar: $unassignedLeads</p>";
    
    // Simular la consulta del index.php
    echo "<h3>6. Simulación de la Consulta del Index.php</h3>";
    
    $canViewAll = userHasPermissionByName($pdo, 'leads.view_all', $current_user_id);
    echo "<p>Puede ver todos los leads: " . ($canViewAll ? 'SÍ' : 'NO') . "</p>";
    
    // Construir la consulta como en index.php
    $whereConditions = [];
    $params = [];
    
    if (!$canViewAll) {
        $whereConditions[] = "(l.assigned_to = ? OR l.assigned_to IS NULL)";
        $params[] = $current_user_id;
    }
    
    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
    
    $sql = "SELECT l.*, d.name as desk_name, u.first_name as assigned_first_name, u.last_name as assigned_last_name 
            FROM leads l 
            LEFT JOIN desks d ON l.desk_id = d.id 
            LEFT JOIN users u ON l.assigned_to = u.id 
            $whereClause 
            ORDER BY l.created_at DESC 
            LIMIT 10";
    
    echo "<p><strong>Consulta SQL:</strong></p>";
    echo "<pre>$sql</pre>";
    echo "<p><strong>Parámetros:</strong> " . implode(', ', $params) . "</p>";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $leads = $stmt->fetchAll();
    
    echo "<p><strong>Resultados encontrados:</strong> " . count($leads) . "</p>";
    
    if ($leads) {
        echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
        echo "<tr><th>ID</th><th>Nombre</th><th>Email</th><th>Estado</th><th>Asignado a</th><th>Desk</th></tr>";
        foreach ($leads as $lead) {
            echo "<tr>";
            echo "<td>{$lead['id']}</td>";
            echo "<td>{$lead['first_name']} {$lead['last_name']}</td>";
            echo "<td>{$lead['email']}</td>";
            echo "<td>{$lead['status']}</td>";
            echo "<td>" . ($lead['assigned_first_name'] ? $lead['assigned_first_name'] . ' ' . $lead['assigned_last_name'] : 'Sin asignar') . "</td>";
            echo "<td>" . ($lead['desk_name'] ?? 'Sin desk') . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    
} else {
    echo "<p style='color: red;'>No hay usuario logueado</p>";
}
?>