<?php
session_start();
require_once '../config.php';
requireAdmin();
$page_title = 'Notifications';

if ($_POST && isset($_POST['action'])) {
    if ($_POST['action'] === 'mark_all_read') {
        $conn->query("UPDATE notifications SET is_read=1 WHERE is_read=0");
        setFlash('success', 'All notifications marked as read.');
    } elseif ($_POST['action'] === 'send_notification') {
        $user_type = clean($_POST['user_type']);
        $user_id   = (int)$_POST['user_id'];
        $title     = clean($_POST['title']);
        $message   = clean($_POST['message']);
        $channel   = clean($_POST['channel']);
        $stmt = $conn->prepare("INSERT INTO notifications (user_type,user_id,title,message,channel,created_at) VALUES (?,?,?,?,?,NOW())");
        $stmt->bind_param('sisss', $user_type, $user_id, $title, $message, $channel);
        $stmt->execute() ? setFlash('success','Notification sent.') : setFlash('error','Failed to send.');
    }
    header('Location: notifications.php'); exit;
}

$stats = [
    'total'  => $conn->query("SELECT COUNT(*) FROM notifications")->fetch_row()[0],
    'unread' => $conn->query("SELECT COUNT(*) FROM notifications WHERE is_read=0")->fetch_row()[0],
    'today'  => $conn->query("SELECT COUNT(*) FROM notifications WHERE DATE(created_at)=CURDATE()")->fetch_row()[0],
];

$filter          = clean($_GET['filter'] ?? 'all');
$user_type_filter= clean($_GET['user_type'] ?? '');
$where = [];
if ($filter === 'unread') $where[] = "n.is_read=0";
if ($filter === 'read')   $where[] = "n.is_read=1";
if ($user_type_filter)    $where[] = "n.user_type='$user_type_filter'";
$wq = $where ? 'WHERE '.implode(' AND ',$where) : '';

