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

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

if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    $_SESSION['error'] = "Please log in to continue.";
    header("Location: index.php");
    exit();
}

$user_sql = "SELECT id, username, role FROM users WHERE id = ?";
$stmt = $conn->prepare($user_sql);
$stmt->bind_param("s", $_SESSION['user_id']);
$stmt->execute();
$user_result = $stmt->get_result();

if ($user_result->num_rows === 0) {
    unset($_SESSION['user_id']);
    header("Location: index.php");
    exit();
}

$user             = $user_result->fetch_assoc();
$employee_id      = $user['id'];
$user_role        = strtolower(trim($user['role']));
$stmt->close();

$is_admin         = in_array($user_role, ['admin', 'superadmin']);
$username_session = $_SESSION['username'] ?? $user['username'] ?? 'Admin';

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

/* 汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽
   FETCH DISTINCT LOCATIONS FROM USERS TABLE
汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽 */
$locations_list = ['All'];
$loc_res = $conn->query("SELECT DISTINCT location FROM users WHERE location IS NOT NULL AND location != '' ORDER BY location ASC");
if ($loc_res) {
    while ($lr = $loc_res->fetch_assoc()) {
        if (!in_array($lr['location'], $locations_list)) $locations_list[] = $lr['location'];
    }
}

/* 汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽
   POST HANDLERS
汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $is_admin) {
    $action = $_POST['action'] ?? '';

    if ($action === 'add_holiday') {
        $holiday_date = trim($_POST['holiday_date'] ?? '');
        $name         = trim($_POST['name']         ?? '');
        $location     = trim($_POST['location']     ?? 'All');
        $is_optional  = isset($_POST['is_optional']) ? 1 : 0;

        if ($holiday_date === '' || $name === '') {
            $_SESSION['error'] = "Please fill in Holiday Date and Name.";
        } else {
            $stmt = $conn->prepare("INSERT INTO company_holidays (holiday_date, name, location, is_optional) VALUES (?, ?, ?, ?)");
            if ($stmt) {
                $stmt->bind_param("sssi", $holiday_date, $name, $location, $is_optional);
                if ($stmt->execute()) {
                    $_SESSION['message'] = "Holiday added successfully.";
                } else {
                    $_SESSION['error'] = "Failed to add holiday: " . $stmt->error;
                }
                $stmt->close();
            }
        }
        header("Location: company_holidays.php"); exit();
    }

    if ($action === 'update_holiday') {
        $id           = (int)($_POST['id']          ?? 0);
        $holiday_date = trim($_POST['holiday_date'] ?? '');
        $name         = trim($_POST['name']         ?? '');
        $location     = trim($_POST['location']     ?? 'All');
        $is_optional  = isset($_POST['is_optional']) ? 1 : 0;

        if ($id <= 0 || $holiday_date === '' || $name === '') {
            $_SESSION['error'] = "Invalid data for update.";
        } else {
            $stmt = $conn->prepare("UPDATE company_holidays SET holiday_date=?, name=?, location=?, is_optional=? WHERE id=?");
            if ($stmt) {
                $stmt->bind_param("sssii", $holiday_date, $name, $location, $is_optional, $id);
                if ($stmt->execute()) {
                    $_SESSION['message'] = "Holiday updated successfully.";
                } else {
                    $_SESSION['error'] = "Failed to update: " . $stmt->error;
                }
                $stmt->close();
            }
        }
        header("Location: company_holidays.php"); exit();
    }

    if ($action === 'delete_holiday') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $stmt = $conn->prepare("DELETE FROM company_holidays WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param("i", $id);
                if ($stmt->execute()) {
                    $_SESSION['message'] = "Holiday deleted.";
                } else {
                    $_SESSION['error'] = "Failed to delete.";
                }
                $stmt->close();
            }
        }
        header("Location: company_holidays.php"); exit();
    }
}

/* 汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽
   EDIT MODE
汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽 */
$edit_holiday = null;
if ($is_admin && isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    if ($edit_id > 0) {
        $stmt = $conn->prepare("SELECT * FROM company_holidays WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param("i", $edit_id);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($res && $res->num_rows > 0) $edit_holiday = $res->fetch_assoc();
            $stmt->close();
        }
    }
}

