<?php
session_start();
if (!isset($_SESSION['unohs'])) {
    header("Location: index.php");
    exit();
}
include "conn.php";

$conn->query("
    CREATE TABLE IF NOT EXISTS agent_messages_to_admin (
        id INT AUTO_INCREMENT PRIMARY KEY,
        agent_userid INT NOT NULL,
        message TEXT NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
");

$messages = [];
$result = $conn->query("
    SELECT am.id, am.message, am.created_at, a.mobile, a.id AS agent_id
    FROM agent_messages_to_admin am
    LEFT JOIN tb_agent a ON a.userid = am.agent_userid
    ORDER BY am.id DESC LIMIT 30
");
if ($result) {
    while ($row = $result->fetch_assoc()) { $messages[] = $row; }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Messages from Agents - RAJ365 Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="admin-gold-theme.css">
    <style>
        body { background: #0A0A0A; padding: 20px; }
        .msg-card { background: #171512; border: 1px solid rgba(212,175,55,.2); border-radius: 12px; padding: 14px 16px; margin-bottom: 10px; }
    </style>
</head>
<body>
<div class="container" style="max-width:600px;">
    <h3 style="color:#D4AF37;">📥 Agent-দের বার্তা</h3>
    <p style="color:#8A8270; font-size:12.5px;">Agent-রা তাদের Panel থেকে যা পাঠিয়েছে</p>

    <?php if (empty($messages)): ?>
        <p style="color:#8A8270;">এখনো কোনো বার্তা আসেনি।</p>
    <?php else: ?>
        <?php foreach ($messages as $m): ?>
            <div class="msg-card">
                <div style="color:#D4AF37; font-weight:700; font-size:12.5px; margin-bottom:6px;">
                    Agent #<?= htmlspecialchars($m['agent_id'] ?? '?') ?> — <?= htmlspecialchars($m['mobile'] ?? 'N/A') ?>
                </div>
                <div style="color:#F5EFDC; font-size:13.5px;"><?= nl2br(htmlspecialchars($m['message'])) ?></div>
                <div style="color:#8A8270; font-size:11px; margin-top:6px;"><?= htmlspecialchars($m['created_at']) ?></div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <a href="dashboard.php" style="color:#D4AF37;">← Dashboard-এ ফিরে যান</a>
</div>
</body>
</html>
