<?php
session_start();
include 'config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

function h($str) { return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8'); }

/* ── Auth: superadmin only ─────────────────────────────────────────────── */
if (!isset($_SESSION['user_id'])) { header("Location: index.php"); exit(); }

$me_id   = $_SESSION['user_id'];
$me_name = $_SESSION['username'] ?? 'Super Admin';

/* Verify superadmin */
$check = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT role, is_superadmin FROM users WHERE id = '" . mysqli_real_escape_string($conn, $me_id) . "'"
));
if (!$check || ($check['role'] !== 'superadmin' && !$check['is_superadmin'])) {
    header("Location: dashboard_admin.php"); exit();
}

$success_msg = '';
$error_msg   = '';

/* ── Handle SEND ───────────────────────────────────────────────────────── */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    /* ── Send notification ── */
    if ($_POST['action'] === 'send') {
        $title       = trim($_POST['title']        ?? '');
        $message     = trim($_POST['message']       ?? '');
        $type        = $_POST['type']               ?? 'general';
        $target_type = $_POST['target_type']        ?? 'all';
        $target_val  = trim($_POST['target_value']  ?? '');
        $expires_at  = trim($_POST['expires_at']    ?? '');

        $valid_types   = ['general','announcement','alert','reminder','urgent'];
        $valid_targets = ['all','role','division','location','user'];

        if ($title === '' || $message === '') {
            $error_msg = 'Title and message are required.';
        } elseif (!in_array($type, $valid_types) || !in_array($target_type, $valid_targets)) {
            $error_msg = 'Invalid type or target.';
        } else {
            $t = mysqli_real_escape_string($conn, $title);
            $m = mysqli_real_escape_string($conn, $message);
            $tp = mysqli_real_escape_string($conn, $type);
            $tt = mysqli_real_escape_string($conn, $target_type);
            $tv = ($target_type === 'all') ? 'NULL' : "'" . mysqli_real_escape_string($conn, $target_val) . "'";
            $ea = ($expires_at !== '') ? "'" . mysqli_real_escape_string($conn, $expires_at) . "'" : 'NULL';
            $sn = mysqli_real_escape_string($conn, $me_name);
            $si = mysqli_real_escape_string($conn, $me_id);

            $sql = "INSERT INTO empnotification
                    (title, message, type, sent_by, sent_by_name, target_type, target_value, expires_at)
                    VALUES ('$t','$m','$tp','$si','$sn','$tt',$tv,$ea)";
            if (mysqli_query($conn, $sql)) {
                $success_msg = 'Notification sent successfully!';
            } else {
                $error_msg = 'DB error: ' . mysqli_error($conn);
            }
        }
    }

    /* ── Deactivate / delete ── */
    if ($_POST['action'] === 'deactivate' && !empty($_POST['notif_id'])) {
        $nid = intval($_POST['notif_id']);
        mysqli_query($conn, "UPDATE empnotification SET is_active = 0 WHERE id = $nid");
        $success_msg = 'Notification deactivated.';
    }
    if ($_POST['action'] === 'delete' && !empty($_POST['notif_id'])) {
        $nid = intval($_POST['notif_id']);
        mysqli_query($conn, "DELETE FROM empnotification WHERE id = $nid");
        $success_msg = 'Notification deleted.';
    }
    if ($_POST['action'] === 'reactivate' && !empty($_POST['notif_id'])) {
        $nid = intval($_POST['notif_id']);
        mysqli_query($conn, "UPDATE empnotification SET is_active = 1 WHERE id = $nid");
        $success_msg = 'Notification reactivated.';
    }
}

/* ── Fetch all notifications (newest first) ────────────────────────────── */
$notifs_result = mysqli_query($conn,
    "SELECT n.*,
            (SELECT COUNT(DISTINCT r.user_id) FROM empnotification_reads r WHERE r.notification_id = n.id) AS read_count
     FROM empnotification n
     ORDER BY n.created_at DESC
     LIMIT 200"
);
$all_notifs = [];
while ($row = mysqli_fetch_assoc($notifs_result)) $all_notifs[] = $row;

/* ── Fetch divisions for dropdown ──────────────────────────────────────── */
$divs_result = mysqli_query($conn, "SELECT DISTINCT division FROM users WHERE division IS NOT NULL AND division != '' AND status='active' ORDER BY division");
$divisions = [];
while ($r = mysqli_fetch_assoc($divs_result)) $divisions[] = $r['division'];

