<?php
session_start();

// Habilitar logging para depuración
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';

$userData = JWTAuth::requireAuth();

// Verificar permiso para ver la página de destinatarios
if (!hasPermission('view_recipients', 'discord')) {
    die('No tienes permiso para ver los destinatarios de Discord.');
}

$db = getDB();

// Obtener destinatarios
$stmt = $db->query("SELECT * FROM destinatarios_discord ORDER BY nombre ASC");
$destinatarios = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="<?php echo $userData->idioma ?? 'es'; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Destinatarios Discord - Sistema de Bots</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --discord-color: #5865F2;
            --discord-dark: #4752C4;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, var(--discord-color) 0%, var(--discord-dark) 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .header {
            background: white;
            border-radius: 15px;
            padding: 20px 30px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }
        
        .header h1 {
            color: var(--discord-color);
            font-size: 24px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .table-responsive {
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        
        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            font-weight: 600;
            color: #555;
            background: #f8f9fa;
        }
        
        .badge {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-channel {
            background: #e3e7ff;
            color: var(--discord-color);
        }
        
        .badge-user {
            background: #d4edda;
            color: #155724;
        }

        .badge-grupo {
            background: #fff3cd;
            color: #856404;
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
        }
        
        .btn-primary {
            background: var(--discord-color);
            color: white;
        }
        
        .btn-primary:hover {
            background: var(--discord-dark);
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
            padding: 5px 10px;
            font-size: 12px;
        }
        
        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
        }
        
        .modal-content {
            background: white;
            margin: 10% auto;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 500px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
        }
        
        .form-control {
            width: 100%;
            padding: 10px;
            border: 2px solid #eee;
            border-radius: 8px;
        }
        
        .close {
            float: right;
            font-size: 24px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-users"></i> Destinatarios Discord</h1>
        <div style="display: flex; gap: 10px;">
            <a href="/discord/dashboard_discord.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Volver
            </a>
            <?php if (hasPermission('manage_recipients', 'discord')): ?>
            <button onclick="openCreateModal()" class="btn btn-primary">
                <i class="fas fa-plus"></i> Nuevo Destinatario
            </button>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="container">
        <div class="card">
            <?php if (empty($destinatarios)): ?>
                <div style="text-align: center; padding: 40px; color: #666;">
                    <i class="fas fa-users-slash" style="font-size: 48px; margin-bottom: 20px; color: #ddd;"></i>
                    <h3>No hay destinatarios guardados</h3>
                    <p>Agrega canales o usuarios frecuentes para enviar mensajes más rápido.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th>Nombre</th>
                                <th>Tipo</th>
                                <th>ID Discord</th>
                                <th>Fecha Registro</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($destinatarios as $dest): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($dest['nombre']); ?></strong>
                                    </td>
                                    <td>
                                        <span class="badge <?php 
                                            if ($dest['tipo'] == 'canal') echo 'badge-channel'; 
                                            else if ($dest['tipo'] == 'usuario') echo 'badge-user';
                                            else if ($dest['tipo'] == 'grupo') echo 'badge-grupo';
                                        ?>">
                                            <?php echo ucfirst($dest['tipo']); ?>
                                        </span>
                                    </td>
                                    <td><code><?php echo htmlspecialchars($dest['discord_id']); ?></code></td>
                                    <td><?php echo date('d/m/Y', strtotime($dest['fecha_registro'])); ?></td>
                                    <td>
                                        <?php if (hasPermission('manage_recipients', 'discord')): ?>
                                        <button onclick="editRecipient(<?php echo $dest['id']; ?>, '<?php echo htmlspecialchars($dest['nombre'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($dest['discord_id'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($dest['tipo'], ENT_QUOTES); ?>')" class="btn btn-primary" style="padding: 5px 10px; font-size: 12px;">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <?php if ($dest['tipo'] === 'usuario'): ?>
                                        <button onclick="kickRecipient(<?php echo $dest['id']; ?>)" class="btn btn-danger" style="padding: 5px 10px; font-size: 12px;">
                                            <i class="fas fa-user-slash"></i> Expulsar
                                        </button>
                                        <?php endif; ?>
                                        <button onclick="deleteRecipient(<?php echo $dest['id']; ?>)" class="btn btn-danger" style="padding: 5px 10px; font-size: 12px;">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Modal Crear -->
    <div id="createModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeCreateModal()">&times;</span>
            <h2 style="margin-bottom: 20px;">Nuevo Destinatario</h2>
            <form id="createForm">
                <div class="form-group">
                    <label>Nombre (Alias)</label>
                    <input type="text" name="nombre" class="form-control" required placeholder="Ej: Canal General">
                </div>
                <div class="form-group">
                    <label>ID de Discord</label>
                    <input type="text" name="discord_id" class="form-control" required placeholder="Ej: 123456789012345678">
                </div>
                <div class="form-group">
                    <label>Tipo</label>
                    <select name="tipo" class="form-control">
                        <option value="canal">Canal</option>
                        <option value="usuario">Usuario (DM)</option>
                        <option value="grupo">Grupo</option>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary" style="width: 100%;">Guardar</button>
            </form>
        </div>
    </div>

    <!-- Modal Editar -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeEditModal()">&times;</span>
            <h2 style="margin-bottom: 20px;">Editar Destinatario</h2>
            <form id="editForm">
                <input type="hidden" id="edit_id" name="id">
                <div class="form-group">
                    <label>Nombre (Alias)</label>
                    <input type="text" id="edit_nombre" name="nombre" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>ID de Discord</label>
                    <input type="text" id="edit_discord_id" name="discord_id" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>Tipo</label>
                    <select id="edit_tipo" name="tipo" class="form-control">
                        <option value="canal">Canal</option>
                        <option value="usuario">Usuario (DM)</option>
                        <option value="grupo">Grupo</option>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary" style="width: 100%;">Guardar Cambios</button>
            </form>
        </div>
    </div>

    <script>
        function openCreateModal() {
            document.getElementById('createModal').style.display = 'block';
        }
        
        function closeCreateModal() {
            document.getElementById('createModal').style.display = 'none';
        }

        function openEditModal() {
            document.getElementById('editModal').style.display = 'block';
        }

        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        function editRecipient(id, nombre, discord_id, tipo) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_nombre').value = nombre;
            document.getElementById('edit_discord_id').value = discord_id;
            document.getElementById('edit_tipo').value = tipo;
            openEditModal();
        }
        
        document.getElementById('createForm').onsubmit = async function(e) {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());
            
            try {
                const response = await fetch('/discord/api/recipients/create.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data)
                });
                const result = await response.json();
                
                if (result.success) {
                    location.reload();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error(error);
                alert('Error de conexión');
            }
        };

        document.getElementById('editForm').onsubmit = async function(e) {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());
            
            try {
                const response = await fetch('/discord/api/recipients/edit.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data)
                });
                const result = await response.json();
                
                if (result.success) {
                    location.reload();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error(error);
                alert('Error de conexión');
            }
        };
        
        async function deleteRecipient(id) {
            if (!confirm('¿Eliminar este destinatario? Esta acción es solo local.')) return;
            
            try {
                const response = await fetch('/discord/api/recipients/delete.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({id})
                });
                const result = await response.json();
                
                if (result.success) {
                    location.reload();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error(error);
                alert('Error de conexión');
            }
        }

        async function kickRecipient(id) {
            if (!confirm('¿Estás seguro de expulsar este usuario de Discord? Esta acción es irreversible en Discord.')) return;
            
            try {
                const response = await fetch('/discord/api/recipients/kick.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({id})
                });
                const result = await response.json();
                
                if (result.success) {
                    alert('Usuario expulsado de Discord y eliminado de la lista local.');
                    location.reload();
                } else {
                    alert('Error al expulsar: ' + result.error);
                }
            } catch (error) {
                console.error(error);
                alert('Error de conexión');
            }
        }
        
        window.onclick = function(event) {
            if (event.target == document.getElementById('createModal')) {
                closeCreateModal();
            }
            if (event.target == document.getElementById('editModal')) {
                closeEditModal();
            }
        }
    </script>
</body>
</html>