<?php
require_once '../config.php';
requirePatient();

$patient_id = $_SESSION['patient_id'];

// Mark all as read when page opens
$conn->query("UPDATE notifications SET is_read=1 WHERE user_type='patient' AND user_id=$patient_id AND is_read=0");

// Mark single as read
if (isset($_GET['read'])) {
    $nid = (int)$_GET['read'];
    $conn->query("UPDATE notifications SET is_read=1 WHERE id=$nid AND user_id=$patient_id");
    header('Location: notifications.php');
    exit;
}

// Delete notification
if (isset($_GET['delete'])) {
    $nid = (int)$_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM notifications WHERE id=? AND user_id=? AND user_type='patient'");
    $stmt->bind_param('ii', $nid, $patient_id);
    $stmt->execute();
    setFlash('success', 'Notification deleted.');
    header('Location: notifications.php');
    exit;
}

// Delete all
if (isset($_POST['delete_all'])) {
    $conn->query("DELETE FROM notifications WHERE user_type='patient' AND user_id=$patient_id");
    setFlash('success', 'All notifications cleared.');
    header('Location: notifications.php');
    exit;
}

// Fetch notifications
$filter = $_GET['filter'] ?? 'all';
$where_filter = $filter === 'unread' ? "AND is_read=0" : ($filter === 'read' ? "AND is_read=1" : "");