/* ── Fetch locations ───────────────────────────────────────────────────── */
$location_labels = [
    'karur'=>'Karur (HO)', 'trichy'=>'Trichy', 'madurai'=>'Madurai',
    'coimbatore'=>'Coimbatore', 'tirunelveli'=>'Tirunelveli', 'salem'=>'Salem',
];

/* ── Fetch employees for user-specific targeting ───────────────────────── */
$emp_result = mysqli_query($conn,
    "SELECT id, first_name, last_name, designation, division FROM users
     WHERE status = 'active' AND role != 'superadmin'
     ORDER BY first_name, last_name"
);
$emp_list = [];
while ($r = mysqli_fetch_assoc($emp_result)) $emp_list[] = $r;

/* ── Stats ─────────────────────────────────────────────────────────────── */
$stat_total  = count($all_notifs);
$stat_active = count(array_filter($all_notifs, fn($n) => $n['is_active']));
$stat_today  = count(array_filter($all_notifs, fn($n) => date('Y-m-d', strtotime($n['created_at'])) === date('Y-m-d')));
?>
<!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">
<title>MPC · Notifications — Super Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
  --ink: #0f172a; --ink-2: #334155; --muted: #94a3b8; --border: #e2e8f0;
  --surface: #ffffff; --bg: #f1f5f9; --sidebar-bg: #0f172a; --sidebar-w: 260px;
  --l1: #0f172a; --l2: #1d4ed8; --l3: #059669; --l4: #d97706; --l5: #dc2626;
  --l1-light: #e2e8f0; --l2-light: #dbeafe; --l3-light: #d1fae5;
  --l4-light: #fef3c7; --l5-light: #fee2e2;
  --radius: 12px;
  --shadow: 0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  --shadow-md: 0 4px 6px rgba(15,23,42,.07), 0 12px 32px rgba(15,23,42,.10);
  font-family: 'Sora', system-ui, sans-serif;
}
html, body { height: 100%; }
body { background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.6; -webkit-font-smoothing: antialiased; }
.layout { display: flex; min-height: 100vh; }

