<?php
// csr_manager/announcements.php — Clean hierarchy announcement system
if (session_status() === PHP_SESSION_NONE) session_start();
if (empty($_SESSION['csr_id'])) { header('Location: ../login.php'); exit; }
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/announcement_system.php';
$db = (new Database())->getConnection();
$managerId = (int)$_SESSION['csr_id'];
$me = annGetCsr($db, $managerId);
if (!$me || ($me['role'] ?? '') !== 'csr_manager') { header('Location: dashboard.php'); exit; }
$teams = annGetTeams($db, null);
$users = annGetAllCsrUsers($db);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['create_announcement'])) {
            $target = $_POST['target_type'] ?? 'role_team_leader';
            $targetType = 'role'; $values = ['team_leader'];
            if ($target === 'all_team_leaders') { $targetType='role'; $values=['team_leader']; }
            elseif ($target === 'all_agents') { $targetType='role'; $values=['csr']; }
            elseif ($target === 'team') { $targetType='team'; $values=[(int)($_POST['team_id'] ?? 0)]; }
            elseif ($target === 'user') { $targetType='user'; $values=[(int)($_POST['user_id'] ?? 0)]; }
            else throw new Exception('Invalid target selected.');
            annCreate($db, 'csr_manager', $managerId, $_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'], 'csr_manager', $managerId); $_SESSION['flash_message']='Announcement status updated.'; }
        elseif (isset($_POST['delete_announcement'])) { annDelete($db, (int)$_POST['announcement_id'], 'csr_manager', $managerId); $_SESSION['flash_message']='Announcement deleted.'; }
        elseif (isset($_POST['mark_read'])) { annMarkRead($db, (int)$_POST['announcement_id'], $managerId); $_SESSION['flash_message']='Announcement marked as read.'; }
    } catch(Throwable $e){ $_SESSION['flash_error']=$e->getMessage(); }
    header('Location: announcements.php'); exit;
}
$sent = annListSent($db, 'csr_manager', $managerId, 180);
$inbox = annGetInboxForUser($db, $managerId, 100);
$title='Announcements';
ob_start();
?>
<style>
.ann-wrap{display:grid;grid-template-columns:minmax(320px,450px) 1fr;gap:16px}.ann-card{background:var(--cm-card);border:1px solid var(--cm-border);border-radius:16px;padding:16px;margin-bottom:12px}.ann-title{font-family:'Space Grotesk';font-weight:900}.ann-meta{color:var(--cm-muted);font-size:.78rem;margin-top:4px}.ann-msg{white-space:pre-wrap;margin-top:10px}.ann-empty{text-align:center;padding:28px;border:1px dashed var(--cm-border);border-radius:14px;color:var(--cm-muted)}@media(max-width:920px){.ann-wrap{grid-template-columns:1fr}}
</style>
<div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-3"><div><h2 style="font-family:'Space Grotesk';font-weight:900;margin:0;">CSR Manager Announcements</h2><div class="text-muted">Send to all Team Leaders, all Agents, a specific Team, or a 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-wrap">
  <div>
    <div class="ann-card"><h5 class="ann-title mb-3">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_team_leaders">All CSR Team Leaders</option><option value="all_agents">All Agents</option><option value="team">Specific Team + Agents</option><option value="user">Specific Person</option></select>
      <div id="teamBox" style="display:none"><label class="form-label">Team</label><select class="form-select mb-3" name="team_id"><?php foreach($teams as $t): ?><option value="<?= (int)$t['id'] ?>"><?= ann_h($t['team_name']) ?></option><?php endforeach; ?></select></div>
      <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="6" 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></div>
    <div class="ann-card"><h5 class="ann-title mb-3">Announcements for Me</h5><?php if(!$inbox): ?><div class="ann-empty">No received announcements.</div><?php endif; ?><?php foreach($inbox as $a): ?><div class="border-bottom pb-3 mb-3" style="border-color:var(--cm-border)!important"><div class="ann-title"><?= ann_h($a['title']) ?></div><div class="ann-meta">From <?= ann_h($a['created_by_name'] ?: annSenderLabel($a['sender_type'])) ?> • <?= date('M j, Y g:i A', strtotime($a['created_at'])) ?></div><div class="ann-msg"><?= nl2br(ann_h($a['message'])) ?></div><?php if(empty($a['is_read'])): ?><form method="post" class="mt-2"><input type="hidden" name="announcement_id" value="<?= (int)$a['id'] ?>"><button class="btn btn-sm btn-primary" name="mark_read" value="1">Read</button></form><?php endif; ?></div><?php endforeach; ?></div>
  </div>
  <div><div class="ann-card"><h5 class="ann-title mb-3">Posted by Me</h5><?php if(!$sent): ?><div class="ann-empty">No announcements posted yet.</div><?php endif; ?><?php foreach($sent as $a): ?><div class="ann-card" style="background:oklch(0.11 0.032 261/.55)"><div class="d-flex justify-content-between align-items-start 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; ?></div></div>
</div>
<script>function annToggleTarget(){const v=document.getElementById('targetType').value;document.getElementById('teamBox').style.display=v==='team'?'block':'none';document.getElementById('userBox').style.display=v==='user'?'block':'none';}document.getElementById('targetType').addEventListener('change',annToggleTarget);annToggleTarget();</script>
<?php $content=ob_get_clean(); require_once __DIR__ . '/layout.php';