/* 汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽
   FETCH ALL HOLIDAYS
汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽汽 */
$holidays = [];
$list_res = $conn->query("SELECT * FROM company_holidays ORDER BY holiday_date ASC");
if ($list_res && $list_res->num_rows > 0) {
    while ($row = $list_res->fetch_assoc()) $holidays[] = $row;
}

// Summary stats
$stats = ['total' => count($holidays), 'mandatory' => 0, 'optional' => 0];
foreach ($holidays as $hol) {
    if ($hol['is_optional']) $stats['optional']++; else $stats['mandatory']++;
}

// Distinct years for filter
$years = array_unique(array_map(fn($h) => date('Y', strtotime($h['holiday_date'])), $holidays));
rsort($years);
?>
<!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 ﹞ Company Holidays</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&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;
  --radius: 12px; --shadow: 0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  --blue: #3b82f6; --green: #10b981; --amber: #f59e0b; --red: #ef4444;
  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; }
.brand-name { font-size: 15px; font-weight: 700; color: #fff; }
.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-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 岸岸 */
.content { flex: 1; margin-left: var(--sidebar-w); min-width: 0; display: flex; flex-direction: column; transition: margin .3s cubic-bezier(.4,0,.2,1); }
.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; display: flex; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
.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; }

/* 岸岸 ALERTS 岸岸 */
.alert { padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 500; display: flex; align-items: flex-start; gap: 10px; margin-bottom: 20px; border: 1px solid transparent; animation: fadeUp .25s ease; }
.alert-success { background: #d1fae5; border-color: #6ee7b7; color: #065f46; }
.alert-danger   { background: #fee2e2; border-color: #fca5a5; color: #991b1b; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }

/* 岸岸 STAT CARDS 岸岸 */
.stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 14px; margin-bottom: 20px; }
.stat-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px 20px; display: flex; align-items: center; gap: 14px; box-shadow: var(--shadow); }
.stat-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; }
.stat-val  { font-size: 22px; font-weight: 700; color: var(--ink); line-height: 1; }
.stat-lbl  { font-size: 11px; color: var(--muted); margin-top: 2px; text-transform: uppercase; letter-spacing: .5px; }

/* 岸岸 CARD 岸岸 */
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; margin-bottom: 20px; }
.card-header { display: flex; align-items: center; gap: 8px; padding: 16px 20px; border-bottom: 1px solid var(--border); flex-wrap: wrap; }
.card-title { font-size: 15px; font-weight: 700; color: var(--ink); }
.card-header-actions { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
.card-body { padding: 24px; }

/* 岸岸 FORM 岸岸 */
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px; align-items: end; }
.form-group { display: flex; flex-direction: column; gap: 5px; }
.form-label { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .8px; color: var(--muted); }
.form-control, .form-select {
  height: 40px; border: 1.5px solid var(--border); border-radius: 8px;
  padding: 0 12px; font-size: 13px; font-family: 'Sora', sans-serif;
  color: var(--ink); background: var(--bg); outline: none;
  transition: border-color .15s, box-shadow .15s; width: 100%;
}
.form-control:focus, .form-select:focus { border-color: var(--blue); box-shadow: 0 0 0 3px rgba(59,130,246,.12); background: var(--surface); }
.form-select { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' 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: 34px; cursor: pointer; }
.checkbox-group { display: flex; align-items: center; gap: 8px; height: 40px; }
.checkbox-group input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--blue); cursor: pointer; }