/* ── SIDEBAR ── */
.sidebar {
  width: var(--sidebar-w); background: var(--sidebar-bg);
  position: fixed; inset: 0 auto 0 0; z-index: 200;
  display: flex; flex-direction: column;
  overflow-y: auto; overflow-x: hidden;
  transition: transform .3s cubic-bezier(.4,0,.2,1); scrollbar-width: none;
}
.sidebar::-webkit-scrollbar { display: none; }
.sidebar.hidden { transform: translateX(-100%); }
.sidebar-brand { padding: 24px 20px 16px; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 8px; }
.brand-logo { width:36px; height:36px; background:linear-gradient(135deg,#3b82f6,#6366f1); border-radius:8px; display:flex; align-items:center; justify-content:center; font-size:16px; font-weight:700; color:#fff; flex-shrink:0; letter-spacing:-.5px; }
.brand-name { font-size:15px; font-weight:700; color:#fff; letter-spacing:.3px; }
.brand-sub  { font-size:10px; color:rgba(255,255,255,.4); letter-spacing:1.5px; text-transform:uppercase; margin-top:1px; }
.nav-section { padding: 0 12px 6px; }
.nav-label   { font-size:10px; font-weight:600; letter-spacing:1.2px; text-transform:uppercase; color:rgba(255,255,255,.25); padding:8px 8px 4px; }
.nav-item    { list-style: none; }
.nav-link, .nav-dropdown-toggle {
  display:flex; align-items:center; gap:10px; padding:8px 10px; border-radius:8px;
  color:rgba(255,255,255,.65); text-decoration:none; font-size:13px; font-weight:500;
  cursor:pointer; border:none; background:none; width:100%; text-align:left;
  transition:background .15s, color .15s;
}
.nav-link:hover, .nav-dropdown-toggle:hover { background:rgba(255,255,255,.07); color:#fff; }
.nav-link.active { background:rgba(59,130,246,.2); color:#60a5fa; }
.nav-link i, .nav-dropdown-toggle i { width:16px; text-align:center; font-size:13px; }
.nav-dropdown-toggle .arrow { margin-left:auto; transition:transform .2s; font-size:10px; }
.nav-dropdown-toggle.open .arrow { transform:rotate(180deg); }
.nav-submenu { list-style:none; overflow:hidden; max-height:0; transition:max-height .3s ease; padding-left:26px; }
.nav-submenu.open { max-height:600px; }
.nav-submenu .nav-link { font-size:12px; padding:6px 10px; color:rgba(255,255,255,.5); }
.nav-submenu .nav-link:hover { color:#fff; background:rgba(255,255,255,.05); }
.sidebar-footer { margin-top:auto; padding:12px; border-top:1px solid rgba(255,255,255,.06); }

/* ── CONTENT / TOPBAR ── */
.content { flex:1; margin-left:var(--sidebar-w); min-width:0; display:flex; flex-direction:column; transition:margin .3s; }
.content.expanded { margin-left:0; }
.topbar { height:60px; background:var(--surface); border-bottom:1px solid var(--border); display:flex; align-items:center; gap:12px; padding:0 24px; position:sticky; top:0; z-index:100; }
.hamburger-btn { width:36px; height:36px; border-radius:8px; border:1px solid var(--border); background:var(--surface); display:flex; align-items:center; justify-content:center; cursor:pointer; color:var(--ink-2); font-size:15px; flex-shrink:0; transition:background .15s; }
.hamburger-btn:hover { background:var(--bg); }
.topbar-breadcrumb { display:flex; align-items:center; gap:6px; font-size:13px; color:var(--muted); }
.topbar-breadcrumb .current { color:var(--ink); font-weight:600; }
.topbar-spacer { flex:1; }
.topbar-user { display:flex; align-items:center; gap:8px; font-size:13px; color:var(--ink-2); font-weight:500; }
.topbar-avatar { width:30px; height:30px; border-radius:50%; background:linear-gradient(135deg,#3b82f6,#6366f1); display:flex; align-items:center; justify-content:center; color:#fff; font-size:12px; font-weight:700; }

/* ── PAGE ── */
.page { padding:24px; flex:1; }
.page-header { margin-bottom:20px; }
.page-title  { font-size:22px; font-weight:700; color:var(--ink); letter-spacing:-.4px; }
.page-subtitle { font-size:13px; color:var(--muted); margin-top:2px; }

/* ── STAT GRID ── */
.stat-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:12px; margin-bottom:20px; }
.stat-card { background:var(--surface); border-radius:var(--radius); padding:16px; box-shadow:var(--shadow); position:relative; overflow:hidden; border:1px solid var(--border); }
.stat-card::before { content:''; position:absolute; top:0; left:0; right:0; height:3px; border-radius:3px 3px 0 0; }
.stat-card.blue::before  { background:#3b82f6; }
.stat-card.green::before { background:#059669; }
.stat-card.amber::before { background:#d97706; }
.stat-icon { width:32px; height:32px; border-radius:8px; display:flex; align-items:center; justify-content:center; font-size:14px; margin-bottom:10px; }
.stat-card.blue  .stat-icon { background:#dbeafe; color:#1d4ed8; }
.stat-card.green .stat-icon { background:#d1fae5; color:#059669; }
.stat-card.amber .stat-icon { background:#fef3c7; color:#d97706; }
.stat-num { font-size:26px; font-weight:700; letter-spacing:-.8px; color:var(--ink); line-height:1; margin-bottom:4px; font-family:'JetBrains Mono',monospace; }
.stat-lbl { font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:.8px; color:var(--muted); }

/* ── GRID ── */
.two-col { display:grid; grid-template-columns:1fr 1.6fr; gap:20px; align-items:start; }

/* ── CARD ── */
.card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:var(--shadow); overflow:hidden; }
.card-head { padding:16px 20px; border-bottom:1px solid var(--border); display:flex; align-items:center; gap:10px; }
.card-head-icon { width:32px; height:32px; border-radius:8px; display:flex; align-items:center; justify-content:center; font-size:14px; flex-shrink:0; }
.card-head-title { font-size:15px; font-weight:700; color:var(--ink); }
.card-body { padding:20px; }

/* ── FORM ── */
.form-group { margin-bottom:14px; }
.form-label { display:block; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.7px; color:var(--muted); margin-bottom:5px; }
.form-input, .form-select, .form-textarea {
  width:100%; border:1px solid var(--border); border-radius:8px;
  padding:9px 12px; font-size:13px; font-family:'Sora',sans-serif;
  color:var(--ink); background:var(--bg); outline:none;
  transition:border-color .15s, box-shadow .15s;
}
.form-input:focus, .form-select:focus, .form-textarea:focus {
  border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); background:var(--surface);
}
.form-textarea { resize:vertical; min-height:100px; }
.form-row { display:grid; grid-template-columns:1fr 1fr; gap:12px; }

/* Type radio pills */
.type-pills { display:flex; flex-wrap:wrap; gap:6px; }
.type-pill input[type=radio] { display:none; }
.type-pill label {
  padding:5px 12px; border-radius:20px; border:1.5px solid var(--border);
  font-size:12px; font-weight:600; cursor:pointer; display:flex; align-items:center; gap:5px;
  transition:all .15s; color:var(--ink-2); background:var(--bg);
}
.type-pill input:checked + label { border-color:currentColor; }
.type-pill.general   input:checked + label { background:#f0fdf4; color:#15803d; border-color:#86efac; }
.type-pill.announcement input:checked + label { background:#eff6ff; color:#1d4ed8; border-color:#93c5fd; }
.type-pill.alert     input:checked + label { background:#fff7ed; color:#c2410c; border-color:#fdba74; }
.type-pill.reminder  input:checked + label { background:#faf5ff; color:#7e22ce; border-color:#c4b5fd; }
.type-pill.urgent    input:checked + label { background:#fef2f2; color:#991b1b; border-color:#fca5a5; }

/* Target type segmented */
.seg-group { display:flex; background:var(--bg); border:1px solid var(--border); border-radius:8px; padding:3px; gap:2px; }
.seg-group input[type=radio] { display:none; }
.seg-group label { flex:1; text-align:center; padding:6px 8px; border-radius:6px; font-size:12px; font-weight:600; cursor:pointer; color:var(--muted); transition:all .15s; }
.seg-group input:checked + label { background:var(--surface); color:var(--ink); box-shadow:0 1px 3px rgba(15,23,42,.1); }

/* Submit btn */
.btn-primary {
  width:100%; padding:11px; border-radius:9px; border:none;
  background:var(--ink); color:#fff; font-size:14px; font-weight:700;
  font-family:'Sora',sans-serif; cursor:pointer; display:flex; align-items:center;
  justify-content:center; gap:8px; transition:background .15s, transform .1s;
}
.btn-primary:hover { background:#1e293b; }
.btn-primary:active { transform:scale(.98); }

/* ── ALERT FLASH ── */
.flash { padding:12px 16px; border-radius:9px; font-size:13px; font-weight:500; margin-bottom:16px; display:flex; align-items:center; gap:8px; }
.flash.success { background:#d1fae5; color:#065f46; border:1px solid #6ee7b7; }
.flash.error   { background:#fee2e2; color:#991b1b; border:1px solid #fca5a5; }

/* ── NOTIFICATION LIST ── */
.notif-list { display:flex; flex-direction:column; gap:0; }
.notif-item {
  padding:14px 16px; border-bottom:1px solid var(--border);
  display:grid; grid-template-columns:auto 1fr auto;
  gap:12px; align-items:start; transition:background .15s;
}
.notif-item:last-child { border-bottom:none; }
.notif-item:hover { background:#f8fafc; }
.notif-item.inactive { opacity:.5; }
.notif-type-dot {
  width:36px; height:36px; border-radius:9px; display:flex; align-items:center;
  justify-content:center; font-size:15px; flex-shrink:0; margin-top:1px;
}
.notif-type-dot.general      { background:#d1fae5; color:#059669; }
.notif-type-dot.announcement { background:#dbeafe; color:#1d4ed8; }
.notif-type-dot.alert        { background:#ffedd5; color:#c2410c; }
.notif-type-dot.reminder     { background:#ede9fe; color:#7c3aed; }
.notif-type-dot.urgent       { background:#fee2e2; color:#dc2626; }
.notif-title { font-size:13px; font-weight:700; color:var(--ink); margin-bottom:2px; }
.notif-msg   { font-size:12px; color:var(--ink-2); margin-bottom:5px; line-height:1.5; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; }
.notif-meta  { display:flex; flex-wrap:wrap; gap:6px; align-items:center; }
.notif-chip  { display:inline-flex; align-items:center; gap:3px; padding:2px 8px; border-radius:20px; font-size:10px; font-weight:700; background:var(--bg); color:var(--muted); border:1px solid var(--border); }
.notif-chip.read-count { background:#d1fae5; color:#065f46; border-color:#6ee7b7; }
.notif-chip.expired    { background:#fee2e2; color:#991b1b; border-color:#fca5a5; }
.notif-actions { display:flex; flex-direction:column; gap:4px; align-items:flex-end; }
.icon-btn {
  width:28px; height:28px; border-radius:6px; border:1px solid var(--border);
  background:var(--bg); cursor:pointer; display:flex; align-items:center;
  justify-content:center; font-size:11px; color:var(--muted); transition:all .15s;
}
.icon-btn:hover { background:var(--surface); color:var(--ink); }
.icon-btn.danger:hover { background:#fee2e2; color:#dc2626; border-color:#fca5a5; }
.icon-btn.success:hover { background:#d1fae5; color:#059669; border-color:#6ee7b7; }

/* ── SEARCH ── */
.list-toolbar { padding:12px 16px; border-bottom:1px solid var(--border); display:flex; gap:8px; align-items:center; }
.list-search  { flex:1; height:32px; border:1px solid var(--border); border-radius:7px; padding:0 10px 0 28px; font-size:12px; font-family:'Sora',sans-serif; background:var(--bg); outline:none; color:var(--ink); }
.list-search:focus { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); background:var(--surface); }
.list-search-wrap { position:relative; flex:1; }
.list-search-wrap i { position:absolute; left:9px; top:50%; transform:translateY(-50%); color:var(--muted); font-size:11px; pointer-events:none; }

/* ── EMPTY STATE ── */
.empty-state { text-align:center; padding:40px 20px; color:var(--muted); }
.empty-state i { font-size:32px; opacity:.3; display:block; margin-bottom:10px; }
.empty-state p { font-size:13px; }

/* ── STATUS TAG ── */
.status-tag { display:inline-flex; align-items:center; gap:3px; padding:2px 8px; border-radius:20px; font-size:10px; font-weight:700; }
.status-tag.active   { background:#d1fae5; color:#065f46; }
.status-tag.inactive { background:#f1f5f9; color:#94a3b8; }

/* ── MODAL ── */
.modal-overlay { position:fixed; inset:0; background:rgba(15,23,42,.5); z-index:500; display:none; align-items:center; justify-content:center; }
.modal-overlay.open { display:flex; }
.modal-box { background:var(--surface); border-radius:16px; padding:24px; max-width:460px; width:90%; box-shadow:var(--shadow-md); }
.modal-title { font-size:16px; font-weight:700; margin-bottom:8px; }
.modal-text  { font-size:13px; color:var(--ink-2); margin-bottom:20px; }
.modal-actions { display:flex; gap:8px; justify-content:flex-end; }
.btn-cancel { padding:8px 16px; border-radius:8px; border:1px solid var(--border); background:var(--bg); font-size:13px; font-weight:600; font-family:'Sora',sans-serif; cursor:pointer; color:var(--ink-2); }
.btn-confirm-del { padding:8px 16px; border-radius:8px; border:none; background:#dc2626; color:#fff; font-size:13px; font-weight:600; font-family:'Sora',sans-serif; cursor:pointer; }

@media(max-width:1024px) { .two-col { grid-template-columns:1fr; } }
@media(max-width:768px)  { .sidebar { transform:translateX(-100%); } .sidebar:not(.hidden) { transform:none; } .content { margin-left:0; } .stat-grid { grid-template-columns:1fr 1fr; } .page { padding:16px; } .form-row { grid-template-columns:1fr; } }
</style>
</head>
<body>
<div class="layout">

<!-- ── SIDEBAR ──────────────────────────────────────────────────────────── -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC</div>
      <div class="brand-sub">Admin Portal</div>
    </div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item"><a href="dashboard_admin.php" class="nav-link"><i class="fas fa-sitemap"></i> Organisation Chart</a></li>
      <li class="nav-item"><a href="superadmin_notifications.php" class="nav-link active"><i class="fas fa-bell"></i> Notifications</a></li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="manage_users.php"         class="nav-link"><i class="fas fa-users"></i> Employee Details</a></li>
          <li><a href="manage_documents.php"     class="nav-link"><i class="fas fa-file-alt"></i> Policies Rolled Out</a></li>
          <li><a href="digital.php"              class="nav-link"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="change_password.php"      class="nav-link"><i class="fas fa-key"></i> Change Password</a></li>
        </ul>
      </li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171;"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </div>
</nav>

<!-- ── CONTENT ───────────────────────────────────────────────────────────── -->
<div class="content" id="content">
  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>Admin</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Notifications</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($me_name, 0, 1)); ?></div>
      <?php echo h($me_name); ?>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title">🔔 Notification Centre</div>
      <div class="page-subtitle">Send and manage notifications to employees, managers, or specific teams</div>
    </div>

    <?php if ($success_msg): ?>
    <div class="flash success"><i class="fas fa-check-circle"></i><?php echo h($success_msg); ?></div>
    <?php endif; ?>
    <?php if ($error_msg): ?>
    <div class="flash error"><i class="fas fa-exclamation-circle"></i><?php echo h($error_msg); ?></div>
    <?php endif; ?>

    <!-- Stat Cards -->
    <div class="stat-grid">
      <div class="stat-card blue">
        <div class="stat-icon"><i class="fas fa-bell"></i></div>
        <div class="stat-num"><?php echo $stat_total; ?></div>
        <div class="stat-lbl">Total Sent</div>
      </div>
      <div class="stat-card green">
        <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
        <div class="stat-num"><?php echo $stat_active; ?></div>
        <div class="stat-lbl">Active</div>
      </div>
      <div class="stat-card amber">
        <div class="stat-icon"><i class="fas fa-calendar-day"></i></div>
        <div class="stat-num"><?php echo $stat_today; ?></div>
        <div class="stat-lbl">Sent Today</div>
      </div>
    </div>

    <div class="two-col">

      <!-- ── SEND FORM ── -->
      <div>
        <div class="card">
          <div class="card-head">
            <div class="card-head-icon" style="background:#dbeafe;color:#1d4ed8"><i class="fas fa-paper-plane"></i></div>
            <div class="card-head-title">Send New Notification</div>
          </div>
          <div class="card-body">
            <form method="POST">
              <input type="hidden" name="action" value="send">

              <!-- Title -->
              <div class="form-group">
                <label class="form-label">Title *</label>
                <input type="text" name="title" class="form-input" placeholder="e.g. Leave Policy Update" required maxlength="255">
              </div>

              <!-- Message -->
              <div class="form-group">
                <label class="form-label">Message *</label>
                <textarea name="message" class="form-textarea" placeholder="Write your notification message here…" required></textarea>
              </div>

              <!-- Type -->
              <div class="form-group">
                <label class="form-label">Type</label>
                <div class="type-pills">
                  <div class="type-pill general">
                    <input type="radio" name="type" id="t-general" value="general" checked>
                    <label for="t-general"><i class="fas fa-info-circle"></i> General</label>
                  </div>
                  <div class="type-pill announcement">
                    <input type="radio" name="type" id="t-announce" value="announcement">
                    <label for="t-announce"><i class="fas fa-bullhorn"></i> Announcement</label>
                  </div>
                  <div class="type-pill alert">
                    <input type="radio" name="type" id="t-alert" value="alert">
                    <label for="t-alert"><i class="fas fa-triangle-exclamation"></i> Alert</label>
                  </div>
                  <div class="type-pill reminder">
                    <input type="radio" name="type" id="t-reminder" value="reminder">
                    <label for="t-reminder"><i class="fas fa-clock"></i> Reminder</label>
                  </div>
                  <div class="type-pill urgent">
                    <input type="radio" name="type" id="t-urgent" value="urgent">
                    <label for="t-urgent"><i class="fas fa-circle-exclamation"></i> Urgent</label>
                  </div>
                </div>
              </div>

              <!-- Target -->
              <div class="form-group">
                <label class="form-label">Send To</label>
                <div class="seg-group">
                  <input type="radio" name="target_type" id="tt-all"      value="all"      checked onchange="showTarget(this.value)">
                  <label for="tt-all">Everyone</label>
                  <input type="radio" name="target_type" id="tt-role"     value="role"     onchange="showTarget(this.value)">
                  <label for="tt-role">By Role</label>
                  <input type="radio" name="target_type" id="tt-division" value="division" onchange="showTarget(this.value)">
                  <label for="tt-division">By Division</label>
                  <input type="radio" name="target_type" id="tt-location" value="location" onchange="showTarget(this.value)">
                  <label for="tt-location">By Location</label>
                  <input type="radio" name="target_type" id="tt-user"     value="user"     onchange="showTarget(this.value)">
                  <label for="tt-user">Specific User</label>
                </div>
              </div>

              <!-- Target value (dynamic) -->
              <div class="form-group" id="target-value-wrap" style="display:none">
                <label class="form-label" id="target-value-label">Value</label>
                <!-- Role -->
                <select name="target_value" id="tv-role" class="form-select" style="display:none">
                  <option value="employee">Employee</option>
                  <option value="manager">Manager</option>
                  <option value="admin">Admin</option>
                </select>
                <!-- Division -->
                <select name="target_value" id="tv-division" class="form-select" style="display:none">
                  <?php foreach ($divisions as $d): ?>
                  <option value="<?php echo h($d); ?>"><?php echo h($d); ?></option>
                  <?php endforeach; ?>
                </select>
                <!-- Location -->
                <select name="target_value" id="tv-location" class="form-select" style="display:none">
                  <?php foreach ($location_labels as $k => $lbl): ?>
                  <option value="<?php echo h($k); ?>"><?php echo h($lbl); ?></option>
                  <?php endforeach; ?>
                </select>
                <!-- User -->
                <select name="target_value" id="tv-user" class="form-select" style="display:none">
                  <?php foreach ($emp_list as $e):
                    $fn = trim(($e['first_name']??'').' '.($e['last_name']??''));
                    $sub = trim(($e['designation']??'').' · '.($e['division']??''), ' ·');
                  ?>
                  <option value="<?php echo h($e['id']); ?>">
                    <?php echo h($fn); ?><?php if ($sub) echo ' — ' . h($sub); ?>
                  </option>
                  <?php endforeach; ?>
                </select>
              </div>

              <!-- Expiry -->
              <div class="form-group">
                <label class="form-label">Expires On <span style="color:var(--muted);font-weight:400;text-transform:none">(optional)</span></label>
                <input type="date" name="expires_at" class="form-input" min="<?php echo date('Y-m-d'); ?>">
              </div>

              <button type="submit" class="btn-primary">
                <i class="fas fa-paper-plane"></i> Send Notification
              </button>
            </form>
          </div>
        </div>
      </div>

      <!-- ── NOTIFICATION LIST ── -->
      <div>
        <div class="card">
          <div class="card-head">
            <div class="card-head-icon" style="background:#d1fae5;color:#059669"><i class="fas fa-list"></i></div>
            <div class="card-head-title">All Notifications</div>
          </div>
          <div class="list-toolbar">
            <div class="list-search-wrap">
              <i class="fas fa-search"></i>
              <input type="text" class="list-search" id="notifSearch" placeholder="Search notifications…" oninput="filterNotifs(this.value)">
            </div>
          </div>

          <?php if (empty($all_notifs)): ?>
          <div class="empty-state">
            <i class="fas fa-bell-slash"></i>
            <p>No notifications sent yet.</p>
          </div>
          <?php else: ?>
          <div class="notif-list" id="notifList">
            <?php
            $type_icons = [
              'general'      => 'fa-info-circle',
              'announcement' => 'fa-bullhorn',
              'alert'        => 'fa-triangle-exclamation',
              'reminder'     => 'fa-clock',
              'urgent'       => 'fa-circle-exclamation',
            ];
            $target_labels = [
              'all'      => 'Everyone',
              'role'     => 'Role',
              'division' => 'Division',
              'location' => 'Location',
              'user'     => 'User',
            ];
            foreach ($all_notifs as $n):
              $icon   = $type_icons[$n['type']] ?? 'fa-bell';
              $target = $target_labels[$n['target_type']] ?? 'Everyone';
              if ($n['target_value']) $target .= ': ' . $n['target_value'];
              $expired = $n['expires_at'] && $n['expires_at'] < date('Y-m-d');
              $dt = date('d M Y, g:i a', strtotime($n['created_at']));
            ?>
            <div class="notif-item<?php echo $n['is_active'] ? '' : ' inactive'; ?>"
                 data-search="<?php echo h(strtolower($n['title'] . ' ' . $n['message'] . ' ' . $n['type'])); ?>">
              <div class="notif-type-dot <?php echo h($n['type']); ?>">
                <i class="fas <?php echo $icon; ?>"></i>
              </div>
              <div>
                <div class="notif-title"><?php echo h($n['title']); ?></div>
                <div class="notif-msg"><?php echo h($n['message']); ?></div>
                <div class="notif-meta">
                  <span class="notif-chip"><i class="fas fa-users"></i><?php echo h($target); ?></span>
                  <span class="notif-chip"><i class="fas fa-calendar"></i><?php echo $dt; ?></span>
                  <span class="notif-chip read-count"><i class="fas fa-eye"></i><?php echo $n['read_count']; ?> read</span>
                  <?php if ($expired): ?>
                  <span class="notif-chip expired"><i class="fas fa-hourglass-end"></i>Expired</span>
                  <?php endif; ?>
                  <span class="status-tag <?php echo $n['is_active'] ? 'active' : 'inactive'; ?>">
                    <?php echo $n['is_active'] ? 'Active' : 'Inactive'; ?>
                  </span>
                </div>
              </div>
              <div class="notif-actions">
                <?php if ($n['is_active']): ?>
                <form method="POST" style="display:inline">
                  <input type="hidden" name="action" value="deactivate">
                  <input type="hidden" name="notif_id" value="<?php echo $n['id']; ?>">
                  <button type="submit" class="icon-btn" title="Deactivate"><i class="fas fa-pause"></i></button>
                </form>
                <?php else: ?>
                <form method="POST" style="display:inline">
                  <input type="hidden" name="action" value="reactivate">
                  <input type="hidden" name="notif_id" value="<?php echo $n['id']; ?>">
                  <button type="submit" class="icon-btn success" title="Reactivate"><i class="fas fa-play"></i></button>
                </form>
                <?php endif; ?>
                <button class="icon-btn danger" title="Delete"
                        onclick="confirmDelete(<?php echo $n['id']; ?>, '<?php echo h(addslashes($n['title'])); ?>')">
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </div>
            <?php endforeach; ?>
          </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div><!-- /page -->
</div><!-- /content -->
</div><!-- /layout -->

<!-- Delete Confirm Modal -->
<div class="modal-overlay" id="deleteModal">
  <div class="modal-box">
    <div class="modal-title">🗑 Delete Notification?</div>
    <div class="modal-text" id="deleteModalText">Are you sure you want to permanently delete this notification? Read receipts will also be removed.</div>
    <div class="modal-actions">
      <button class="btn-cancel" onclick="closeDeleteModal()">Cancel</button>
      <form method="POST" id="deleteForm" style="display:inline">
        <input type="hidden" name="action" value="delete">
        <input type="hidden" name="notif_id" id="deleteNotifId" value="">
        <button type="submit" class="btn-confirm-del"><i class="fas fa-trash"></i> Delete</button>
      </form>
    </div>
  </div>
</div>

<script>
function toggleSidebar() { document.getElementById('sidebar').classList.toggle('hidden'); document.getElementById('content').classList.toggle('expanded'); }
function toggleMenu(btn) { btn.nextElementSibling.classList.toggle('open'); btn.classList.toggle('open'); }

/* Target type dynamic fields */
function showTarget(val) {
  const wrap = document.getElementById('target-value-wrap');
  const ids = ['tv-role','tv-division','tv-location','tv-user'];
  const map = { role:'tv-role', division:'tv-division', location:'tv-location', user:'tv-user' };
  const labels = { role:'Role', division:'Division', location:'Location', user:'Employee' };

  if (val === 'all') { wrap.style.display = 'none'; return; }
  wrap.style.display = 'block';
  document.getElementById('target-value-label').textContent = labels[val] || 'Value';
  ids.forEach(id => {
    const el = document.getElementById(id);
    const active = (id === map[val]);
    el.style.display = active ? 'block' : 'none';
    el.disabled = !active;
    el.name = active ? 'target_value' : '';
  });
}
/* init */
showTarget('all');

/* Search */
function filterNotifs(q) {
  const term = q.toLowerCase();
  document.querySelectorAll('#notifList .notif-item').forEach(item => {
    item.style.display = item.dataset.search.includes(term) ? '' : 'none';
  });
}

/* Delete modal */
function confirmDelete(id, title) {
  document.getElementById('deleteNotifId').value = id;
  document.getElementById('deleteModalText').textContent = 'Delete "' + title + '"? Read receipts will also be removed.';
  document.getElementById('deleteModal').classList.add('open');
}
function closeDeleteModal() { document.getElementById('deleteModal').classList.remove('open'); }
document.getElementById('deleteModal').addEventListener('click', function(e) {
  if (e.target === this) closeDeleteModal();
});
</script>
</body>
</html>