<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require 'config.php';

/* ── AUTH: HR / Admin only ── */
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', ['hr','admin','superadmin'])) {
    die("Access Denied — HR Access Required");
}

$success = ""; $error = "";

/* ── ADD / UPDATE ── */
if (isset($_POST['save_birthday'])) {
    $uid  = intval($_POST['user_id'] ?? 0);
    $dob  = $_POST['date_of_birth'] ?? '';
    $note = trim($_POST['date_of_birth'] ?? '');

    if (!$uid || !$dob) {
        $error = "Please select an employee and provide a date of birth.";
    } else {
        $photo_path = null;
        if (!empty($_FILES['photo']['name'])) {
            $target_dir = "uploads/"; // Ensure this directory exists and is writable
            if (!file_exists($target_dir)) {
                mkdir($target_dir, 0755, true);
            }
            $target_file = $target_dir . basename($_FILES["photo"]["name"]);
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

            // Validate image
            $check = getimagesize($_FILES["photo"]["tmp_name"]);
            if ($check === false) {
                $error = "File is not an image.";
            } elseif ($_FILES["photo"]["size"] > 5000000) { // 5MB limit
                $error = "File is too large.";
            } elseif (!in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif'])) {
                $error = "Only JPG, JPEG, PNG & GIF files are allowed. Detected extension: .$imageFileType";
            } elseif (file_exists($target_file)) {
                $error = "File already exists.";
            } else {
                if (move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file)) {
                    $photo_path = $target_file;
                } else {
                    $error = "Failed to upload photo.";
                }
            }
        }

        if (empty($error)) {
            // Fetch current photo if no new upload
            if ($photo_path === null) {
                $current = $conn->query("SELECT photo FROM users WHERE id=$uid")->fetch_assoc();
                $photo_path = $current['photo'] ?? null;
            }

            $stmt = $conn->prepare("UPDATE users SET date_of_birth=?, date_of_birth=?, photo=? WHERE id=?");
            $stmt->bind_param("sssi", $dob, $note, $photo_path, $uid);
            $success = $stmt->execute() ? "Birthday saved successfully." : "Failed to save. ".$conn->error;
        }
    }
}

/* ── DELETE (clear DOB) ── */
if (isset($_GET['clear']) && is_numeric($_GET['clear'])) {
    $cid = intval($_GET['clear']);
    $conn->query("UPDATE users SET date_of_birth=NULL, date_of_birth=NULL WHERE id=$cid");
    $success = "Birthday record cleared.";
}

/* ── FETCH ALL EMPLOYEES ── */
$employees = $conn->query("
    SELECT id, first_name, last_name, division, designation, date_of_birth, date_of_birth, photo,
           CASE WHEN date_of_birth IS NOT NULL AND date_of_birth != '0000-00-00' THEN 1 ELSE 0 END AS has_dob
    FROM users
    WHERE status='active'
    ORDER BY first_name
");

/* ── STATS ── */
$s_total   = $conn->query("SELECT COUNT(*) AS c FROM users WHERE status='active'")->fetch_assoc()['c'];
$s_hasDob  = $conn->query("SELECT COUNT(*) AS c FROM users WHERE status='active' AND date_of_birth IS NOT NULL AND date_of_birth!='0000-00-00'")->fetch_assoc()['c'];
$s_today   = $conn->query("SELECT COUNT(*) AS c FROM users WHERE status='active' AND DATE_FORMAT(date_of_birth,'%m-%d')=DATE_FORMAT(NOW(),'%m-%d')")->fetch_assoc()['c'];
$s_month   = $conn->query("SELECT COUNT(*) AS c FROM users WHERE status='active' AND MONTH(date_of_birth)=MONTH(NOW())")->fetch_assoc()['c'];
$s_missing = $s_total - $s_hasDob;

/* ── FETCH FOR EDIT MODE ── */
$editData = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $eid = intval($_GET['edit']);
    $editData = $conn->query("SELECT * FROM users WHERE id=$eid")->fetch_assoc();
}

/* ── PREP TABLE ROWS ── */
$rows = [];
$employees->data_seek(0);
while($r = $employees->fetch_assoc()) $rows[] = $r;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Birthday Management — HR Panel</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=Fraunces:wght@700;800;900&family=DM+Sans:opsz,wght@9..40,300;9..40,400;9..40,500;9..40,600;9..40,700&display=swap" rel="stylesheet">

