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

requireAdmin();

$pageTitle = 'Chat Telegram';

$interactions = [];
$selectedUser = $_GET['user_id'] ?? null;

try {
    $pdo = getDbConnection();
    
    if ($selectedUser) {
        $stmt = $pdo->prepare("
            SELECT * FROM telegram_bot_interactions 
            WHERE user_id = ?
            ORDER BY interaction_date DESC
            LIMIT 100
        ");
        $stmt->execute([$selectedUser]);
    } else {
        $stmt = $pdo->query("
            SELECT user_id, username, first_name, last_name, 
                   COUNT(*) as total_interactions,
                   MAX(interaction_date) as last_interaction
            FROM telegram_bot_interactions
            GROUP BY user_id, username, first_name, last_name
            ORDER BY last_interaction DESC
            LIMIT 50
        ");
    }
    $interactions = $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> Chat Telegram</h2>
</div>

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

<div class="row">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0">Usuarios</h5>
            </div>
            <div class="card-body p-0">
                <?php if (empty($interactions)): ?>
                    <p class="text-muted p-3">No hay interacciones</p>
                <?php else: ?>
                    <div class="list-group list-group-flush">
                        <?php if ($selectedUser): ?>
                            <a href="chat_telegram.php" class="list-group-item list-group-item-action">
                                <i class="bi bi-arrow-left"></i> Volver a lista
                            </a>
                        <?php else: ?>
                            <?php foreach ($interactions as $user): ?>
                            <a href="chat_telegram.php?user_id=<?= $user['user_id'] ?>" class="list-group-item list-group-item-action">
                                <div class="d-flex w-100 justify-content-between">
                                    <h6 class="mb-1"><?= htmlspecialchars($user['first_name'] ?? 'Usuario') ?></h6>
                                    <small><?= $user['total_interactions'] ?></small>
                                </div>
                                <small class="text-muted">@<?= htmlspecialchars($user['username'] ?? 'sin username') ?></small>
                            </a>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0">Historial de Mensajes</h5>
            </div>
            <div class="card-body" style="max-height: 500px; overflow-y: auto;">
                <?php if ($selectedUser && !empty($interactions)): ?>
                    <?php foreach ($interactions as $msg): ?>
                    <div class="mb-3 p-2 <?= $msg['interaction_type'] === 'in' ? 'bg-light' : 'bg-white' ?> rounded">
                        <small class="text-muted">
                            <?= date('d/m/Y H:i:s', strtotime($msg['interaction_date'])) ?>
                            - <?= $msg['interaction_type'] === 'in' ? '📥 Usuario' : '📤 Bot' ?>
                        </small>
                        <p class="mb-0 mt-1"><?= htmlspecialchars($msg['interaction_type'] ?? '') ?></p>
                    </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-muted text-center">Selecciona un usuario para ver el historial</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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