<?php
// Filename: admin_announcements.php
require 'config.php';
requireLogin();

// 1. PERMISSION CHECK
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$allowed_roles = ['admin', 'principal', 'assistant'];

if (empty(array_intersect($user_roles, $allowed_roles))) {
    header("Location: dashboard.php"); 
    exit;
}

// --- CSRF TOKEN ---
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// --- AUTO-CREATE RECIPIENT TABLE ---
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS announcement_recipients (
        id INT AUTO_INCREMENT PRIMARY KEY,
        announcement_id INT NOT NULL,
        user_id INT NOT NULL,
        INDEX (announcement_id),
        INDEX (user_id)
    )");
} catch (Exception $e) { /* Table exists */ }

$msg = ''; $msg_type = '';

// 2. HANDLE ACTIONS
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // --- ACTION: CREATE ANNOUNCEMENT ---
    if ($_POST['action'] === 'create') {
        if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
            die("Security Alert: Invalid Request.");
        }

        $title = trim($_POST['title']);
        $message = trim($_POST['message']);
        $target_type = $_POST['target_type']; 
        $target_users = isset($_POST['target_user_ids']) ? $_POST['target_user_ids'] : []; 
        $start = !empty($_POST['start_date']) ? $_POST['start_date'] : date('Y-m-d H:i:s');
        $end = !empty($_POST['end_date']) ? $_POST['end_date'] : null; 

        if ($title && $message) {
            try {
                $pdo->beginTransaction();

                $stmt = $pdo->prepare("INSERT INTO announcements (title, message, type, target_user_id, created_by, start_date, end_date) VALUES (?, ?, ?, NULL, ?, ?, ?)");
                $stmt->execute([$title, $message, $target_type, $uid, $start, $end]);
                $announcement_id = $pdo->lastInsertId();

                $telegram_recipients = []; 
                $ins_notif = $pdo->prepare("INSERT INTO notifications (user_id, message, link, is_read, created_at) VALUES (?, ?, ?, 0, NOW())");

                if ($target_type === 'global') {
                    $all_staff = $pdo->query("SELECT id FROM users WHERE role != 'student'")->fetchAll(PDO::FETCH_COLUMN);
                    foreach ($all_staff as $staff_id) {
                        $ins_notif->execute([$staff_id, "Announcement: $title", "dashboard.php"]);
                    }
                } else {
                    if (!empty($target_users)) {
                        $rec_stmt = $pdo->prepare("INSERT INTO announcement_recipients (announcement_id, user_id) VALUES (?, ?)");
                        $placeholders = implode(',', array_fill(0, count($target_users), '?'));
                        $chat_stmt = $pdo->prepare("SELECT id, telegram_chat_id FROM users WHERE id IN ($placeholders)");
                        $chat_stmt->execute($target_users);
                        $user_chats = $chat_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

                        foreach ($target_users as $target_uid) {
                            $rec_stmt->execute([$announcement_id, $target_uid]);
                            $ins_notif->execute([$target_uid, "Alert: $title", "dashboard.php"]);
                            if (!empty($user_chats[$target_uid])) {
                                $telegram_recipients[] = $user_chats[$target_uid];
                            }
                        }
                    }
                }

                $pdo->commit();
                $msg = "Published and alerts sent!"; 
                $msg_type = "success";

                $plain_text_msg = strip_tags($message);
                $tg_msg = "?? <b>ANNOUNCEMENT: " . strtoupper($title) . "</b>\n\n" . $plain_text_msg;

                if ($target_type === 'global') {
                    // FIXED: Added 'announcement' type
                    if (function_exists('sendTelegram')) sendTelegram($tg_msg, null, 'announcement');
                    if (function_exists('broadcastPushNotification')) broadcastPushNotification($title, $plain_text_msg);
                } else {
                    if (function_exists('sendTelegram')) {
                        foreach ($telegram_recipients as $chat_id) { 
                            // FIXED: Added 'announcement' type
                            sendTelegram($tg_msg, $chat_id, 'announcement'); 
                        }
                    }
                    if (function_exists('sendPushNotification')) sendPushNotification($target_users, $title, $plain_text_msg);
                }

            } catch (Exception $e) {
                $pdo->rollBack();
                $msg = "Error: " . $e->getMessage(); 
                $msg_type = "danger";
            }
        }
    }

    // --- ACTION: DELETE ANNOUNCEMENT ---
    if ($_POST['action'] === 'delete') {
        $pdo->prepare("DELETE FROM announcement_recipients WHERE announcement_id = ?")->execute([$_POST['delete_id']]);
        $pdo->prepare("DELETE FROM announcements WHERE id = ?")->execute([$_POST['delete_id']]);
        $msg = "Deleted successfully."; 
        $msg_type = "warning";
    }
}

