<?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', 'telegram')) {
    die('No tienes permiso para ver los destinatarios de Telegram.');
}

$db = getDB();

// Obtener destinatarios
$stmt = $db->query("SELECT * FROM destinatarios_telegram 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 Telegram - 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 {
            --telegram-color: #0088cc;
            --telegram-dark: #006699;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, var(--telegram-color) 0%, var(--telegram-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(--telegram-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: #e3f2fd;
            color: var(--telegram-color);
        }
        
        .badge-user {
            background: #e0f2f1;
            color: #00796b;
        }
        
        .badge-grupo {
            background: #fff8e1;
            color: #ff8f00;
        }
        
        .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(--telegram-color);
            color: white;
        }
        
        .btn-primary:hover {
            background: var(--telegram-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 Telegram</h1>
        <div style="display: flex; gap: 10px;">
            <a href="/telegram/dashboard_telegram.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Volver
            </a>
            <?php if (hasPermission('manage_recipients', 'telegram')): ?>
            <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 chats 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 Telegram</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['telegram_id']); ?></code></td>
                                    <td><?php echo date('d/m/Y', strtotime($dest['fecha_registro'])); ?></td>
                                    <td>
                                        <?php if (hasPermission('manage_recipients', 'telegram')): ?>
                                        <button onclick="editRecipient(<?php echo $dest['id']; ?>, '<?php echo htmlspecialchars($dest['nombre'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($dest['telegram_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' || $dest['tipo'] === 'grupo'): // Only kick users or remove bot from groups ?>
                                        <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 Telegram</label>
                    <input type="text" name="telegram_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 Telegram</label>
                    <input type="text" id="edit_telegram_id" name="telegram_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, telegram_id, tipo) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_nombre').value = nombre;
            document.getElementById('edit_telegram_id').value = telegram_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('/telegram/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('/telegram/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?')) return;
            
            try {
                const response = await fetch('/telegram/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 intentar expulsar/remover este destinatario de Telegram? Para usuarios, esto solo lo eliminará de la base de datos local (requiere chat_id para expulsión real). Para chats/canales/grupos, el bot intentará abandonarlos.')) return;
            
            try {
                const response = await fetch('/telegram/api/recipients/kick.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({id})
                });
                const result = await response.json();
                
                if (result.success) {
                    alert('Destinatario procesado para expulsión/eliminación.');
                    location.reload();
                } else {
                    alert('Error al expulsar/remover: ' + 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>