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

requireAdmin();

$pageTitle = 'Mensajes de Bienvenida por Grupo';

try {
    $pdo = getDbConnection();
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';
        
        if ($action === 'add') {
            $chatId = $_POST['chat_id'];
            $welcomeMessage = $_POST['welcome_message'];
            $buttonText = $_POST['button_text'];
            $groupInviteLink = $_POST['group_invite_link'];
            $languageCode = $_POST['language_code'];
            $languageName = $_POST['language_name'];
            $flagEmoji = $_POST['flag_emoji'];
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            
            $stmt = $pdo->prepare("
                INSERT INTO telegram_welcome_messages 
                (chat_id, welcome_message, button_text, group_invite_link, language_code, language_name, flag_emoji, is_active)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$chatId, $welcomeMessage, $buttonText, $groupInviteLink, $languageCode, $languageName, $flagEmoji, $isActive]);
            
            logActivity(getCurrentUserId(), 'add_group_welcome', "Mensaje de bienvenida agregado para grupo: $chatId");
            header('Location: telegram_welcome.php');
            exit;
            
        } elseif ($action === 'update') {
            $id = $_POST['id'];
            $welcomeMessage = $_POST['welcome_message'];
            $buttonText = $_POST['button_text'];
            $groupInviteLink = $_POST['group_invite_link'];
            $languageCode = $_POST['language_code'];
            $languageName = $_POST['language_name'];
            $flagEmoji = $_POST['flag_emoji'];
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            
            $stmt = $pdo->prepare("
                UPDATE telegram_welcome_messages 
                SET welcome_message = ?, button_text = ?, group_invite_link = ?, 
                    language_code = ?, language_name = ?, flag_emoji = ?, is_active = ?
                WHERE id = ?
            ");
            $stmt->execute([$welcomeMessage, $buttonText, $groupInviteLink, $languageCode, $languageName, $flagEmoji, $isActive, $id]);
            
            logActivity(getCurrentUserId(), 'update_group_welcome', "Mensaje de bienvenida actualizado ID: $id");
            header('Location: telegram_welcome.php');
            exit;
            
        } elseif ($action === 'delete') {
            $id = $_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM telegram_welcome_messages WHERE id = ?");
            $stmt->execute([$id]);
            
            logActivity(getCurrentUserId(), 'delete_group_welcome', "Mensaje de bienvenida eliminado ID: $id");
            header('Location: telegram_welcome.php');
            exit;
        }
    }
    
    $stmt = $pdo->query("SELECT * FROM telegram_welcome_messages ORDER BY created_at DESC");
    $welcomeMessages = $stmt->fetchAll();
    
} catch (Exception $e) {
    $error = $e->getMessage();
}

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-telegram"></i> Mensajes de Bienvenida por Grupo</h2>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#welcomeModal">
        <i class="bi bi-plus-circle"></i> Nuevo Mensaje
    </button>
</div>

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

<div class="row">
    <?php if (empty($welcomeMessages)): ?>
        <div class="col-12">
            <p class="text-muted text-center py-4">No hay mensajes de bienvenida configurados</p>
        </div>
    <?php else: ?>
        <?php foreach ($welcomeMessages as $msg): ?>
        <div class="col-md-6 mb-4">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0"><?= htmlspecialchars($msg['flag_emoji'] ?? '') ?> <?= htmlspecialchars($msg['language_name'] ?? 'Grupo') ?></h6>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editModal<?= $msg['id'] ?>">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <form method="POST" onsubmit="return confirm('¿Eliminar?');" class="d-inline">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= $msg['id'] ?>">
                            <button type="submit" class="btn btn-outline-danger">
                                <i class="bi bi-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
                <div class="card-body">
                    <p class="text-muted small mb-1">Chat ID: <?= $msg['chat_id'] ?></p>
                    <p class="mb-1"><?= nl2br(htmlspecialchars($msg['welcome_message'] ?? '')) ?></p>
                    <small class="text-muted"><?= $msg['is_active'] ? '✅ Activo' : '❌ Inactivo' ?></small>
                </div>
            </div>
        </div>
        
        <div class="modal fade" id="editModal<?= $msg['id'] ?>" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <form method="POST">
                        <input type="hidden" name="action" value="update">
                        <input type="hidden" name="id" value="<?= $msg['id'] ?>">
                        <div class="modal-header">
                            <h5 class="modal-title">Editar Mensaje</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">Mensaje de bienvenida</label>
                                <textarea name="welcome_message" class="form-control" rows="3"><?= htmlspecialchars($msg['welcome_message'] ?? '') ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Texto del botón</label>
                                <input type="text" name="button_text" class="form-control" value="<?= htmlspecialchars($msg['button_text'] ?? '') ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Enlace de invitación</label>
                                <input type="text" name="group_invite_link" class="form-control" value="<?= htmlspecialchars($msg['group_invite_link'] ?? '') ?>">
                            </div>
                            <div class="row mb-3">
                                <div class="col-4">
                                    <label class="form-label">Código idioma</label>
                                    <input type="text" name="language_code" class="form-control" value="<?= htmlspecialchars($msg['language_code'] ?? 'es') ?>">
                                </div>
                                <div class="col-4">
                                    <label class="form-label">Nombre idioma</label>
                                    <input type="text" name="language_name" class="form-control" value="<?= htmlspecialchars($msg['language_name'] ?? 'Español') ?>">
                                </div>
                                <div class="col-4">
                                    <label class="form-label">Flag</label>
                                    <input type="text" name="flag_emoji" class="form-control" value="<?= htmlspecialchars($msg['flag_emoji'] ?? '🇪🇸') ?>">
                                </div>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_active" id="editActive<?= $msg['id'] ?>" <?= $msg['is_active'] ? 'checked' : '' ?>>
                                <label class="form-check-label" for="editActive<?= $msg['id'] ?>">Activo</label>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary">Guardar</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<div class="modal fade" id="welcomeModal" 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 Mensaje de Bienvenida</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">Chat ID del grupo</label>
                        <input type="text" name="chat_id" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Mensaje de bienvenida</label>
                        <textarea name="welcome_message" class="form-control" rows="3" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Texto del botón</label>
                        <input type="text" name="button_text" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Enlace de invitación</label>
                        <input type="text" name="group_invite_link" class="form-control">
                    </div>
                    <div class="row mb-3">
                        <div class="col-4">
                            <label class="form-label">Código idioma</label>
                            <input type="text" name="language_code" class="form-control" value="es">
                        </div>
                        <div class="col-4">
                            <label class="form-label">Nombre idioma</label>
                            <input type="text" name="language_name" class="form-control" value="Español">
                        </div>
                        <div class="col-4">
                            <label class="form-label">Flag</label>
                            <input type="text" name="flag_emoji" class="form-control" value="🇪🇸">
                        </div>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_active" id="newActive" checked>
                        <label class="form-check-label" for="newActive">Activo</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Agregar</button>
                </div>
            </form>
        </div>
    </div>
</div>

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