// 4. FETCH DATA
$users = $pdo->query("SELECT id, full_name, role FROM users WHERE role != 'student' ORDER BY full_name ASC")->fetchAll();
$history = $pdo->query("SELECT a.*, (SELECT COUNT(*) FROM announcement_recipients ar WHERE ar.announcement_id = a.id) as recipient_count FROM announcements a ORDER BY a.created_at DESC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Manage Announcements</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        .nav-pills .nav-link { border-radius: 50px; color: #64748b; font-weight: 700; background: #f1f5f9; margin-right: 5px; font-size: 0.85rem; width: 100%; }
        .nav-pills .nav-link.active { background: #8B5CF6; color: white; }
        .user-select-container { max-height: 200px; overflow-y: auto; border: 1px solid #e2e8f0; border-radius: 12px; background: #f8fafc; padding: 10px; }
        .user-option { display: flex; align-items: center; padding: 8px; border-bottom: 1px solid #f1f5f9; cursor: pointer; }
    </style>
</head>
<body>
    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Announcements</div>
            <div style="width: 24px;"></div>
        </div>
    </div>

    <div class="floating-card">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> text-center small mb-4"><?= $msg ?></div><?php endif; ?>

        <ul class="nav nav-pills mb-4" id="pills-tab" role="tablist">
            <li class="nav-item col-6 pe-1"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#pills-compose">Compose</button></li>
            <li class="nav-item col-6 ps-1"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#pills-history">History</button></li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane fade show active" id="pills-compose">
                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="action" value="create">
                    <div class="mb-3"><label class="form-label small fw-bold">Title</label><input type="text" name="title" class="form-control" required></div>
                    <div class="mb-3"><label class="form-label small fw-bold">Message</label><textarea name="message" class="form-control" rows="3" required></textarea></div>
                    <div class="mb-3"><label class="form-label small fw-bold">Audience</label>
                        <select name="target_type" id="target_type" class="form-select" onchange="toggleUsers()">
                            <option value="global">Everyone (Broadcast)</option>
                            <option value="specific">Selected Users</option>
                        </select>
                    </div>
                    <div id="userSelection" class="mb-3 d-none">
                        <div class="user-select-container">
                            <?php foreach($users as $u): ?>
                            <label class="user-option"><input type="checkbox" name="target_user_ids[]" value="<?= $u['id'] ?>" class="me-2"><span class="small fw-bold"><?= htmlspecialchars($u['full_name']) ?></span></label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <button class="btn btn-primary w-100 rounded-pill fw-bold">Send Announcement</button>
                </form>
            </div>
            <div class="tab-pane fade" id="pills-history">
                <?php foreach($history as $h): ?>
                <div class="p-3 border-bottom d-flex justify-content-between align-items-center">
                    <div><div class="fw-bold small"><?= htmlspecialchars($h['title']) ?></div><div class="text-muted" style="font-size: 0.7rem;"><?= $h['type'] ?>  <?= $h['created_at'] ?></div></div>
                    <form method="POST">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="delete_id" value="<?= $h['id'] ?>">
                        <button class="btn btn-link text-danger p-0"><i class="bi bi-trash"></i></button>
                    </form>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <?php include 'menu.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleUsers() {
            const type = document.getElementById('target_type').value;
            document.getElementById('userSelection').classList.toggle('d-none', type === 'global');
        }
    </script>
</body>
</html>