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

$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
    )
");
// ✅ পুরনো কোনো version-এ table আগে থেকে তৈরি থাকলেও (recipient_agent_id ছাড়া),
// এখানে নিরাপদে সেই Column যোগ করে দেওয়া হচ্ছে — Error হলে চুপচাপ উপেক্ষা করা হয়
try {
try {
    $conn->query("ALTER TABLE admin_messages ADD COLUMN recipient_agent_id INT DEFAULT NULL");
} catch (mysqli_sql_exception $e) {
    // Column আগে থেকেই থাকলে এই Exception স্বাভাবিক — চুপচাপ উপেক্ষা করা হচ্ছে
}
} catch (Exception $e) {
    // Column আগে থেকেই থাকলে এটা normal — কিছু করার দরকার নেই
}

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

$feedback = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add' && !empty($_POST['message_text'])) {
        $text = $_POST['message_text'];
        $sendToAll = isset($_POST['send_all']);
        $selectedAgents = $_POST['agent_ids'] ?? [];

        if ($sendToAll) {
            $stmt = $conn->prepare("INSERT INTO admin_messages (message, recipient_agent_id) VALUES (?, NULL)");
            $stmt->bind_param("s", $text);
            $stmt->execute();
            $stmt->close();
            $feedback = '✅ বার্তা সব Agent-কে পাঠানো হয়েছে।';
        } elseif (!empty($selectedAgents)) {
            $stmt = $conn->prepare("INSERT INTO admin_messages (message, recipient_agent_id) VALUES (?, ?)");
            foreach ($selectedAgents as $agentId) {
                $agentIdInt = intval($agentId);
                $stmt->bind_param("si", $text, $agentIdInt);
                $stmt->execute();
            }
            $stmt->close();
            $feedback = '✅ বার্তা নির্বাচিত ' . count($selectedAgents) . ' জন Agent-কে পাঠানো হয়েছে।';
        } else {
            $feedback = '❌ কোনো Agent বেছে নাওনি, বা "সবাইকে" টিক দাওনি।';
        }
    } elseif ($_POST['action'] === 'delete' && isset($_POST['msg_id'])) {
        $id = intval($_POST['msg_id']);
        $conn->query("DELETE FROM admin_messages WHERE id = $id");
        $feedback = '✅ বার্তা মুছে ফেলা হয়েছে।';
    }
}

$agents = [];
$agentResult = $conn->query("SELECT a.userid, a.mobile FROM tb_agent a WHERE a.status = 1 ORDER BY a.userid");
if ($agentResult) {
    while ($row = $agentResult->fetch_assoc()) { $agents[] = $row; }
}

$messages = [];
$result = $conn->query("
    SELECT m.id, m.message, m.recipient_agent_id, m.created_at, a.mobile
    FROM admin_messages m
    LEFT JOIN tb_agent a ON a.userid = m.recipient_agent_id
    ORDER BY m.id DESC LIMIT 20
");
if ($result) {
    while ($row = $result->fetch_assoc()) { $messages[] = $row; }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Agent Messages - 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; }
        .form-box { background: #171512; border: 1px solid rgba(212,175,55,.3); border-radius: 14px; padding: 20px; margin-bottom: 20px; }
        textarea { background: #0A0A0A; border: 1px solid #3A3226; color: #F5EFDC; border-radius: 10px; padding: 12px 14px; width: 100%; min-height: 90px; }
        .msg-card { background: #171512; border: 1px solid rgba(212,175,55,.2); border-radius: 12px; padding: 12px 16px; margin-bottom: 10px; }
        .agent-check { background: #0A0A0A; border: 1px solid #3A3226; border-radius: 8px; padding: 8px 12px; margin-bottom: 6px; display: flex; align-items: center; gap: 8px; }
        .agent-check label { color: #F5EFDC; font-size: 13px; margin: 0; }
        .target-badge { font-size: 10.5px; padding: 2px 8px; border-radius: 999px; }
        .target-all { background: rgba(212,175,55,.15); color: #D4AF37; }
        .target-one { background: rgba(31,185,121,.15); color: #1FB979; }
    </style>
</head>
<body>
<div class="container" style="max-width:600px;">
    <h3 style="color:#D4AF37;">📝 Agent-দের জন্য বার্তা</h3>

    <?php if ($feedback): ?>
        <div class="alert" style="background:#171512; border:1px solid #D4AF37; color:#F5EFDC;"><?= htmlspecialchars($feedback) ?></div>
    <?php endif; ?>

    <form method="POST" class="form-box" id="msgForm">
        <input type="hidden" name="action" value="add">
        <textarea name="message_text" placeholder="যেমন: আগামীকাল Server Maintenance হবে..." required></textarea>

        <div style="margin:14px 0;">
            <label style="color:#D4AF37; display:flex; align-items:center; gap:8px; font-weight:700;">
                <input type="checkbox" name="send_all" id="sendAll" onchange="toggleAgentList()"> সবাইকে পাঠাও
            </label>
        </div>

        <div id="agentList">
            <div style="color:#8A8270; font-size:12px; margin-bottom:8px;">অথবা নির্দিষ্ট Agent বেছে নাও:</div>
            <?php foreach ($agents as $a): ?>
                <div class="agent-check">
                    <input type="checkbox" name="agent_ids[]" value="<?= $a['userid'] ?>" id="agent<?= $a['userid'] ?>">
                    <label for="agent<?= $a['userid'] ?>">Agent (User ID: <?= $a['userid'] ?>) — <?= htmlspecialchars($a['mobile']) ?></label>
                </div>
            <?php endforeach; ?>
        </div>

        <button type="submit" class="btn" style="background:#D4AF37; color:#1A1400; font-weight:700; border-radius:10px; margin-top:12px; width:100%;">
            বার্তা পাঠাও
        </button>
    </form>

    <script>
    function toggleAgentList() {
        document.getElementById('agentList').style.display =
            document.getElementById('sendAll').checked ? 'none' : 'block';
    }
    </script>

    <div style="color:#D4AF37; font-weight:700; margin-bottom:10px;">আগের বার্তাসমূহ</div>
    <?php if (empty($messages)): ?>
        <p style="color:#8A8270;">এখনো কোনো বার্তা পাঠানো হয়নি।</p>
    <?php else: ?>
        <?php foreach ($messages as $m): ?>
            <div class="msg-card">
                <div style="margin-bottom:6px;">
                    <?php if ($m['recipient_agent_id'] === null): ?>
                        <span class="target-badge target-all">সবাইকে</span>
                    <?php else: ?>
                        <span class="target-badge target-one">শুধু <?= htmlspecialchars($m['mobile'] ?? ('Agent #' . $m['recipient_agent_id'])) ?></span>
                    <?php endif; ?>
                </div>
                <div style="color:#F5EFDC; font-size:13.5px;"><?= nl2br(htmlspecialchars($m['message'])) ?></div>
                <div style="color:#8A8270; font-size:11px; margin-top:6px; display:flex; justify-content:space-between; align-items:center;">
                    <span><?= htmlspecialchars($m['created_at']) ?></span>
                    <form method="POST" onsubmit="return confirm('মুছে ফেলতে চান?');">
                        <input type="hidden" name="action" value="delete">
                        <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>
        <?php endforeach; ?>
    <?php endif; ?>

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