/* 岸岸 FILTER BAR 岸岸 */
.filter-bar { display: flex; align-items: flex-end; gap: 10px; padding: 14px 20px; background: #f8fafc; border-bottom: 1px solid var(--border); flex-wrap: wrap; }
.filter-bar .ff { display: flex; flex-direction: column; gap: 4px; }
.filter-bar .ff label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .8px; color: var(--muted); }
.filter-bar select,
.filter-bar input[type="text"] {
  height: 36px; border: 1.5px solid var(--border); border-radius: 8px;
  padding: 0 10px; font-size: 12px; font-family: 'Sora', sans-serif;
  color: var(--ink); background: var(--surface); outline: none; min-width: 120px;
  transition: border-color .15s;
}
.filter-bar select:focus, .filter-bar input:focus { border-color: var(--blue); }
.filter-bar select { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2.5'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 8px center; padding-right: 26px; cursor: pointer; }
.filter-search { position: relative; }
.filter-search svg { position: absolute; left: 9px; top: 50%; transform: translateY(-50%); color: var(--muted); pointer-events: none; }
.filter-search input { padding-left: 28px; min-width: 180px; }
.btn-clear-f { height: 36px; padding: 0 14px; border-radius: 8px; border: 1.5px solid var(--border); background: var(--surface); color: var(--muted); font-size: 12px; cursor: pointer; font-family: 'Sora', sans-serif; display: inline-flex; align-items: center; gap: 5px; transition: border-color .15s, color .15s; }
.btn-clear-f:hover { border-color: #adb5c5; color: var(--ink); }

/* 岸岸 BUTTONS 岸岸 */
.btn { display: inline-flex; align-items: center; gap: 6px; padding: 9px 16px; border-radius: 8px; border: none; font-size: 13px; font-weight: 600; font-family: 'Sora', sans-serif; cursor: pointer; transition: opacity .15s, transform .1s; text-decoration: none; white-space: nowrap; }
.btn:hover { opacity: .88; transform: translateY(-1px); }
.btn-primary   { background: #1d4ed8; color: #fff; }
.btn-secondary { background: var(--bg); border: 1.5px solid var(--border); color: var(--ink-2); }
.btn-warning   { background: #d97706; color: #fff; }
.btn-danger    { background: #dc2626; color: #fff; }
.btn-sm { padding: 5px 11px; font-size: 12px; border-radius: 6px; }
.btn-group { display: flex; gap: 6px; justify-content: center; }

/* 岸岸 TABLE 岸岸 */
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
thead th { background: #f8fafc; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: .6px; color: var(--muted); padding: 10px 14px; border-bottom: 1px solid var(--border); white-space: nowrap; }
thead th:last-child { text-align: center; }
tbody td { padding: 12px 14px; border-bottom: 1px solid var(--border); color: var(--ink-2); vertical-align: middle; }
tbody tr:last-child td { border-bottom: none; }
tbody tr:hover { background: #f8fafc; }
.no-rows td { text-align: center; padding: 48px 14px; color: var(--muted); }

/* 岸岸 BADGES 岸岸 */
.badge { display: inline-flex; align-items: center; gap: 4px; padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; white-space: nowrap; }
.badge-optional  { background: #fef3c7; color: #92400e; }
.badge-mandatory { background: #d1fae5; color: #065f46; }
.badge-loc       { background: #e0f2fe; color: #075985; }
.badge-all       { background: #f1f5f9; color: #475569; }

/* 岸岸 MODAL 岸岸 */
.modal-overlay { position: fixed; inset: 0; background: rgba(15,23,42,.45); z-index: 500; display: none; align-items: center; justify-content: center; padding: 16px; }
.modal-overlay.open { display: flex; animation: fadeIn .2s ease; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.modal { background: var(--surface); border-radius: 14px; box-shadow: 0 20px 60px rgba(15,23,42,.2); width: 100%; max-width: 520px; animation: slideUp .2s ease; }
@keyframes slideUp { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: none; } }
.modal-header { padding: 20px 24px 16px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; }
.modal-title { font-size: 16px; font-weight: 700; color: var(--ink); display: flex; align-items: center; gap: 8px; }
.modal-close { width: 30px; height: 30px; border-radius: 7px; border: none; background: var(--bg); color: var(--muted); cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 14px; transition: background .15s; }
.modal-close:hover { background: var(--border); color: var(--ink); }
.modal-body { padding: 24px; }
.modal-footer { padding: 16px 24px; border-top: 1px solid var(--border); display: flex; gap: 8px; justify-content: flex-end; }
.modal-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.modal-grid .span-2 { grid-column: 1 / -1; }

@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 16px; }
  .stat-grid { grid-template-columns: 1fr 1fr; }
  .modal-grid { grid-template-columns: 1fr; }
  .modal-grid .span-2 { grid-column: 1; }
}
</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">
        <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>
      <li class="nav-item">
        <button class="nav-dropdown-toggle open" onclick="toggleMenu(this)"><i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu open">
          <li><a href="attendance.php"              class="nav-link"><i class="fas fa-clock"></i>             Attendance Dashboard</a></li>
          <li><a href="payroll.php"                 class="nav-link"><i class="fas fa-money-bill"></i>        Payroll Dashboard</a></li>
          <li><a href="task_dashboard.php"          class="nav-link"><i class="fas fa-tasks"></i>            Task Dashboard</a></li>
          <li><a href="daily_reports_dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>       Daily Report Dashboard</a></li>
          <li><a href="ot_dashboard.php"            class="nav-link"><i class="fas fa-hourglass-half"></i>   OT Dashboard</a></li>
          <li><a href="company_holidays.php"        class="nav-link active"><i class="fas fa-star"></i>      Company Holidays</a></li>
          <li><a href="hr_approval_salary.php"      class="nav-link"><i class="fas fa-hand-holding-usd"></i> Advance Dashboard</a></li>
          <li><a href="expense_dashboard.php"       class="nav-link"><i class="fas fa-receipt"></i>          Expenses Dashboard</a></li>
          <li><a href="leave_dashboard.php"         class="nav-link"><i class="fas fa-umbrella-beach"></i>   Leave Dashboard</a></li>
          <li><a href="grievance_dashboard.php"     class="nav-link"><i class="fas fa-comment-alt"></i>      Grievance Dashboard</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="individual_rr.php"     class="nav-link"><i class="fas fa-trophy"></i>   Individual R &amp; R</a></li>
          <li><a href="individual_kpi.php"    class="nav-link"><i class="fas fa-bullseye"></i> Individual KPI</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>  Login Credentials</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="incident_employee.php"  class="nav-link"><i class="fas fa-exclamation-triangle"></i> Incident Portal</a></li>
          <li><a href="training_dashboard.php" class="nav-link"><i class="fas fa-chalkboard-teacher"></i>   Training Portal</a></li>
          <li><a href="rr.php"                 class="nav-link"><i class="fas fa-award"></i>                Rewards &amp; Recognition</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="employee_tiy.php"      class="nav-link"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>    Login Credentials</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>CAB</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Company Holidays</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($username_session ?: 'A', 0, 1)) ?></div>
      <?= h($username_session) ?>
    </div>
  </div>

  <div class="page">

    <div class="page-header">
      <div>
        <div class="page-title">Company Holidays</div>
        <div class="page-subtitle">Manage and view the company-wide holiday calendar</div>
      </div>
      <?php if ($is_admin): ?>
      <button class="btn btn-primary" onclick="openAddModal()">
        <i class="fas fa-plus"></i> Add Holiday
      </button>
      <?php endif; ?>
    </div>

    <?php if (isset($_SESSION['message'])): ?>
      <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= h($_SESSION['message']) ?><?php unset($_SESSION['message']); ?></div>
    <?php endif; ?>
    <?php if (isset($_SESSION['error'])): ?>
      <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= h($_SESSION['error']) ?><?php unset($_SESSION['error']); ?></div>
    <?php endif; ?>

    <!-- STAT CARDS -->
    <div class="stat-grid">
      <div class="stat-card">
        <div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><i class="fas fa-calendar-check"></i></div>
        <div><div class="stat-val"><?= $stats['total'] ?></div><div class="stat-lbl">Total Holidays</div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background:#d1fae5;color:#059669;"><i class="fas fa-star"></i></div>
        <div><div class="stat-val"><?= $stats['mandatory'] ?></div><div class="stat-lbl">Mandatory</div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background:#fef3c7;color:#d97706;"><i class="fas fa-flag"></i></div>
        <div><div class="stat-val"><?= $stats['optional'] ?></div><div class="stat-lbl">Optional</div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background:#f0fdf4;color:#16a34a;"><i class="fas fa-map-marker-alt"></i></div>
        <div><div class="stat-val"><?= count(array_filter($locations_list, fn($l) => $l !== 'All')) ?></div><div class="stat-lbl">Locations</div></div>
      </div>
    </div>

    <!-- EDIT CARD (shown only when ?edit= is set) -->
    <?php if ($is_admin && $edit_holiday): ?>
    <div class="card" id="editCard">
      <div class="card-header">
        <i class="fas fa-edit" style="color:var(--blue)"></i>
        <div class="card-title">Edit Holiday</div>
        <div class="card-header-actions">
          <a href="company_holidays.php" class="btn btn-secondary btn-sm">
            <i class="fas fa-times"></i> Cancel
          </a>
        </div>
      </div>
      <div class="card-body">
        <form method="POST">
          <input type="hidden" name="action" value="update_holiday">
          <input type="hidden" name="id" value="<?= (int)$edit_holiday['id'] ?>">
          <div class="form-grid">
            <div class="form-group">
              <label class="form-label">Holiday Date *</label>
              <input type="date" name="holiday_date" class="form-control" required
                     value="<?= h($edit_holiday['holiday_date']) ?>">
            </div>
            <div class="form-group">
              <label class="form-label">Holiday Name *</label>
              <input type="text" name="name" class="form-control" required
                     value="<?= h($edit_holiday['name']) ?>">
            </div>
            <div class="form-group">
              <label class="form-label">Location</label>
              <select name="location" class="form-select">
                <?php
                $edit_loc = $edit_holiday['location'] ?? 'All';
                foreach ($locations_list as $loc) {
                    $sel = ($edit_loc === $loc) ? 'selected' : '';
                    echo '<option value="'.h($loc).'" '.$sel.'>'.h($loc).'</option>';
                }
                ?>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">Type</label>
              <div class="checkbox-group">
                <input type="checkbox" name="is_optional" id="is_optional_edit"
                       <?= $edit_holiday['is_optional'] ? 'checked' : '' ?>>
                <label for="is_optional_edit" style="font-size:13px;color:var(--ink-2);">Optional Holiday</label>
              </div>
            </div>
            <div class="form-group" style="display:flex;gap:8px;align-items:flex-end;">
              <button type="submit" class="btn btn-primary">
                <i class="fas fa-save"></i> Update Holiday
              </button>
              <a href="company_holidays.php" class="btn btn-secondary">Cancel</a>
            </div>
          </div>
        </form>
      </div>
    </div>
    <?php endif; ?>

    <!-- HOLIDAY TABLE CARD -->
    <div class="card">
      <div class="card-header">
        <i class="fas fa-calendar-alt" style="color:var(--muted)"></i>
        <div class="card-title">
          Holiday List
          <span style="color:var(--muted);font-weight:400;font-size:13px;margin-left:6px;" id="visibleCount">
            (<?= count($holidays) ?> holiday<?= count($holidays) !== 1 ? 's' : '' ?>)
          </span>
        </div>
      </div>

      <!-- FILTER BAR -->
      <div class="filter-bar">
        <div class="ff filter-search">
          <label>Search</label>
          <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="fSearch" placeholder="Holiday name, location＃" oninput="applyFilters()">
        </div>
        <div class="ff">
          <label>Location</label>
          <select id="fLocation" onchange="applyFilters()">
            <option value="">All Locations</option>
            <?php foreach ($locations_list as $lc): if ($lc === 'All') continue; ?>
            <option value="<?= h(strtolower($lc)) ?>"><?= h($lc) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="ff">
          <label>Type</label>
          <select id="fType" onchange="applyFilters()">
            <option value="">All Types</option>
            <option value="mandatory">Mandatory</option>
            <option value="optional">Optional</option>
          </select>
        </div>
        <div class="ff">
          <label>Year</label>
          <select id="fYear" onchange="applyFilters()">
            <option value="">All Years</option>
            <?php foreach ($years as $yr): ?>
            <option value="<?= $yr ?>"><?= $yr ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="ff">
          <label>Month</label>
          <select id="fMonth" onchange="applyFilters()">
            <option value="">All Months</option>
            <?php for ($m = 1; $m <= 12; $m++): ?>
            <option value="<?= str_pad($m, 2, '0', STR_PAD_LEFT) ?>"><?= date('F', mktime(0,0,0,$m,1)) ?></option>
            <?php endfor; ?>
          </select>
        </div>
        <div class="ff" style="margin-left:auto;">
          <label>&nbsp;</label>
          <button class="btn-clear-f" onclick="clearFilters()" type="button">
            <i class="fas fa-times"></i> Clear
          </button>
        </div>
      </div>

      <!-- TABLE -->
      <div class="table-wrap">
        <table id="holidayTable">
          <thead>
            <tr>
              <th>#</th>
              <th>Date</th>
              <th>Holiday Name</th>
              <th>Location</th>
              <th>Type</th>
              <?php if ($is_admin): ?><th>Actions</th><?php endif; ?>
            </tr>
          </thead>
          <tbody id="holidayTbody">
            <?php if (!empty($holidays)): ?>
              <?php foreach ($holidays as $idx => $hol): ?>
              <tr
                data-location="<?= h(strtolower($hol['location'] ?? '')) ?>"
                data-type="<?= $hol['is_optional'] ? 'optional' : 'mandatory' ?>"
                data-name="<?= h(strtolower($hol['name'])) ?>"
                data-year="<?= date('Y', strtotime($hol['holiday_date'])) ?>"
                data-month="<?= date('m', strtotime($hol['holiday_date'])) ?>"
              >
                <td style="color:var(--muted);font-size:11px;font-weight:600;"><?= $idx + 1 ?></td>
                <td style="font-weight:600;white-space:nowrap;">
                  <div><?= date('d M Y', strtotime($hol['holiday_date'])) ?></div>
                  <div style="font-size:11px;color:var(--muted);font-weight:400;"><?= date('l', strtotime($hol['holiday_date'])) ?></div>
                </td>
                <td style="font-weight:500;"><?= h($hol['name']) ?></td>
                <td>
                  <?php $loc = $hol['location'] ?? 'All'; ?>
                  <span class="badge <?= $loc === 'All' ? 'badge-all' : 'badge-loc' ?>">
                    <i class="fas fa-map-marker-alt" style="font-size:9px;"></i>
                    <?= h($loc) ?>
                  </span>
                </td>
                <td>
                  <span class="badge <?= $hol['is_optional'] ? 'badge-optional' : 'badge-mandatory' ?>">
                    <?= $hol['is_optional'] ? 'Optional' : 'Mandatory' ?>
                  </span>
                </td>
                <?php if ($is_admin): ?>
                <td>
                  <div class="btn-group">
                    <a href="company_holidays.php?edit=<?= (int)$hol['id'] ?>" class="btn btn-warning btn-sm">
                      <i class="fas fa-edit"></i> Edit
                    </a>
                    <form method="POST" onsubmit="return confirm('Delete this holiday?');" style="display:inline;">
                      <input type="hidden" name="action" value="delete_holiday">
                      <input type="hidden" name="id"     value="<?= (int)$hol['id'] ?>">
                      <button type="submit" class="btn btn-danger btn-sm">
                        <i class="fas fa-trash"></i>
                      </button>
                    </form>
                  </div>
                </td>
                <?php endif; ?>
              </tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr class="no-rows">
                <td colspan="<?= $is_admin ? 6 : 5 ?>">
                  <i class="fas fa-calendar-times" style="font-size:32px;display:block;margin-bottom:8px;opacity:.4;"></i>
                  No holidays added yet.
                </td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div><!-- /card -->

  </div><!-- /page -->
</div><!-- /content -->
</div><!-- /layout -->

<!-- 汽汽汽汽汽汽汽汽汽汽汽 ADD HOLIDAY MODAL 汽汽汽汽汽汽汽汽汽汽汽 -->
<?php if ($is_admin): ?>
<div class="modal-overlay" id="addModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title">
        <i class="fas fa-plus-circle" style="color:var(--blue);"></i>
        Add New Holiday
      </div>
      <button class="modal-close" onclick="closeAddModal()" type="button"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="add_holiday">
      <div class="modal-body">
        <div class="modal-grid">
          <div class="form-group span-2">
            <label class="form-label">Holiday Name *</label>
            <input type="text" name="name" class="form-control" required placeholder="e.g. Republic Day">
          </div>
          <div class="form-group">
            <label class="form-label">Holiday Date *</label>
            <input type="date" name="holiday_date" class="form-control" required>
          </div>
          <div class="form-group">
            <label class="form-label">Location</label>
            <select name="location" class="form-select">
              <?php foreach ($locations_list as $loc): ?>
              <option value="<?= h($loc) ?>"><?= h($loc) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group span-2">
            <label class="form-label">Type</label>
            <div class="checkbox-group">
              <input type="checkbox" name="is_optional" id="is_optional_add">
              <label for="is_optional_add" style="font-size:13px;color:var(--ink-2);">Optional Holiday</label>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" onclick="closeAddModal()">Cancel</button>
        <button type="submit" class="btn btn-primary"><i class="fas fa-plus"></i> Add Holiday</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<script>
/* 岸岸 SIDEBAR 岸岸 */
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');
}

/* 岸岸 MODAL 岸岸 */
function openAddModal()  { document.getElementById('addModal')?.classList.add('open'); }
function closeAddModal() { document.getElementById('addModal')?.classList.remove('open'); }
document.getElementById('addModal')?.addEventListener('click', function(e) {
  if (e.target === this) closeAddModal();
});

/* 岸岸 FILTERS 岸岸 */
function applyFilters() {
  const search   = document.getElementById('fSearch').value.trim().toLowerCase();
  const location = document.getElementById('fLocation').value;
  const type     = document.getElementById('fType').value;
  const year     = document.getElementById('fYear').value;
  const month    = document.getElementById('fMonth').value;

  const rows = document.querySelectorAll('#holidayTbody tr:not(.no-rows)');
  let visible  = 0;

  rows.forEach(row => {
    const loc = row.dataset.location || '';
    const typ = row.dataset.type     || '';
    const nm  = row.dataset.name     || '';
    const yr  = row.dataset.year     || '';
    const mo  = row.dataset.month    || '';

    const locOk   = !location || loc === location;
    const typeOk  = !type     || typ === type;
    const yearOk  = !year     || yr  === year;
    const monthOk = !month    || mo  === month;
    const srchOk  = !search   || nm.includes(search) || loc.includes(search);

    const show = locOk && typeOk && yearOk && monthOk && srchOk;
    row.style.display = show ? '' : 'none';
    if (show) visible++;
  });

  const vc = document.getElementById('visibleCount');
  if (vc) vc.textContent = `(${visible} holiday${visible !== 1 ? 's' : ''})`;

  const noRow = document.querySelector('#holidayTbody .no-rows');
  if (noRow) noRow.style.display = (visible === 0 && rows.length > 0) ? '' : 'none';
}

function clearFilters() {
  ['fSearch', 'fLocation', 'fType', 'fYear', 'fMonth'].forEach(id => {
    const el = document.getElementById(id);
    if (!el) return;
    if (el.tagName === 'SELECT') el.selectedIndex = 0; else el.value = '';
  });
  applyFilters();
}

document.addEventListener('DOMContentLoaded', applyFilters);

<?php if ($edit_holiday): ?>
document.getElementById('editCard')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
<?php endif; ?>
</script>
</body>
</html>
<?php $conn->close(); ?>