<?php
require_once 'auth.php';
ensureAdminAuth();
require_once '../config/database.php';
require_once '../includes/announcement_system.php';
$db = (new Database())->getConnection();
ensureUnifiedAnnouncementSystem($db);
$adminId = (int)($_SESSION['admin_id'] ?? 0);
$users = annGetAllCsrUsers($db);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['create_announcement'])) {
            $target = $_POST['target_type'] ?? 'all';
            $targetType = 'all'; $values = [];
            if ($target === 'all') { $targetType='all'; }
            elseif ($target === 'csr_managers') { $targetType='role'; $values=['csr_manager']; }
            elseif ($target === 'team_leaders') { $targetType='role'; $values=['team_leader']; }
            elseif ($target === 'agents') { $targetType='role'; $values=['csr']; }
            elseif ($target === 'user') { $targetType='user'; $values=[(int)($_POST['user_id'] ?? 0)]; }
            else throw new Exception('Invalid target selected.');
            annCreate($db, 'admin', $adminId, $_POST['title'] ?? '', $_POST['message'] ?? '', $_POST['priority'] ?? 'info', $targetType, $values);
            $_SESSION['flash_message']='Announcement posted successfully.';
        } elseif (isset($_POST['toggle_announcement'])) { annToggle($db, (int)$_POST['announcement_id'], 'admin', $adminId); $_SESSION['flash_message']='Announcement status updated.'; }
        elseif (isset($_POST['delete_announcement'])) { annDelete($db, (int)$_POST['announcement_id'], 'admin', $adminId); $_SESSION['flash_message']='Announcement deleted.'; }
    } catch(Throwable $e){ $_SESSION['flash_error']=$e->getMessage(); }
    header('Location: announcements.php'); exit;
}
$sent = annListSent($db, 'admin', $adminId, 200);
?>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Announcements - Admin</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700;800;900&display=swap" rel="stylesheet"><link rel="stylesheet" href="../assets/ushs-global-theme.css"><link rel="stylesheet" href="../assets/admin-sidebar.css"><style>
:root{--bg1:#080240;--bg2:#093349;--card1:#17295e;--card2:#102448;--cyan:#17bdd4;--muted:#aebbd4;--soft:#d7e7ff}body{background:linear-gradient(135deg,var(--bg1),var(--bg2)) fixed!important;color:#fff!important;font-family:Montserrat,sans-serif!important}.main-content{padding:24px}.panel{background:linear-gradient(135deg,var(--card1),var(--card2));border:1px solid rgba(56,189,248,.24);border-radius:18px;padding:20px;margin-bottom:18px}.form-control,.form-select,textarea{background:rgba(8,20,48,.62)!important;border:1px solid rgba(255,255,255,.14)!important;color:#fff!important;border-radius:12px!important}.form-select option{background:#102448;color:#fff}.text-muted{color:var(--muted)!important}.ann-card{background:rgba(8,20,48,.38);border:1px solid rgba(96,165,250,.18);border-radius:16px;padding:16px;margin-bottom:12px}.ann-title{font-weight:900}.ann-meta{color:var(--muted);font-size:.8rem}.ann-msg{white-space:pre-wrap;margin-top:10px}.ann-grid{display:grid;grid-template-columns:minmax(320px,460px) 1fr;gap:16px}@media(max-width:900px){.ann-grid{grid-template-columns:1fr}.main-content{padding:14px}}
</style></head><body><?php require_once __DIR__ . '/admin_sidebar.php'; render_admin_sidebar('announcements.php'); ?>
<main class="main-content"><div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-3"><div><h2 style="font-weight:900;margin:0;">Admin Announcements</h2><div class="text-muted">Send to all, CSR Managers, Team Leaders, Agents, or one specific person.</div></div></div>
<?php if (!empty($_SESSION['flash_message'])): ?><div class="alert alert-success"><?= ann_h($_SESSION['flash_message']); unset($_SESSION['flash_message']); ?></div><?php endif; ?>
<?php if (!empty($_SESSION['flash_error'])): ?><div class="alert alert-danger"><?= ann_h($_SESSION['flash_error']); unset($_SESSION['flash_error']); ?></div><?php endif; ?>
<div class="ann-grid"><section class="panel"><h5 class="mb-3" style="font-weight:900">New Announcement</h5><form method="post">
<label class="form-label">Send to</label><select class="form-select mb-3" name="target_type" id="targetType"><option value="all">All CSR users</option><option value="csr_managers">All CSR Managers</option><option value="team_leaders">All Team Leaders</option><option value="agents">All Agents</option><option value="user">Specific Person</option></select>
<div id="userBox" style="display:none"><label class="form-label">Person</label><select class="form-select mb-3" name="user_id"><?php foreach($users as $u): ?><option value="<?= (int)$u['id'] ?>"><?= ann_h(annFullName($u)) ?> — <?= ann_h(annRoleLabel($u['role'])) ?></option><?php endforeach; ?></select></div>
<label class="form-label">Title</label><input class="form-control mb-3" name="title" required maxlength="180" placeholder="Announcement title"><label class="form-label">Message</label><textarea class="form-control mb-3" name="message" required rows="7" placeholder="Write announcement..."></textarea><label class="form-label">Priority</label><select class="form-select mb-3" name="priority"><option value="info">Info</option><option value="success">Success</option><option value="warning">Warning</option><option value="danger">Danger</option></select><button class="btn btn-primary w-100" name="create_announcement" value="1"><i class="fas fa-paper-plane me-1"></i>Post Announcement</button></form></section>
<section class="panel"><h5 class="mb-3" style="font-weight:900">Posted by Admin</h5><?php if(!$sent): ?><div class="text-muted text-center py-4">No announcements posted yet.</div><?php endif; ?><?php foreach($sent as $a): ?><div class="ann-card"><div class="d-flex justify-content-between gap-2 flex-wrap"><div><div class="ann-title"><?= ann_h($a['title']) ?></div><div class="ann-meta"><?= ann_h(annTargetLabel($db,$a)) ?> • <?= date('M j, Y g:i A', strtotime($a['created_at'])) ?></div></div><span class="badge bg-<?= $a['is_active']?'success':'secondary' ?>"><?= $a['is_active']?'Active':'Inactive' ?></span></div><div class="ann-msg"><?= nl2br(ann_h($a['message'])) ?></div><div class="d-flex gap-2 mt-3"><form method="post"><input type="hidden" name="announcement_id" value="<?= (int)$a['id'] ?>"><button class="btn btn-sm btn-warning" name="toggle_announcement" value="1"><?= $a['is_active']?'Disable':'Enable' ?></button></form><form method="post" onsubmit="return confirm('Delete this announcement?')"><input type="hidden" name="announcement_id" value="<?= (int)$a['id'] ?>"><button class="btn btn-sm btn-danger" name="delete_announcement" value="1">Delete</button></form></div></div><?php endforeach; ?></section></div></main>
<script>function annToggleTarget(){document.getElementById('userBox').style.display=document.getElementById('targetType').value==='user'?'block':'none';}document.getElementById('targetType').addEventListener('change',annToggleTarget);annToggleTarget();</script><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script></body></html>
