<?php
/**
 * Admin — Chat History Viewer
 * Path: admin/chat-history.php
 */
require_once 'layout-header.php';

$msg_success = '';
$search      = trim($_GET['search'] ?? '');
$page        = max(1, intval($_GET['page'] ?? 1));
$per_page    = 20;
$offset      = ($page - 1) * $per_page;

if (!$conn) {
    echo "<main class='flex-1 p-6'><div class='p-4 bg-red-950/40 border border-red-800 text-red-200 text-sm rounded-xl'>ডাটাবেজ কানেক্টেড নেই!</div></main>";
    require_once 'layout-footer.php';
    exit;
}

$prefix = DB_PREFIX;

// Delete single
if (isset($_GET['delete']) && intval($_GET['delete']) > 0) {
    $del_id = intval($_GET['delete']);
    $stmt = $conn->prepare("DELETE FROM `{$prefix}chat_history` WHERE id = ?");
    $stmt->bind_param("i", $del_id);
    $stmt->execute() ? $msg_success = 'রেকর্ড মুছে ফেলা হয়েছে।' : null;
    $stmt->close();
}

// Clear all
if (isset($_GET['clear_all']) && $_GET['clear_all'] === 'confirm') {
    $conn->query("TRUNCATE TABLE `{$prefix}chat_history`");
    $msg_success = 'সমস্ত চ্যাট হিস্টরি মুছে ফেলা হয়েছে।';
}

// Fetch with search
$where  = '';
$params = [];
$types  = '';

if ($search) {
    $where = " WHERE user_message LIKE ? OR bot_response LIKE ? OR user_ip LIKE ?";
    $like  = '%' . $search . '%';
    $params = [$like, $like, $like];
    $types  = 'sss';
}

$count_sql = "SELECT COUNT(*) as cnt FROM `{$prefix}chat_history`" . $where;
if ($search) {
    $cs = $conn->prepare($count_sql);
    $cs->bind_param($types, ...$params);
    $cs->execute();
    $total = (int)$cs->get_result()->fetch_assoc()['cnt'];
    $cs->close();
} else {
    $total = (int)$conn->query($count_sql)->fetch_assoc()['cnt'];
}

$sql = "SELECT * FROM `{$prefix}chat_history`" . $where . " ORDER BY created_at DESC LIMIT {$per_page} OFFSET {$offset}";
if ($search) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}

$total_pages = max(1, ceil($total / $per_page));
$chats = [];
if ($result) {
    while ($row = $result->fetch_assoc()) $chats[] = $row;
}
?>

<main class="flex-1 p-6 md:p-8 space-y-6">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-slate-800/80 pb-5">
        <div>
            <h1 class="text-2xl font-black text-white uppercase tracking-wider">Chat History</h1>
            <p class="text-xs text-slate-400 mt-1">ইউজার প্রশ্ন ও বট উত্তরের সম্পূর্ণ রেকর্ড — মোট <?php echo $total; ?>টি</p>
        </div>
        <?php if ($total > 0): ?>
        <a href="?clear_all=confirm" onclick="return confirm('সমস্ত চ্যাট হিস্টরি মুছে ফেলবেন? এটি ফিরিয়ে আনা যাবে না।');"
            class="bg-red-950/50 hover:bg-red-900 border border-red-800 text-red-300 px-4 py-2 rounded-xl text-xs font-bold uppercase flex items-center">
            <i class="fa-solid fa-trash-can mr-2"></i> Clear All
        </a>
        <?php endif; ?>
    </div>

    <?php if ($msg_success): ?>
    <div class="p-4 bg-emerald-950/40 border border-emerald-800 text-emerald-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-circle-check mr-3"></i> <?php echo $msg_success; ?>
    </div>
    <?php endif; ?>

    <!-- Search -->
    <form method="get" action="" class="flex gap-3">
        <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>"
            placeholder="প্রশ্ন, উত্তর বা IP দিয়ে খুঁজুন..."
            class="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100 focus:ring-2 focus:ring-sky-500">
        <button type="submit" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-bold px-6 py-3 rounded-xl text-xs uppercase">
            <i class="fa-solid fa-magnifying-glass mr-1"></i> Search
        </button>
        <?php if ($search): ?>
        <a href="chat-history.php" class="bg-slate-800 text-slate-400 px-4 py-3 rounded-xl text-xs flex items-center">Clear</a>
        <?php endif; ?>
    </form>

    <!-- Chat Records -->
    <?php if (empty($chats)): ?>
    <div class="text-center py-16 text-slate-500">
        <i class="fa-solid fa-comments text-3xl mb-3 block opacity-30"></i>
        <p class="text-sm">কোনো চ্যাট রেকর্ড নেই।</p>
    </div>
    <?php else: ?>
    <div class="space-y-4">
        <?php foreach ($chats as $chat): ?>
        <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-5 hover:border-sky-500/20 transition-all">
            <div class="flex items-center justify-between mb-4 pb-3 border-b border-slate-800/80">
                <div class="flex items-center gap-3">
                    <div class="w-8 h-8 rounded-full bg-sky-500/10 flex items-center justify-center">
                        <i class="fa-solid fa-user text-sky-400 text-xs"></i>
                    </div>
                    <div>
                        <span class="text-xs font-mono text-slate-400"><?php echo htmlspecialchars($chat['user_ip'] ?? 'Unknown IP'); ?></span>
                        <span class="text-[10px] text-slate-600 ml-2"><?php echo date('d M Y, h:i A', strtotime($chat['created_at'])); ?></span>
                    </div>
                </div>
                <a href="?delete=<?php echo $chat['id']; ?><?php echo $search ? '&search='.urlencode($search) : ''; ?>&page=<?php echo $page; ?>"
                    onclick="return confirm('এই রেকর্ড মুছে ফেলবেন?');"
                    class="text-red-400 hover:text-red-300 text-xs p-2 hover:bg-red-950/30 rounded-lg transition-all">
                    <i class="fa-solid fa-trash"></i>
                </a>
            </div>

            <!-- User Question -->
            <div class="flex gap-3 mb-3">
                <span class="text-[10px] font-bold uppercase text-sky-400 w-12 flex-shrink-0 pt-1">User</span>
                <p class="text-sm text-white bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 flex-1 leading-relaxed">
                    <?php echo htmlspecialchars($chat['user_message']); ?>
                </p>
            </div>

            <!-- Bot Response -->
            <div class="flex gap-3">
                <span class="text-[10px] font-bold uppercase text-emerald-400 w-12 flex-shrink-0 pt-1">Bot</span>
                <div class="text-sm text-slate-300 bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 flex-1 leading-relaxed max-h-40 overflow-y-auto">
                    <?php echo strip_tags($chat['bot_response'], '<a><img><span><div>'); ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <div class="flex justify-center gap-2 pt-4">
        <?php for ($p = 1; $p <= $total_pages; $p++): ?>
        <a href="?page=<?php echo $p; ?><?php echo $search ? '&search='.urlencode($search) : ''; ?>"
            class="px-3 py-1.5 rounded-lg text-xs font-bold <?php echo $p === $page ? 'bg-sky-500 text-slate-950' : 'bg-slate-800 text-slate-400 hover:text-white'; ?>">
            <?php echo $p; ?>
        </a>
        <?php endfor; ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>

</main>

<?php require_once 'layout-footer.php'; ?>
