<?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);

echo "<h2>Asignación de Permisos para Visualización de Leads</h2>";
echo "<p>Usuario ID: " . $current_user_id . "</p>";

if ($current_user_id > 0) {
    try {
        // Verificar si el usuario ya tiene el rol admin
        $adminRole = $pdo->prepare("SELECT ur.role_id FROM user_roles ur INNER JOIN roles r ON ur.role_id = r.id WHERE ur.user_id = ? AND r.name = 'admin'");
        $adminRole->execute([$current_user_id]);
        $hasAdminRole = $adminRole->fetch();
        
        if ($hasAdminRole) {
            echo "<p style='color: green;'>El usuario ya tiene rol de administrador.</p>";
        } else {
            // Asignar rol de administrador al usuario
            $adminRoleId = $pdo->query("SELECT id FROM roles WHERE name = 'admin' LIMIT 1")->fetchColumn();
            
            if ($adminRoleId) {
                $insertRole = $pdo->prepare("INSERT IGNORE INTO user_roles (user_id, role_id, assigned_at) VALUES (?, ?, NOW())");
                $insertRole->execute([$current_user_id, $adminRoleId]);
                echo "<p style='color: green;'>Rol de administrador asignado correctamente.</p>";
            } else {
                echo "<p style='color: red;'>No se encontró el rol de administrador.</p>";
            }
        }
        
        // Verificar permisos después de la asignación
        echo "<h3>Verificación de Permisos Después de la Asignación</h3>";
        
        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();
        }
        
        $leadPermissions = ['leads.view', 'leads.view_all', 'leads.create', 'leads.edit', 'leads.edit_all'];
        
        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>";
        }
        
        // Probar la consulta de leads
        echo "<h3>Prueba de Consulta de Leads</h3>";
        
        $canViewAll = userHasPermissionByName($pdo, 'leads.view_all', $current_user_id);
        echo "<p>Puede ver todos los leads: " . ($canViewAll ? 'SÍ' : 'NO') . "</p>";
        
        if ($canViewAll) {
            $leads = $pdo->query("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 
                                  ORDER BY l.created_at DESC 
                                  LIMIT 10")->fetchAll();
            
            echo "<p><strong>Leads encontrados:</strong> " . count($leads) . "</p>";
            
            if ($leads) {
                echo "<table border='1' style='border-collapse: collapse; width: 100%; margin-top: 10px;'>";
                echo "<tr style='background-color: #f0f0f0;'><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>";
            }
        }
        
        echo "<h3>Resultado</h3>";
        echo "<p style='color: green; font-weight: bold;'>✅ Permisos asignados correctamente. Ahora puedes acceder al listado de leads.</p>";
        echo "<p><a href='modules/leads/index.php' style='background-color: #007cba; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Ir al Listado de Leads</a></p>";
        
    } catch (Exception $e) {
        echo "<p style='color: red;'>Error: " . $e->getMessage() . "</p>";
    }
} else {
    echo "<p style='color: red;'>No hay usuario logueado</p>";
}
?>