$notifications = $conn->query("
    SELECT * FROM notifications
    WHERE user_type='patient' AND user_id=$patient_id $where_filter
    ORDER BY created_at DESC
")->fetch_all(MYSQLI_ASSOC);

$total       = $conn->query("SELECT COUNT(*) FROM notifications WHERE user_type='patient' AND user_id=$patient_id")->fetch_row()[0];
$unread_count = $conn->query("SELECT COUNT(*) FROM notifications WHERE user_type='patient' AND user_id=$patient_id AND is_read=0")->fetch_row()[0];

$notif_icons = [
    'appointment'          => ['fa' => 'fa-calendar-check',  'color' => 'primary'],
    'verification_status'  => ['fa' => 'fa-check-circle',    'color' => 'success'],
    'prescription'         => ['fa' => 'fa-prescription-bottle-alt', 'color' => 'success'],
    'reminder'             => ['fa' => 'fa-bell',            'color' => 'warning'],
    'payment'              => ['fa' => 'fa-credit-card',     'color' => 'info'],
    'general'              => ['fa' => 'fa-info-circle',     'color' => 'secondary'],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Notifications - HealthLink</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <style>
    body { background: #f0f4ff; font-family: Inter, 'Segoe UI', sans-serif; }
    .card { border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 2px 10px rgba(11,74,203,.07); }
    .top-bar { background:#fff; border-bottom:1px solid #e2e8f0; padding:14px 28px; display:flex; align-items:center; justify-content:space-between; box-shadow:0 1px 8px rgba(11,74,203,.07); }
    .top-bar h5 { margin:0; font-size:16px; font-weight:700; color:#0f172a; }
    .page-body { padding:26px 28px; }
    .notif-row { padding:16px 20px; border-bottom:1px solid #f0f4ff; display:flex; align-items:flex-start; gap:14px; transition:background .15s; }
    .notif-row:hover { background:#f8faff; }
    .notif-row:last-child { border-bottom:none; }
    .notif-row.unread { background:#eff4ff; border-left:3px solid #0B4ACB; }
    .notif-icon { width:42px; height:42px; border-radius:14px; display:flex; align-items:center; justify-content:center; font-size:1.2rem; flex-shrink:0; background:#eff4ff; border:1px solid #c7d7fc; }
    .filter-btn { border-radius:10px; padding:7px 16px; 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; box-shadow:0 4px 12px rgba(11,74,203,.25); }
    .stat-card { border-radius:16px; padding:20px 24px; display:flex; align-items:center; gap:16px; box-shadow:0 4px 16px rgba(11,74,203,.1); }
    .btn-blue { background:linear-gradient(135deg,#0B4ACB,#3B63E6); color:#fff !important; border:none; padding:8px 18px; border-radius:10px; font-size:13px; font-weight:600; text-decoration:none; display:inline-flex; align-items:center; gap:6px; transition:all .2s; cursor:pointer; }
    .btn-blue:hover { opacity:.9; transform:translateY(-1px); }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>

<div class="main-content">
<?php $page_title = 'Notifications'; include 'topbar.php'; ?>

  <div class="page-body">
    <?php displayFlash(); ?>

    <!-- Stats -->
    <div class="row g-3 mb-4">
      <div class="col-6 col-md-3">
        <div class="stat-card" style="background:linear-gradient(135deg,#0B4ACB,#3B63E6);">
          <div style="width:46px;height:46px;border-radius:14px;background:rgba(255,255,255,.2);display:grid;place-items:center;font-size:20px;"><i class="fas fa-bell" style="color:#fff;"></i></div>
          <div><div style="font-size:28px;font-weight:800;color:#fff;line-height:1;"><?= $total ?></div><div style="font-size:12px;color:rgba(255,255,255,.8);margin-top:3px;">Total</div></div>
        </div>
      </div>
      <div class="col-6 col-md-3">
        <div class="stat-card" style="background:linear-gradient(135deg,#dc2626,#ef4444);">
          <div style="width:46px;height:46px;border-radius:14px;background:rgba(255,255,255,.2);display:grid;place-items:center;font-size:20px;"><i class="fas fa-envelope" style="color:#fff;"></i></div>
          <div><div style="font-size:28px;font-weight:800;color:#fff;line-height:1;"><?= $unread_count ?></div><div style="font-size:12px;color:rgba(255,255,255,.8);margin-top:3px;">Unread</div></div>
        </div>
      </div>
    </div>

    <!-- Filter Tabs -->
    <div class="mb-3 d-flex gap-2 flex-wrap">
      <a href="?filter=all" class="filter-btn <?= $filter==='all'?'active':'' ?>"><i class="fas fa-list"></i> All (<?= $total ?>)</a>
      <a href="?filter=unread" class="filter-btn <?= $filter==='unread'?'active':'' ?>" style="<?= $filter!=='unread'?'border-color:#fecaca;color:#ef4444;':'' ?>"><i class="fas fa-envelope"></i> Unread (<?= $unread_count ?>)</a>
      <a href="?filter=read" class="filter-btn <?= $filter==='read'?'active':'' ?>"><i class="fas fa-envelope-open"></i> Read</a>
    </div>

    <!-- Notifications List -->
    <div class="card">
      <?php if (empty($notifications)): ?>
        <div class="p-5 text-center text-muted">
          <i class="fas fa-bell-slash fa-4x mb-3" style="opacity:0.2;"></i>
          <h5>No Notifications</h5>
          <p>You're all caught up! Notifications about appointments, prescriptions, and reminders will appear here.</p>
        </div>
      <?php else: ?>
        <?php foreach ($notifications as $n):
          $ni = $notif_icons[$n['type']] ?? $notif_icons['general'];
        ?>
          <div class="notif-row <?= !$n['is_read'] ? 'unread' : '' ?>">
            <div class="notif-icon"><i class="fas <?= $ni['fa'] ?> text-<?= $ni['color'] ?>"></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' : '500' ?>;font-size:0.9rem;">
                    <?= htmlspecialchars($n['title']) ?>
                    <?php if (!$n['is_read']): ?>
                      <span class="badge bg-danger ms-1" style="font-size:0.6rem;">NEW</span>
                    <?php endif; ?>
                  </div>
                  <div style="font-size:0.82rem;color:#4a5568;margin-top:3px;"><?= htmlspecialchars($n['message']) ?></div>
                  <div style="font-size:0.72rem;color:#a0aec0;margin-top:4px;">
                    <i class="fas fa-clock me-1"></i><?= date('d M Y, h:i A', strtotime($n['created_at'])) ?>
                    <span class="badge ms-1" style="background:#eff4ff;color:#0B4ACB;font-size:10px;"><?= ucfirst(str_replace('_',' ',$n['type'])) ?></span>
                  </div>
                </div>
                <div class="d-flex gap-2 flex-shrink-0">
                  <a href="?delete=<?= $n['id'] ?>" onclick="return confirm('Delete?')" class="text-muted" style="font-size:0.78rem;" title="Delete">
                    <i class="fas fa-times"></i>
                  </a>
                </div>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