<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

:root {
  --plum:   #4a1942;
  --plum2:  #6b2d62;
  --rose:   #e11d48;
  --rose2:  #f43f5e;
  --pink:   #f472b6;
  --gold:   #d97706;
  --bg:     #fdf6fb;
  --card:   #ffffff;
  --border: #f0e4f5;
  --text:   #2a1628;
  --muted:  #7a5f76;
  --green:  #059669;
  --red:    #dc2626;
  --shadow: 0 4px 24px rgba(74,25,66,.09);
  --r:      14px;
}

body {
  font-family: 'DM Sans', sans-serif;
  background: var(--bg);
  color: var(--text);
  min-height: 100vh;
}
body::before {
  content: '';
  position: fixed; inset: 0;
  background: radial-gradient(ellipse 80% 50% at 50% 0%, rgba(74,25,66,.07), transparent);
  pointer-events: none; z-index: 0;
}

/* ── NAV ── */
.topnav {
  background: var(--plum);
  padding: 0 2.5rem; height: 62px;
  display: flex; align-items: center; justify-content: space-between;
  position: sticky; top: 0; z-index: 200;
  box-shadow: 0 2px 24px rgba(74,25,66,.4);
}
.nav-brand {
  font-family: 'Fraunces', serif;
  font-size: 1.15rem; font-weight: 800;
  color: #fff;
  display: flex; align-items: center; gap: 10px;
}
.hr-badge {
  background: rgba(244,114,182,.25);
  border: 1px solid rgba(244,114,182,.4);
  color: var(--pink);
  font-family: 'DM Sans', sans-serif;
  font-size: .65rem; font-weight: 700;
  padding: 2px 9px; border-radius: 20px;
  letter-spacing: .1em; text-transform: uppercase;
}
.nav-actions { display: flex; gap: 10px; align-items: center; }
.nav-btn {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 7px 16px; border-radius: 8px;
  font-size: .82rem; font-weight: 600;
  text-decoration: none; border: none; cursor: pointer;
  transition: .2s;
}
.nav-btn-ghost {
  background: rgba(255,255,255,.07);
  color: rgba(255,255,255,.8);
  border: 1px solid rgba(255,255,255,.12);
}
.nav-btn-ghost:hover { background: rgba(255,255,255,.14); color: #fff; }
.nav-btn-rose {
  background: linear-gradient(135deg, var(--rose), var(--rose2));
  color: #fff;
  box-shadow: 0 4px 14px rgba(225,29,72,.3);
}
.nav-btn-rose:hover { box-shadow: 0 6px 20px rgba(225,29,72,.45); transform: translateY(-1px); }

/* ── PAGE ── */
.page { max-width: 1200px; margin: 0 auto; padding: 2.5rem 1.5rem 5rem; position: relative; z-index: 1; }

/* ── PAGE HEADER ── */
.page-hd { margin-bottom: 2rem; }
.page-hd h1 {
  font-family: 'Fraunces', serif;
  font-size: 2rem; font-weight: 900; color: var(--plum);
  letter-spacing: -.03em;
}
.page-hd p { color: var(--muted); font-size: .9rem; margin-top: 4px; }

/* ── ALERTS ── */
.alert {
  display: flex; align-items: center; gap: 12px;
  padding: 14px 20px; border-radius: 10px;
  font-size: .88rem; font-weight: 500;
  margin-bottom: 1.5rem;
  animation: slideIn .35s ease;
}
.alert-success { background: #ecfdf5; border: 1px solid #6ee7b7; color: #065f46; }
.alert-danger  { background: #fff1f2; border: 1px solid #fda4af; color: #9f1239; }
@keyframes slideIn { from{opacity:0;transform:translateY(-8px)} to{opacity:1;transform:translateY(0)} }

/* ── STATS ROW ── */
.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem; margin-bottom: 2rem;
}
.stat-card {
  background: var(--card);
  border-radius: var(--r);
  padding: 1.2rem 1.5rem;
  border: 1.5px solid var(--border);
  display: flex; align-items: center; gap: 14px;
  box-shadow: var(--shadow);
  animation: popIn .4s cubic-bezier(.34,1.56,.64,1) both;
}
.stat-card:nth-child(2){animation-delay:.08s}
.stat-card:nth-child(3){animation-delay:.16s}
.stat-card:nth-child(4){animation-delay:.24s}
@keyframes popIn {
  from{opacity:0;transform:scale(.88) translateY(16px)}
  to{opacity:1;transform:scale(1) translateY(0)}
}
.st-icon {
  width: 46px; height: 46px; border-radius: 12px;
  display: flex; align-items: center; justify-content: center;
  font-size: 1.3rem; flex-shrink: 0;
}
.sti-1 { background: linear-gradient(135deg,#fce7f3,#f9a8d4); }
.sti-2 { background: linear-gradient(135deg,#ede9fe,#c4b5fd); }
.sti-3 { background: linear-gradient(135deg,#d1fae5,#6ee7b7); }
.sti-4 { background: linear-gradient(135deg,#fee2e2,#fca5a5); }
.st-label { font-size: .72rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
.st-val {
  font-family: 'Fraunces', serif;
  font-size: 1.9rem; font-weight: 800;
  color: var(--plum); line-height: 1; margin-top: 2px;
}

/* ── TWO COL LAYOUT ── */
.layout { display: grid; grid-template-columns: 380px 1fr; gap: 2rem; align-items: start; }

/* ── FORM CARD ── */
.form-card {
  background: var(--card);
  border-radius: var(--r);
  border: 1.5px solid var(--border);
  box-shadow: var(--shadow);
  overflow: hidden;
  position: sticky; top: 80px;
}
.fc-head {
  background: linear-gradient(135deg, var(--plum), var(--plum2));
  padding: 1.3rem 1.75rem;
  display: flex; align-items: center; gap: 12px;
}
.fc-head-icon {
  width: 40px; height: 40px; border-radius: 10px;
  background: rgba(255,255,255,.15);
  display: flex; align-items: center; justify-content: center;
  font-size: 1.2rem;
}
.fc-head h3 { font-family: 'Fraunces', serif; font-size: 1rem; font-weight: 800; color: #fff; }
.fc-head p  { font-size: .75rem; color: rgba(255,255,255,.65); margin-top: 2px; }
.fc-body { padding: 1.75rem; }

.field { margin-bottom: 1.1rem; }
.field label {
  display: block; font-size: .74rem; font-weight: 700;
  color: var(--muted); text-transform: uppercase;
  letter-spacing: .06em; margin-bottom: 6px;
}
.field select,
.field input[type="date"],
.field input[type="file"],
.field textarea {
  width: 100%;
  padding: 10px 14px;
  border: 1.5px solid var(--border);
  border-radius: 9px;
  font-family: 'DM Sans', sans-serif;
  font-size: .88rem;
  color: var(--text);
  background: #fff;
  transition: border-color .2s, box-shadow .2s;
}
.field select {
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%237a5f76' stroke-width='2.5'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 12px center;
  padding-right: 36px;
  cursor: pointer;
}
.field textarea { resize: vertical; min-height: 72px; }
.field select:focus,
.field input:focus,
.field textarea:focus {
  outline: none;
  border-color: var(--rose2);
  box-shadow: 0 0 0 3px rgba(244,63,94,.1);
}

.divider { height: 1px; background: var(--border); margin: 1.2rem 0; }

.btn-save {
  width: 100%;
  display: flex; align-items: center; justify-content: center; gap: 8px;
  background: linear-gradient(135deg, var(--plum), var(--plum2));
  color: #fff; border: none;
  padding: 12px 24px; border-radius: 10px;
  font-family: 'DM Sans', sans-serif;
  font-size: .9rem; font-weight: 700;
  cursor: pointer;
  box-shadow: 0 4px 16px rgba(74,25,66,.35);
  transition: .2s;
}
.btn-save:hover { transform: translateY(-1px); box-shadow: 0 6px 22px rgba(74,25,66,.45); }

.btn-reset {
  width: 100%;
  display: flex; align-items: center; justify-content: center; gap: 8px;
  background: transparent; color: var(--muted);
  border: 1.5px solid var(--border);
  padding: 10px 24px; border-radius: 10px;
  font-family: 'DM Sans', sans-serif;
  font-size: .88rem; font-weight: 600;
  cursor: pointer; margin-top: 8px;
  transition: .2s;
}
.btn-reset:hover { border-color: #c4a4c0; color: var(--text); }

/* ── TABLE CARD ── */
.table-card {
  background: var(--card);
  border-radius: var(--r);
  border: 1.5px solid var(--border);
  box-shadow: var(--shadow);
  overflow: hidden;
}
.tc-toolbar {
  padding: 1.1rem 1.5rem;
  border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 12px;
  flex-wrap: wrap;
}
.tc-toolbar h3 {
  font-family: 'Fraunces', serif;
  font-size: 1rem; font-weight: 800; color: var(--plum);
}
.pill-count {
  background: linear-gradient(135deg, var(--rose), var(--rose2));
  color: #fff; font-size: .68rem; font-weight: 700;
  padding: 2px 9px; border-radius: 20px;
}
.search-wrap { position: relative; margin-left: auto; }
.search-wrap input {
  padding: 8px 14px 8px 34px;
  border: 1.5px solid var(--border);
  border-radius: 8px;
  font-family: 'DM Sans', sans-serif;
  font-size: .83rem; color: var(--text);
  width: 220px;
  transition: border-color .2s;
}
.search-wrap input:focus { outline: none; border-color: var(--rose2); }
.search-wrap svg { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: var(--muted); }

/* filter tabs */
.filter-tabs { display: flex; gap: 6px; }
.ftab {
  padding: 5px 14px; border-radius: 20px;
  font-size: .75rem; font-weight: 600;
  border: 1.5px solid var(--border);
  background: #fff; color: var(--muted);
  cursor: pointer; transition: .2s;
}
.ftab.active { background: var(--plum); color: #fff; border-color: var(--plum); }
.ftab:hover:not(.active) { border-color: #c4a4c0; color: var(--text); }

/* table */
.data-table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: .85rem; }
.data-table thead th {
  background: #faf4fc;
  padding: 10px 16px;
  font-size: .7rem; font-weight: 700; text-transform: uppercase;
  letter-spacing: .07em; color: var(--muted);
  border-bottom: 1.5px solid var(--border); text-align: left;
}
.data-table tbody tr { transition: background .12s; }
.data-table tbody tr:hover { background: #fdf0f8; }
.data-table tbody td { padding: 12px 16px; border-bottom: 1px solid #f9f2fd; vertical-align: middle; }
.data-table tbody tr:last-child td { border-bottom: none; }

.emp-avatar {
  width: 36px; height: 36px; border-radius: 50%; object-fit: cover;
  display: flex; align-items: center; justify-content: center;
  font-size: .78rem; font-weight: 800; color: #fff;
  flex-shrink: 0;
}
.emp-name { font-weight: 600; color: var(--plum); }
.emp-dept { font-size: .74rem; color: var(--muted); margin-top: 1px; }

.dob-val { font-weight: 600; color: var(--text); }
.dob-sub { font-size: .73rem; color: var(--muted); margin-top: 1px; }

.status-set   { background:#ecfdf5;color:#065f46;padding:3px 10px;border-radius:20px;font-size:.72rem;font-weight:700; }
.status-unset { background:#fef2f2;color:#991b1b;padding:3px 10px;border-radius:20px;font-size:.72rem;font-weight:700; }
.birthday-today { background:#fff7ed;color:#9a3412;padding:3px 10px;border-radius:20px;font-size:.72rem;font-weight:700;animation:pulse 1.5s ease-in-out infinite; }
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.7} }

.days-tag { display:inline-block;padding:3px 9px;border-radius:20px;font-size:.72rem;font-weight:700;background:#f5f3ff;color:#5b21b6; }
.days-tag.soon { background:#fff7ed;color:#c2410c; }
.days-tag.today { background:linear-gradient(135deg,#f43f5e,#fb923c);color:#fff; }

.action-btns { display: flex; gap: 6px; }
.a-btn {
  display: inline-flex; align-items: center; gap: 4px;
  padding: 6px 12px; border-radius: 7px;
  font-size: .75rem; font-weight: 600;
  text-decoration: none; border: none; cursor: pointer;
  transition: .15s;
}
.a-btn-edit { background: #f5f3ff; color: #5b21b6; border: 1px solid #ddd6fe; }
.a-btn-edit:hover { background: #5b21b6; color: #fff; }
.a-btn-clear { background: #fff1f2; color: #be123c; border: 1px solid #fecdd3; }
.a-btn-clear:hover { background: #be123c; color: #fff; }

/* avatar color cycle */
.av-1 { background: linear-gradient(135deg,#f43f5e,#fb7185); }
.av-2 { background: linear-gradient(135deg,#8b5cf6,#a78bfa); }
.av-3 { background: linear-gradient(135deg,#0ea5e9,#38bdf8); }
.av-4 { background: linear-gradient(135deg,#10b981,#34d399); }
.av-5 { background: linear-gradient(135deg,#f59e0b,#fbbf24); }
.av-6 { background: linear-gradient(135deg,#ec4899,#f472b6); }

.no-data-row td { text-align:center;padding:3rem;color:var(--muted);font-size:.9rem; }

/* ── EDIT MODE HIGHLIGHT ── */
.form-card.editing .fc-head { background: linear-gradient(135deg, #be123c, var(--rose2)); }
.edit-notice {
  background: #fff7ed; border: 1.5px solid #fed7aa;
  border-radius: 9px; padding: 10px 14px;
  font-size: .82rem; color: #92400e; font-weight: 500;
  display: flex; align-items: center; gap: 8px;
  margin-bottom: 1rem;
}

@media (max-width: 900px) {
  .layout { grid-template-columns: 1fr; }
  .form-card { position: static; }
  .stats-row { grid-template-columns: repeat(2,1fr); }
}
@media (max-width: 600px) {
  .topnav { padding: 0 1rem; }
  .page { padding: 1.5rem 1rem 3rem; }
  .stats-row { grid-template-columns: 1fr 1fr; }
  .search-wrap input { width: 160px; }
}
</style>
</head>
<body>

<!-- NAV -->
<nav class="topnav">
  <div class="nav-brand">
    🎂 Birthday Manager <span class="hr-badge">HR Only</span>
  </div>
  <div class="nav-actions">
    <a href="birthday_view.php" class="nav-btn nav-btn-ghost">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
      View Page
    </a>
    <a href="dashboard_admin.php" class="nav-btn nav-btn-ghost">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>
      Dashboard
    </a>
  </div>
</nav>

<div class="page">

  <!-- PAGE HEADER -->
  <div class="page-hd">
    <h1>🎂 Birthday Management</h1>
    <p>Add, edit and manage employee birthdays. These appear on the company-wide birthday reminder page.</p>
  </div>

  <!-- ALERTS -->
  <?php if($success): ?>
  <div class="alert alert-success">✅ <?= htmlspecialchars($success) ?></div>
  <?php endif; ?>
  <?php if($error): ?>
  <div class="alert alert-danger">⚠️ <?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <!-- STATS -->
  <div class="stats-row">
    <div class="stat-card">
      <div class="st-icon sti-1">👥</div>
      <div>
        <div class="st-label">Total Employees</div>
        <div class="st-val"><?= $s_total ?></div>
      </div>
    </div>
    <div class="stat-card">
      <div class="st-icon sti-2">✅</div>
      <div>
        <div class="st-label">DOB Recorded</div>
        <div class="st-val"><?= $s_hasDob ?></div>
      </div>
    </div>
    <div class="stat-card">
      <div class="st-icon sti-3">🎂</div>
      <div>
        <div class="st-label">This Month</div>
        <div class="st-val"><?= $s_month ?></div>
      </div>
    </div>
    <div class="stat-card">
      <div class="st-icon sti-4">⚠️</div>
      <div>
        <div class="st-label">Missing DOB</div>
        <div class="st-val" style="<?= $s_missing>0?'color:var(--red)':'' ?>"><?= $s_missing ?></div>
      </div>
    </div>
  </div>

  <!-- LAYOUT -->
  <div class="layout">

    <!-- LEFT: FORM -->
    <div class="form-card <?= $editData ? 'editing' : '' ?>">
      <div class="fc-head">
        <div class="fc-head-icon"><?= $editData ? '✏️' : '➕' ?></div>
        <div>
          <h3><?= $editData ? 'Edit Birthday' : 'Add / Update Birthday' ?></h3>
          <p><?= $editData ? 'Editing: '.htmlspecialchars($editData['first_name'].' '.$editData['last_name']) : 'Select an employee and enter their DOB' ?></p>
        </div>
      </div>
      <div class="fc-body">

        <?php if($editData): ?>
        <div class="edit-notice">
          ✏️ Editing <strong><?= htmlspecialchars($editData['first_name'].' '.$editData['last_name']) ?></strong>
          — <a href="birthday_hr.php" style="color:var(--gold);font-weight:700;">Cancel</a>
        </div>
        <?php endif; ?>

        <form method="post" id="bdayForm" enctype="multipart/form-data">

          <div class="field">
            <label>Employee *</label>
            <select name="user_id" required <?= $editData ? 'disabled' : '' ?>>
              <option value="">— Select Employee —</option>
              <?php foreach($rows as $r): ?>
              <option value="<?= $r['id'] ?>"
                <?= ($editData && $editData['id'] == $r['id']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($r['first_name'].' '.$r['last_name']) ?>
                (<?= htmlspecialchars($r['division'] ?? $r['designation'] ?? 'N/A') ?>)
              </option>
              <?php endforeach; ?>
            </select>
            <?php if($editData): ?>
            <input type="hidden" name="user_id" value="<?= $editData['id'] ?>">
            <?php endif; ?>
          </div>

          <div class="field">
            <label>Date of Birth *</label>
            <input type="date"
                   name="date_of_birth"
                   max="<?= date('Y-m-d', strtotime('-16 years')) ?>"
                   value="<?= $editData ? htmlspecialchars($editData['date_of_birth'] ?? '') : '' ?>"
                   required>
          </div>

          <div class="field">
            <label>Birthday Note <span style="font-weight:400;text-transform:none;">(optional)</span></label>
            <textarea name="date_of_birth" placeholder="e.g. Prefers no fuss, loves chocolate cake…"><?= $editData ? htmlspecialchars($editData['date_of_birth'] ?? '') : '' ?></textarea>
          </div>

          <div class="field">
            <label>Photo <span style="font-weight:400;text-transform:none;">(optional)</span></label>
            <input type="file" name="photo" accept="image/*">
            <?php if($editData && !empty($editData['photo'])): ?>
            <div style="margin-top:8px;">
              Current: <img src="<?= htmlspecialchars($editData['photo']) ?>" style="width:80px;height:80px;border-radius:50%;object-fit:cover;">
            </div>
            <?php endif; ?>
          </div>

          <div class="divider"></div>

          <button type="submit" name="save_birthday" class="btn-save">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
            <?= $editData ? 'Update Birthday' : 'Save Birthday' ?>
          </button>
          <button type="reset" class="btn-reset">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>
            Clear Form
          </button>

        </form>
      </div>
    </div>

    <!-- RIGHT: TABLE -->
    <div class="table-card">

      <!-- toolbar -->
      <div class="tc-toolbar">
        <h3>All Employees <span class="pill-count"><?= count($rows) ?></span></h3>
        <div class="filter-tabs">
          <div class="ftab active" onclick="filterBy('all',this)">All</div>
          <div class="ftab" onclick="filterBy('set',this)">Has DOB</div>
          <div class="ftab" onclick="filterBy('unset',this)">Missing</div>
          <div class="ftab" onclick="filterBy('today',this)">🎂 Today</div>
        </div>
        <div class="search-wrap">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
          <input type="text" id="srch" placeholder="Search name…" oninput="doSearch()">
        </div>
      </div>

      <!-- table -->
      <div style="overflow-x:auto;">
        <table class="data-table" id="mainTable">
          <thead>
            <tr>
              <th>Employee</th>
              <th>division</th>
              <th>Date of Birth</th>
              <th>Status</th>
              <th>Days Left</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $today = date('m-d');
            $avCls = ['av-1','av-2','av-3','av-4','av-5','av-6'];
            foreach($rows as $i => $r):
              $initials = strtoupper(substr($r['first_name'],0,1).substr($r['last_name'],0,1));
              $avClass  = $avCls[$i % count($avCls)];
              $hasDob   = !empty($r['date_of_birth']) && $r['date_of_birth'] !== '0000-00-00';
              $isToday  = false;
              $daysLeft = null;
              $daysStr  = '—';
              $daysTag  = '';

              if($hasDob) {
                $bdMd = date('m-d', strtotime($r['date_of_birth']));
                $isToday = ($bdMd === $today);

                $nowTs  = strtotime(date('Y-m-d'));
                $bdYear = (int)date('Y');
                $bdThisYear = strtotime($bdYear.'-'.date('m-d', strtotime($r['date_of_birth'])));
                if($bdThisYear < $nowTs) $bdThisYear = strtotime(($bdYear+1).'-'.date('m-d', strtotime($r['date_of_birth'])));
                $daysLeft = (int)(($bdThisYear - $nowTs) / 86400);

                if($isToday) {
                  $daysStr = '<span class="days-tag today">🎂 Today!</span>';
                } elseif($daysLeft <= 7) {
                  $daysStr = '<span class="days-tag soon">⏰ '.$daysLeft.' days</span>';
                } else {
                  $daysStr = '<span class="days-tag">'.$daysLeft.' days</span>';
                }
              }

              $dataAttr = 'data-hasdob="'.($hasDob?'set':'unset').'" data-today="'.($isToday?'yes':'no').'"';
            ?>
            <tr <?= $dataAttr ?>>
              <td>
                <div style="display:flex;align-items:center;gap:10px;">
                  <?php if (!empty($r['photo'])): ?>
                    <img src="<?= htmlspecialchars($r['photo']) ?>" class="emp-avatar" alt="<?= $initials ?>">
                  <?php else: ?>
                    <div class="emp-avatar <?= $avClass ?>"><?= $initials ?></div>
                  <?php endif; ?>
                  <div>
                    <div class="emp-name"><?= htmlspecialchars($r['first_name'].' '.$r['last_name']) ?></div>
                    <div class="emp-dept">ID #<?= $r['id'] ?></div>
                  </div>
                </div>
              </td>
              <td style="color:var(--muted);font-size:.83rem;"><?= htmlspecialchars($r['division'] ?? $r['designation'] ?? '—') ?></td>
              <td>
                <?php if($hasDob): ?>
                <div class="dob-val"><?= date('d M Y', strtotime($r['date_of_birth'])) ?></div>
                <div class="dob-sub">
                  Turns <?= (int)date('Y') - (int)date('Y', strtotime($r['date_of_birth'])) + ($daysLeft === 0 ? 0 : 1) ?> this year
                  <?php if (!empty($r['date_of_birth'])): ?>
                  <br><span style="font-style:italic;"><?= htmlspecialchars($r['date_of_birth']) ?></span>
                  <?php endif; ?>
                </div>
                <?php else: ?>
                <span style="color:var(--muted);font-style:italic;font-size:.82rem;">Not recorded</span>
                <?php endif; ?>
              </td>
              <td>
                <?php if($isToday): ?>
                  <span class="birthday-today">🎉 Birthday Today!</span>
                <?php elseif($hasDob): ?>
                  <span class="status-set">✓ Recorded</span>
                <?php else: ?>
                  <span class="status-unset">✗ Missing</span>
                <?php endif; ?>
              </td>
              <td><?= $daysStr ?></td>
              <td>
                <div class="action-btns">
                  <a href="birthday_hr.php?edit=<?= $r['id'] ?>" class="a-btn a-btn-edit">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                    Edit
                  </a>
                  <?php if($hasDob): ?>
                  <a href="birthday_hr.php?clear=<?= $r['id'] ?>"
                     onclick="return confirm('Clear birthday for <?= htmlspecialchars(addslashes($r['first_name'])) ?>?')"
                     class="a-btn a-btn-clear">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/></svg>
                    Clear
                  </a>
                  <?php endif; ?>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
            <?php if(empty($rows)): ?>
            <tr class="no-data-row"><td colspan="6">🎈 No employees found.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

    </div><!-- /table-card -->

  </div><!-- /layout -->

</div><!-- /page -->

<script>
let currentFilter = 'all';

function filterBy(type, el) {
  currentFilter = type;
  document.querySelectorAll('.ftab').forEach(t => t.classList.remove('active'));
  el.classList.add('active');
  applyFilters();
}

function doSearch() { applyFilters(); }

function applyFilters() {
  const q = document.getElementById('srch').value.toLowerCase();
  document.querySelectorAll('#mainTable tbody tr:not(.no-data-row)').forEach(row => {
    const name = row.textContent.toLowerCase();
    const hasDob  = row.dataset.hasdob;
    const isToday = row.dataset.today;

    let show = name.includes(q);
    if(show && currentFilter === 'set')   show = hasDob === 'set';
    if(show && currentFilter === 'unset') show = hasDob === 'unset';
    if(show && currentFilter === 'today') show = isToday === 'yes';

    row.style.display = show ? '' : 'none';
  });
}

// Auto-scroll to form if in edit mode
<?php if($editData): ?>
document.querySelector('.form-card').scrollIntoView({behavior:'smooth', block:'start'});
<?php endif; ?>
</script>

</body>
</html>