<?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
    )
");
// ✅ admin_messages table এই page আগে কখনো visit না হলেও তৈরি না
// থাকতে পারে — তাই Reply কাজ করার আগে এখানেও নিশ্চিত করা হচ্ছে
$conn->query("
    CREATE TABLE IF NOT EXISTS admin_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        message TEXT NOT NULL,
        recipient_agent_id INT DEFAULT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
");
try {
    $conn->query("ALTER TABLE admin_messages ADD COLUMN recipient_agent_id INT DEFAULT NULL");
} catch (mysqli_sql_exception $e) {
    // Column আগে থেকেই থাকলে এই Exception স্বাভাবিক — চুপচাপ উপেক্ষা করা হচ্ছে
}

// ✅ ২৪ ঘণ্টার পুরনো বার্তা স্বয়ংক্রিয়ভাবে মুছে ফেলা (দুটো Table-ই)
$conn->query("DELETE FROM agent_messages_to_admin WHERE created_at < (NOW() - INTERVAL 24 HOUR)");
$conn->query("DELETE FROM admin_messages WHERE created_at < (NOW() - INTERVAL 24 HOUR)");

$feedback = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_msg' && isset($_POST['msg_id'])) {
    $delId = intval($_POST['msg_id']);
    $conn->query("DELETE FROM agent_messages_to_admin WHERE id = $delId");
    $feedback = '✅ বার্তা মুছে ফেলা হয়েছে।';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['reply_text']) && !empty($_POST['reply_to_userid'])) {
    $replyUserId = intval($_POST['reply_to_userid']);
    $replyText = $_POST['reply_text'];
    $stmt = $conn->prepare("INSERT INTO admin_messages (message, recipient_agent_id) VALUES (?, ?)");
    if ($stmt) {
        $stmt->bind_param("si", $replyText, $replyUserId);
        if ($stmt->execute()) {
            $feedback = '✅ Reply পাঠানো হয়েছে — সেই Agent তার Panel-এ এটা দেখতে পাবে।';
        }
        $stmt->close();
    } else {
        $feedback = '❌ Database সমস্যা — আবার চেষ্টা করো।';
    }
}

$messages = [];
$result = $conn->query("
    SELECT am.id, am.message, am.created_at, am.agent_userid, 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 ($feedback): ?>
        <div class="alert" style="background:#171512; border:1px solid #D4AF37; color:#F5EFDC;"><?= htmlspecialchars($feedback) ?></div>
    <?php endif; ?>

    <?php if (empty($messages)): ?>
        <p style="color:#8A8270;">এখনো কোনো বার্তা আসেনি।</p>
    <?php else: ?>
        <?php foreach ($messages as $m): ?>
            <div class="msg-card">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
                    <div style="color:#D4AF37; font-weight:700; font-size:12.5px;">
                        Agent #<?= htmlspecialchars($m['agent_id'] ?? '?') ?> — <?= htmlspecialchars($m['mobile'] ?? 'N/A') ?>
                    </div>
                    <form method="POST" onsubmit="return confirm('এই বার্তা মুছে ফেলতে চান?');">
                        <input type="hidden" name="action" value="delete_msg">
                        <input type="hidden" name="msg_id" value="<?= $m['id'] ?>">
                        <button type="submit" style="background:none; border:none; color:#E8544A; font-size:11px;">🗑 Delete</button>
                    </form>
                </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>

                <form method="POST" style="display:flex; gap:6px; margin-top:10px;">
                    <input type="hidden" name="reply_to_userid" value="<?= htmlspecialchars($m['agent_userid']) ?>">
                    <input type="text" name="reply_text" placeholder="Reply লেখো..." required
                           style="flex:1; padding:6px 10px; border-radius:8px; border:1px solid #3A3226; background:#0A0A0A; color:#F5EFDC; font-size:12.5px;">
                    <button type="submit" style="background:#D4AF37; color:#1A1400; font-weight:700; border:none; border-radius:8px; padding:6px 14px; font-size:12.5px;">Reply</button>
                </form>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

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