<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/session_check.php';
require_once __DIR__ . '/../includes/activity_logger.php';

requireAdmin();

$pageTitle = 'Gestión de Destinatarios';

$recipients = [];
$languages = [];

try {
    $pdo = getDbConnection();
    
    $stmt = $pdo->query("SELECT * FROM recipients ORDER BY platform, name");
    $recipients = $stmt->fetchAll();
    
    $stmt = $pdo->query("SELECT * FROM supported_languages ORDER BY language_name");
    $languages = $stmt->fetchAll();
} catch (Exception $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'add') {
        $platformId = $_POST['platform_id'];
        $name = $_POST['name'];
        $type = $_POST['type'];
        $platform = $_POST['platform'];
        $languageCode = $_POST['language_code'];
        
        $stmt = $pdo->prepare("
            INSERT INTO recipients (platform_id, name, type, platform, language_code, created_at)
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        $stmt->execute([$platformId, $name, $type, $platform, $languageCode]);
        
        logActivity(getCurrentUserId(), 'add_recipient', "Destinatario agregado: $name ($platform)");
        header('Location: recipients.php');
        exit;
        
    } elseif ($action === 'update_language') {
        $recipientId = (int) $_POST['recipient_id'];
        $languageCode = $_POST['language_code'];
        
        $stmt = $pdo->prepare("UPDATE recipients SET language_code = ? WHERE id = ?");
        $stmt->execute([$languageCode, $recipientId]);
        
        header('Location: recipients.php');
        exit;
        
    } elseif ($action === 'delete') {
        $recipientId = (int) $_POST['recipient_id'];
        
        $stmt = $pdo->prepare("DELETE FROM recipients WHERE id = ?");
        $stmt->execute([$recipientId]);
        
        logActivity(getCurrentUserId(), 'delete_recipient', "Destinatario eliminado ID: $recipientId");
        header('Location: recipients.php');
        exit;
    }
}

require_once __DIR__ . '/../templates/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-person-check"></i> Gestión de Destinatarios</h2>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRecipientModal">
        <i class="bi bi-plus-circle"></i> Nuevo Destinatario
    </button>
</div>

<?php if (isset($error)): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<ul class="nav nav-tabs mb-3">
    <li class="nav-item">
        <a class="nav-link active" href="#discord" data-bs-toggle="tab">Discord</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#telegram" data-bs-toggle="tab">Telegram</a>
    </li>
</ul>

<div class="tab-content">
    <div class="tab-pane fade show active" id="discord">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <?php $discordRecipients = array_filter($recipients, fn($r) => $r['platform'] === 'discord'); ?>
                <?php if (empty($discordRecipients)): ?>
                    <p class="text-muted">No hay destinatarios de Discord</p>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Platform ID</th>
                                    <th>Nombre</th>
                                    <th>Tipo</th>
                                    <th>Idioma</th>
                                    <th>Creado</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($discordRecipients as $recipient): ?>
                                <tr>
                                    <td><?= $recipient['id'] ?></td>
                                    <td><code><?= $recipient['platform_id'] ?></code></td>
                                    <td><?= htmlspecialchars($recipient['name']) ?></td>
                                    <td><?= $recipient['type'] ?></td>
                                    <td>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="action" value="update_language">
                                            <input type="hidden" name="recipient_id" value="<?= $recipient['id'] ?>">
                                            <select name="language_code" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
                                                <?php foreach ($languages as $lang): ?>
                                                <option value="<?= $lang['language_code'] ?>" <?= $recipient['language_code'] === $lang['language_code'] ? 'selected' : '' ?>>
                                                    <?= $lang['flag_emoji'] ?> <?= $lang['language_name'] ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </form>
                                    </td>
                                    <td><?= date('d/m/Y', strtotime($recipient['created_at'])) ?></td>
                                    <td>
                                        <form method="POST" onsubmit="return confirm('¿Eliminar?');" class="d-inline">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="recipient_id" value="<?= $recipient['id'] ?>">
                                            <button type="submit" class="btn btn-outline-danger btn-sm">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div class="tab-pane fade" id="telegram">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <?php $telegramRecipients = array_filter($recipients, fn($r) => $r['platform'] === 'telegram'); ?>
                <?php if (empty($telegramRecipients)): ?>
                    <p class="text-muted">No hay destinatarios de Telegram</p>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Platform ID</th>
                                    <th>Nombre</th>
                                    <th>Tipo</th>
                                    <th>Idioma</th>
                                    <th>Creado</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($telegramRecipients as $recipient): ?>
                                <tr>
                                    <td><?= $recipient['id'] ?></td>
                                    <td><code><?= $recipient['platform_id'] ?></code></td>
                                    <td><?= htmlspecialchars($recipient['name']) ?></td>
                                    <td><?= $recipient['type'] ?></td>
                                    <td>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="action" value="update_language">
                                            <input type="hidden" name="recipient_id" value="<?= $recipient['id'] ?>">
                                            <select name="language_code" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
                                                <?php foreach ($languages as $lang): ?>
                                                <option value="<?= $lang['language_code'] ?>" <?= $recipient['language_code'] === $lang['language_code'] ? 'selected' : '' ?>>
                                                    <?= $lang['flag_emoji'] ?> <?= $lang['language_name'] ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </form>
                                    </td>
                                    <td><?= date('d/m/Y', strtotime($recipient['created_at'])) ?></td>
                                    <td>
                                        <form method="POST" onsubmit="return confirm('¿Eliminar?');" class="d-inline">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="recipient_id" value="<?= $recipient['id'] ?>">
                                            <button type="submit" class="btn btn-outline-danger btn-sm">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Modal para agregar destinatario -->
<div class="modal fade" id="addRecipientModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="add">
                
                <div class="modal-header">
                    <h5 class="modal-title">Nuevo Destinatario</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Plataforma</label>
                        <select name="platform" class="form-select" required>
                            <option value="discord">Discord</option>
                            <option value="telegram">Telegram</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">ID en la plataforma</label>
                        <input type="text" name="platform_id" class="form-control" required placeholder="Ej: 123456789">
                        <small class="text-muted">ID del canal/usuario en Discord o Telegram</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Nombre</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Tipo</label>
                        <select name="type" class="form-select" required>
                            <option value="channel">Canal</option>
                            <option value="user">Usuario</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Idioma</label>
                        <select name="language_code" class="form-select">
                            <?php foreach ($languages as $lang): ?>
                            <option value="<?= $lang['language_code'] ?>">
                                <?= $lang['flag_emoji'] ?> <?= $lang['language_name'] ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Agregar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