$notifications = $conn->query("
    SELECT n.*,
      CASE WHEN n.user_type='patient' THEN p.full_name WHEN n.user_type='doctor' THEN d.full_name ELSE 'Admin' END as user_name
    FROM notifications n
    LEFT JOIN patients p ON n.user_type='patient' AND n.user_id=p.id
    LEFT JOIN doctors d  ON n.user_type='doctor'  AND n.user_id=d.id
    $wq ORDER BY n.created_at DESC LIMIT 50
")->fetch_all(MYSQLI_ASSOC);

include 'header.php';
?>
<style>
  .stat-card { border-radius:14px; padding:18px; display:flex; align-items:center; gap:14px; box-shadow:0 4px 20px rgba(11,74,203,.12); transition:transform .2s; position:relative; overflow:hidden; }
  .stat-card:hover { transform:translateY(-3px); }
  .stat-card::after { content:''; position:absolute; right:-20px; top:-20px; width:80px; height:80px; border-radius:50%; background:rgba(255,255,255,.1); }
  .stat-icon { width:46px; height:46px; border-radius:14px; background:rgba(255,255,255,.22); display:grid; place-items:center; flex-shrink:0; font-size:20px; color:#fff; }
  .stat-num { font-size:24px; font-weight:800; color:#fff; line-height:1; }
  .stat-lbl { font-size:11px; color:rgba(255,255,255,.8); margin-top:3px; font-weight:500; }
  .notif-row { padding:14px 18px; border-bottom:1px solid #f0f4ff; display:flex; align-items:flex-start; gap:12px; transition:background .15s; }
  .notif-row:hover { background:#f8faff; }
  .notif-row.unread { background:#eff4ff; border-left:3px solid #0B4ACB; }
  .notif-icon { width:38px; height:38px; border-radius:12px; display:grid; place-items:center; flex-shrink:0; }
  .filter-btn { border-radius:10px; padding:6px 14px; font-size:13px; font-weight:600; border:1.5px solid #e2e8f0; background:#fff; color:#64748b; text-decoration:none; transition:all .2s; display:inline-flex; align-items:center; gap:6px; }
  .filter-btn:hover { border-color:#0B4ACB; color:#0B4ACB; }
  .filter-btn.active { background:linear-gradient(135deg,#0B4ACB,#3B63E6); color:#fff; border-color:#0B4ACB; }
  @media(max-width:768px) { .stat-card { padding:14px 12px; gap:10px; } .stat-num { font-size:20px; } }
</style>

<?php displayFlash(); ?>

<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-800" style="color:#0f172a;"><i class="fas fa-bell me-2 text-primary"></i>Notifications</h5>
    <small class="text-muted">Manage & send notifications</small>
  </div>
  <form method="POST">
    <input type="hidden" name="action" value="mark_all_read">
    <button class="btn btn-sm btn-outline-primary"><i class="fas fa-check-double me-1"></i>Mark All Read</button>
  </form>
</div>

<!-- Stats -->
<div class="row g-3 mb-4">
  <?php $cards = [
    ['Total',    $stats['total'],  'fa-bell',         'linear-gradient(135deg,#0B4ACB,#3B63E6)'],
    ['Unread',   $stats['unread'], 'fa-envelope',     'linear-gradient(135deg,#dc2626,#ef4444)'],
    ['Today',    $stats['today'],  'fa-calendar-day', 'linear-gradient(135deg,#0891b2,#06b6d4)'],
  ]; ?>
  <?php foreach ($cards as [$lbl,$val,$icon,$grad]): ?>
  <div class="col-4">
    <div class="stat-card" style="background:<?= $grad ?>;">
      <div class="stat-icon"><i class="fas <?= $icon ?>"></i></div>
      <div><div class="stat-num"><?= $val ?></div><div class="stat-lbl"><?= $lbl ?></div></div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<div class="row g-4">
  <!-- Notifications List -->
  <div class="col-lg-8">
    <!-- Filter tabs -->
    <div class="d-flex gap-2 mb-3 flex-wrap">
      <a href="?filter=all<?= $user_type_filter?'&user_type='.$user_type_filter:'' ?>" class="filter-btn <?= $filter==='all'?'active':'' ?>"><i class="fas fa-list"></i> All</a>
      <a href="?filter=unread<?= $user_type_filter?'&user_type='.$user_type_filter:'' ?>" class="filter-btn <?= $filter==='unread'?'active':'' ?>"><i class="fas fa-envelope"></i> Unread</a>
      <a href="?filter=read<?= $user_type_filter?'&user_type='.$user_type_filter:'' ?>" class="filter-btn <?= $filter==='read'?'active':'' ?>"><i class="fas fa-envelope-open"></i> Read</a>
      <select class="form-select form-select-sm" style="width:auto;" onchange="location='?filter=<?= $filter ?>&user_type='+this.value">
        <option value="">All Users</option>
        <option value="patient" <?= $user_type_filter==='patient'?'selected':'' ?>>Patients</option>
        <option value="doctor"  <?= $user_type_filter==='doctor'?'selected':'' ?>>Doctors</option>
      </select>
    </div>

    <div class="admin-card">
      <?php if (empty($notifications)): ?>
        <div class="p-5 text-center text-muted">
          <i class="fas fa-bell-slash fa-3x mb-3" style="opacity:.2;"></i>
          <h6>No notifications found</h6>
        </div>
      <?php else: ?>
        <?php foreach ($notifications as $n):
          $ico_map = ['patient'=>['fa-user','#0B4ACB','#eff4ff'], 'doctor'=>['fa-user-md','#059669','#f0fdf4']];
          [$ico,$clr,$bg] = $ico_map[$n['user_type']] ?? ['fa-user-shield','#7c3aed','#f5f3ff'];
        ?>
        <div class="notif-row <?= !$n['is_read']?'unread':'' ?>">
          <div class="notif-icon" style="background:<?= $bg ?>;"><i class="fas <?= $ico ?>" style="color:<?= $clr ?>;font-size:15px;"></i></div>
          <div class="flex-grow-1">
            <div class="d-flex justify-content-between align-items-start flex-wrap gap-1">
              <div>
                <div style="font-weight:<?= !$n['is_read']?'700':'600' ?>;font-size:13px;">
                  <?= htmlspecialchars($n['title']) ?>
                  <?php if (!$n['is_read']): ?><span class="badge bg-danger ms-1" style="font-size:9px;">NEW</span><?php endif; ?>
                </div>
                <div style="font-size:12px;color:#4a5568;margin-top:2px;"><?= htmlspecialchars($n['message']) ?></div>
                <div style="font-size:11px;color:#94a3b8;margin-top:4px;">
                  <i class="fas fa-user me-1"></i><?= ucfirst($n['user_type']) ?>: <?= htmlspecialchars($n['user_name'] ?? 'Unknown') ?>
                  &nbsp;&middot;&nbsp;<i class="fas fa-clock me-1"></i><?= date('d M Y, h:i A', strtotime($n['created_at'])) ?>
                  &nbsp;&middot;&nbsp;<span class="badge bg-light text-dark"><?= ucfirst($n['channel'] ?? 'in_app') ?></span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>

  <!-- Send Notification -->
  <div class="col-lg-4">
    <div class="admin-card">
      <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-paper-plane me-2 text-primary"></i>Send Notification</h6></div>
      <div class="p-3">
        <form method="POST">
          <input type="hidden" name="action" value="send_notification">
          <div class="mb-3">
            <label class="form-label fw-600" style="font-size:12px;">User Type</label>
            <select name="user_type" class="form-select form-select-sm" required>
              <option value="">Select...</option>
              <option value="patient">Patient</option>
              <option value="doctor">Doctor</option>
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label fw-600" style="font-size:12px;">User ID <small class="text-muted fw-400">(0 = all)</small></label>
            <input type="number" name="user_id" class="form-control form-control-sm" placeholder="0" required>
          </div>
          <div class="mb-3">
            <label class="form-label fw-600" style="font-size:12px;">Title</label>
            <input type="text" name="title" class="form-control form-control-sm" placeholder="Notification title" required>
          </div>
          <div class="mb-3">
            <label class="form-label fw-600" style="font-size:12px;">Message</label>
            <textarea name="message" class="form-control form-control-sm" rows="3" placeholder="Message..." required></textarea>
          </div>
          <div class="mb-3">
            <label class="form-label fw-600" style="font-size:12px;">Channel</label>
            <select name="channel" class="form-select form-select-sm">
              <option value="in_app">In-App</option>
              <option value="email">Email</option>
              <option value="sms">SMS</option>
            </select>
          </div>
          <button type="submit" class="btn btn-primary btn-sm w-100"><i class="fas fa-paper-plane me-1"></i>Send</button>
        </form>
      </div>
    </div>

    <!-- Quick Templates -->
    <div class="admin-card mt-3">
      <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-bolt me-2 text-warning"></i>Quick Templates</h6></div>
      <div class="p-3 d-grid gap-2">
        <button class="btn btn-outline-primary btn-sm" onclick="fillTemplate('Appointment Reminder','Your appointment is scheduled for tomorrow. Please be on time.')">Appointment Reminder</button>
        <button class="btn btn-outline-success btn-sm" onclick="fillTemplate('Doctor Approved','Congratulations! Your account has been verified. You can now receive patients.')">Doctor Approved</button>
        <button class="btn btn-outline-info btn-sm" onclick="fillTemplate('Payment Received','Your payment has been received successfully.')">Payment Received</button>
        <button class="btn btn-outline-warning btn-sm" onclick="fillTemplate('System Maintenance','HealthLink will undergo maintenance on Sunday 2AM-4AM.')">System Maintenance</button>
      </div>
    </div>
  </div>
</div>

<script>
function fillTemplate(title, msg) {
  document.querySelector('input[name=title]').value = title;
  document.querySelector('textarea[name=message]').value = msg;
  document.querySelector('input[name=title]').scrollIntoView({behavior:'smooth'});
}
</script>

<?php include 'footer.php'; ?>
