<?php
// team_leader/announcements.php — Clean announcement creator + inbox
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();
$leaderId = (int)$_SESSION['csr_id'];
$me = annGetCsr($db, $leaderId);
if (!$me || ($me['role'] ?? '') !== 'team_leader') { header('Location: ../login.php'); exit; }
$teams = annGetTeams($db, $leaderId);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['create_announcement'])) {
            $teamIds = array_map(fn($t)=>(int)$t['id'], $teams);
            if (!$teamIds) throw new Exception('You do not have an active team yet.');
            $chosen = isset($_POST['team_id']) && (int)$_POST['team_id'] > 0 ? [(int)$_POST['team_id']] : $teamIds;
            foreach ($chosen as $tid) if (!in_array($tid, $teamIds, true)) throw new Exception('Invalid team selected.');
            annCreate($db, 'team_leader', $leaderId, $_POST['title'] ?? '', $_POST['message'] ?? '', $_POST['priority'] ?? 'info', 'team_agents', $chosen);
            $_SESSION['flash_message']='Announcement posted to your team agents.';
        } elseif (isset($_POST['toggle_announcement'])) {
            annToggle($db, (int)$_POST['announcement_id'], 'team_leader', $leaderId); $_SESSION['flash_message']='Announcement status updated.';
        } elseif (isset($_POST['delete_announcement'])) {
            annDelete($db, (int)$_POST['announcement_id'], 'team_leader', $leaderId); $_SESSION['flash_message']='Announcement deleted.';
        } elseif (isset($_POST['mark_read'])) {
            annMarkRead($db, (int)$_POST['announcement_id'], $leaderId); $_SESSION['flash_message']='Announcement marked as read.';
        }
    } catch(Throwable $e){ $_SESSION['flash_error']=$e->getMessage(); }
    header('Location: announcements.php'); exit;
}
$sent = annListSent($db, 'team_leader', $leaderId, 150);
$inbox = annGetInboxForUser($db, $leaderId, 100);
$title='Announcements';
ob_start();
?>
<style>
.ann-wrap{display:grid;grid-template-columns:minmax(320px,430px) 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;">Announcements</h2><div class="text-muted">Create announcements for agents inside your team. Admin/Manager announcements for you show below.</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 Team Announcement</h5><form method="post">
      <label class="form-label">Send to</label><select class="form-select mb-3" name="team_id"><option value="0">All my team agents</option><?php foreach($teams as $t): ?><option value="<?= (int)$t['id'] ?>"><?= ann_h($t['team_name']) ?> agents</option><?php endforeach; ?></select>
      <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>
<?php $content=ob_get_clean(); require_once __DIR__ . '/layout.php';
