<?php
session_start();
require_once '../../database/connection.php';

// Simular usuario logueado para pruebas
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = 1;
    $_SESSION['username'] = 'admin';
    $_SESSION['role'] = 'admin';
}

echo "<h1>Diagnóstico y Corrección - Permisos de Desk</h1>";
echo "<style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
    .success { background-color: #d4edda; border-color: #c3e6cb; }
    .error { background-color: #f8d7da; border-color: #f5c6cb; }
    .warning { background-color: #fff3cd; border-color: #ffeaa7; }
    .info { background-color: #d1ecf1; border-color: #bee5eb; }
    pre { background: #f8f9fa; padding: 10px; border-radius: 3px; overflow-x: auto; }
    .fix-button { padding: 10px 15px; margin: 5px; background: #28a745; color: white; border: none; border-radius: 3px; cursor: pointer; }
    .fix-button:hover { background: #218838; }
    table { border-collapse: collapse; width: 100%; margin: 10px 0; }
    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
    th { background-color: #f2f2f2; }
</style>";

try {
    $pdo = getDB()->getConnection();
    
    // 1. Verificar estructura de tablas
    echo "<div class='section info'>";
    echo "<h2>1. Verificación de Estructura de Tablas</h2>";
    
    // Verificar tabla desk_allowed_statuses
    $stmt = $pdo->query("SHOW TABLES LIKE 'desk_allowed_statuses'");
    if ($stmt->rowCount() > 0) {
        echo "<p class='success'>✓ Tabla 'desk_allowed_statuses' existe</p>";
        
        // Mostrar estructura
        $stmt = $pdo->query("DESCRIBE desk_allowed_statuses");
        $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo "<h4>Estructura de desk_allowed_statuses:</h4>";
        echo "<table><tr><th>Campo</th><th>Tipo</th><th>Null</th><th>Key</th><th>Default</th></tr>";
        foreach ($columns as $col) {
            echo "<tr><td>{$col['Field']}</td><td>{$col['Type']}</td><td>{$col['Null']}</td><td>{$col['Key']}</td><td>{$col['Default']}</td></tr>";
        }
        echo "</table>";
    } else {
        echo "<p class='error'>✗ Tabla 'desk_allowed_statuses' NO existe</p>";
        echo "<button class='fix-button' onclick='createTable()'>Crear Tabla</button>";
    }
    
    // Verificar tabla desks
    $stmt = $pdo->query("SHOW TABLES LIKE 'desks'");
    if ($stmt->rowCount() > 0) {
        echo "<p class='success'>✓ Tabla 'desks' existe</p>";
    } else {
        echo "<p class='error'>✗ Tabla 'desks' NO existe</p>";
    }
    echo "</div>";
    
    // 2. Verificar datos actuales
    echo "<div class='section info'>";
    echo "<h2>2. Datos Actuales</h2>";
    
    // Mostrar desks existentes
    $stmt = $pdo->query("SELECT id, name FROM desks ORDER BY id");
    $desks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if ($desks) {
        echo "<h4>Desks existentes:</h4>";
        echo "<table><tr><th>ID</th><th>Nombre</th></tr>";
        foreach ($desks as $desk) {
            echo "<tr><td>{$desk['id']}</td><td>{$desk['name']}</td></tr>";
        }
        echo "</table>";
    } else {
        echo "<p class='warning'>⚠ No hay desks configurados</p>";
    }
    
    // Mostrar permisos actuales si la tabla existe
    $stmt = $pdo->query("SHOW TABLES LIKE 'desk_allowed_statuses'");
    if ($stmt->rowCount() > 0) {
        $stmt = $pdo->query("SELECT das.desk_id, d.name as desk_name, das.status 
                            FROM desk_allowed_statuses das 
                            LEFT JOIN desks d ON das.desk_id = d.id 
                            ORDER BY das.desk_id, das.status");
        $permissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if ($permissions) {
            echo "<h4>Permisos de status por desk:</h4>";
            echo "<table><tr><th>Desk ID</th><th>Desk Name</th><th>Status Permitido</th></tr>";
            foreach ($permissions as $perm) {
                echo "<tr><td>{$perm['desk_id']}</td><td>{$perm['desk_name']}</td><td>{$perm['status']}</td></tr>";
            }
            echo "</table>";
        } else {
            echo "<p class='warning'>⚠ No hay permisos de status configurados</p>";
            echo "<button class='fix-button' onclick='addDefaultPermissions()'>Agregar Permisos por Defecto</button>";
        }
    }
    echo "</div>";
    
    // 3. Verificar lead específico
    echo "<div class='section info'>";
    echo "<h2>3. Verificación de Lead Específico</h2>";
    
    // Buscar un lead para probar
    $stmt = $pdo->query("SELECT id, desk_id, status, first_name, last_name FROM leads WHERE id = 10292 OR id IN (SELECT id FROM leads LIMIT 1)");
    $lead = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($lead) {
        echo "<h4>Lead de prueba:</h4>";
        echo "<table><tr><th>ID</th><th>Desk ID</th><th>Status Actual</th><th>Nombre</th></tr>";
        echo "<tr><td>{$lead['id']}</td><td>{$lead['desk_id']}</td><td>{$lead['status']}</td><td>{$lead['first_name']} {$lead['last_name']}</td></tr>";
        echo "</table>";
        
        // Verificar permisos para este desk
        if ($lead['desk_id']) {
            $stmt = $pdo->prepare("SELECT status FROM desk_allowed_statuses WHERE desk_id = ?");
            $stmt->execute([$lead['desk_id']]);
            $allowed_statuses = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            if ($allowed_statuses) {
                echo "<h4>Status permitidos para Desk {$lead['desk_id']}:</h4>";
                echo "<p>" . implode(', ', $allowed_statuses) . "</p>";
            } else {
                echo "<p class='error'>✗ No hay status permitidos para Desk {$lead['desk_id']}</p>";
                echo "<button class='fix-button' onclick='fixDeskPermissions({$lead['desk_id']})'>Corregir Permisos para este Desk</button>";
            }
        } else {
            echo "<p class='error'>✗ El lead no tiene desk_id asignado</p>";
        }
    } else {
        echo "<p class='error'>✗ No se encontraron leads para probar</p>";
    }
    echo "</div>";
    
} catch (Exception $e) {
    echo "<div class='section error'>";
    echo "<h2>Error</h2>";
    echo "<p>Error: " . $e->getMessage() . "</p>";
    echo "</div>";
}
?>

<script>
function createTable() {
    if (confirm('¿Crear la tabla desk_allowed_statuses?')) {
        fetch('fix_desk_permissions.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=create_table'
        })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
            if (data.success) location.reload();
        })
        .catch(error => alert('Error: ' + error));
    }
}

function addDefaultPermissions() {
    if (confirm('¿Agregar permisos por defecto para todos los desks?')) {
        fetch('fix_desk_permissions.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=add_default_permissions'
        })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
            if (data.success) location.reload();
        })
        .catch(error => alert('Error: ' + error));
    }
}

function fixDeskPermissions(deskId) {
    if (confirm(`¿Agregar permisos por defecto para el Desk ${deskId}?`)) {
        fetch('fix_desk_permissions.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=fix_desk_permissions&desk_id=${deskId}`
        })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
            if (data.success) location.reload();
        })
        .catch(error => alert('Error: ' + error));
    }
}
</script>