<?php
/* Bereavement Leave Register - Modernized with Ant Design Styling */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity = 0;
ob_start();
include('includes/session.inc');
$Title = _('Bereavement Leave Register');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');

$userid = $_SESSION['UserID'];
$isAdmin = ($userid === 'admin');

// ── HANDLE ADD / DELETE ─────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['FormID']) || $_POST['FormID'] !== $_SESSION['FormID']) {
        prnMsg(_('Invalid form submission'), 'error');
        exit;
    }
    $action  = isset($_POST['actionType']) ? $_POST['actionType'] : '';
    $leaveid = isset($_POST['leaveid']) ? (int)$_POST['leaveid'] : 0;

    if ($action === 'delete') {
        if ($isAdmin) {
            DB_query(
              "DELETE FROM leave_register_bereavement_leave WHERE leaveid = '$leaveid'",
              _('Could not delete record')
            );
            prnMsg(_('Record deleted'), 'success');
        } else {
            prnMsg(_('Only admin may delete records.'), 'error');
        }
    }
    elseif ($action === 'add') {
        $periodId    = (int)$_POST['periodid'];
        $employeeId  = $_POST['employeeid'];
        $type        = $_POST['type'];
        $adjustments = (float)$_POST['adjustments'];
        $remarks     = addslashes($_POST['remarks']);

        $lastQ = DB_query(
          "SELECT balance AS last_bal
             FROM leave_register_bereavement_leave
            WHERE employeeid='$employeeId'
              AND type='$type'
            ORDER BY periodid DESC
            LIMIT 1"
        );
        $last = DB_fetch_array($lastQ);
        $opening     = $last ? (float)$last['last_bal'] : 0.0;
        $accruals    = 0.0;
        $newBalance  = $opening + $accruals + $adjustments;
        $logs        = addslashes("{$userid} added adjustment {$adjustments} on ".date('Y-m-d H:i:s'));

        DB_query("
          INSERT INTO leave_register_bereavement_leave
            (periodid,payid,employeeid,type,
             opening_balance,accruals,adjustments,
             balance,remarks,logs)
          VALUES
            ('$periodId',NULL,'$employeeId','$type',
             '$opening','$accruals','$adjustments',
             '$newBalance','$remarks','$logs')
        ", _('Could not add leave record'));
        prnMsg(_('Record added'), 'success');
    }
}

// ── KPI QUERIES ──────────────────────────────────────────────
$kpiTotal = DB_fetch_array(DB_query("SELECT COUNT(*) AS cnt FROM leave_register_bereavement_leave"));
$totalRecords = $kpiTotal ? (int)$kpiTotal['cnt'] : 0;

$kpiEmp = DB_fetch_array(DB_query("SELECT COUNT(DISTINCT employeeid) AS cnt FROM leave_register_bereavement_leave"));
$totalEmployees = $kpiEmp ? (int)$kpiEmp['cnt'] : 0;

$kpiAdj = DB_fetch_array(DB_query("SELECT COALESCE(SUM(adjustments),0) AS total FROM leave_register_bereavement_leave"));
$totalAdjustments = $kpiAdj ? number_format((float)$kpiAdj['total'], 2) : '0.00';

$kpiNeg = DB_fetch_array(DB_query("SELECT COUNT(*) AS cnt FROM leave_register_bereavement_leave WHERE balance < 0"));
$negativeBalances = $kpiNeg ? (int)$kpiNeg['cnt'] : 0;

// ── FETCH ALL ROWS ──────────────────────────────────────────
$res = DB_query("
  SELECT
    lr.leaveid,
    lr.periodid,
    COALESCE(cm.period,'N/A') AS period_label,
    lr.payid,
    lr.employeeid,
    CONCAT(em.first_name,' ',em.last_name) AS emp_name,
    lr.type,
    lr.opening_balance,
    lr.accruals,
    lr.adjustments,
    lr.balance,
    lr.remarks,
    lr.logs
  FROM leave_register_bereavement_leave lr
  LEFT JOIN calendar_management cm ON lr.periodid = cm.id
  LEFT JOIN employeemaster em     ON lr.employeeid = em.employeeid
  ORDER BY lr.periodid DESC
");

// ── FETCH PERIODS & EMPLOYEES FOR ADD FORM ──────────────────
$periods = array();
$pQ = DB_query("SELECT id,period FROM calendar_management ORDER BY id DESC");
while ($p = DB_fetch_array($pQ)) {
    $periods[] = $p;
}

$employees = array();
$eQ = DB_query("SELECT employeeid,first_name,last_name FROM employeemaster WHERE status='Active' ORDER BY first_name");
while ($emp = DB_fetch_array($eQ)) {
    $employees[] = $emp;
}
?>

<style>
/* ========== Bereavement Leave Register - Ant Design Style ========== */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

:root {
  --bl-primary: #2AABB3;
  --bl-primary-dark: #1E8F96;
  --bl-primary-darker: #187278;
  --bl-primary-light: #E6F7F8;
  --bl-success: #52C41A;
  --bl-warning: #FAAD14;
  --bl-danger: #FF4D4F;
  --bl-purple: #722ED1;
  --bl-text: #1F2937;
  --bl-text-muted: #6B7280;
  --bl-border: #E5E7EB;
  --bl-bg: #F5F7FA;
  --bl-card-bg: #FFFFFF;
  --bl-radius: 10px;
  --bl-shadow: 0 2px 8px rgba(0,0,0,0.06);
  --bl-shadow-hover: 0 4px 16px rgba(0,0,0,0.1);
}

.bl-wrapper {
  font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
  color: var(--bl-text);
  padding: 0;
}

/* ── Header Banner ─────────────────────────────── */
.bl-header {
  background: linear-gradient(135deg, #187278 0%, #1E8F96 40%, #2AABB3 100%);
  color: #fff;
  padding: 28px 32px 24px;
  border-radius: 14px 14px 0 0;
  position: relative;
  overflow: hidden;
  margin: -10px -10px 0 -10px;
}
.bl-header::before {
  content: '';
  position: absolute;
  top: -40%;
  right: -5%;
  width: 320px;
  height: 320px;
  background: radial-gradient(circle, rgba(255,255,255,0.08) 0%, transparent 70%);
  border-radius: 50%;
}
.bl-header::after {
  content: '';
  position: absolute;
  bottom: -30%;
  left: 15%;
  width: 200px;
  height: 200px;
  background: radial-gradient(circle, rgba(255,255,255,0.05) 0%, transparent 70%);
  border-radius: 50%;
}
.bl-header-content {
  position: relative;
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}
.bl-header h2 {
  margin: 0 0 4px 0;
  font-size: 22px;
  font-weight: 600;
  letter-spacing: -0.3px;
  color: #fff;
}
.bl-header p {
  margin: 0;
  font-size: 13px;
  opacity: 0.85;
}
.bl-breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  opacity: 0.75;
  margin-bottom: 12px;
}
.bl-breadcrumb a {
  color: #fff;
  text-decoration: none;
}
.bl-breadcrumb a:hover { text-decoration: underline; }
.bl-breadcrumb span { opacity: 0.6; }
.bl-date-badge {
  display: inline-block;
  background: rgba(255,255,255,0.15);
  padding: 4px 14px;
  border-radius: 20px;
  font-size: 12px;
  margin-top: 8px;
  backdrop-filter: blur(4px);
}
.bl-add-btn {
  background: rgba(255,255,255,0.2);
  color: #fff;
  border: 1.5px solid rgba(255,255,255,0.35);
  padding: 10px 22px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  font-family: 'Poppins', sans-serif;
  display: flex;
  align-items: center;
  gap: 8px;
  backdrop-filter: blur(4px);
}
.bl-add-btn:hover {
  background: rgba(255,255,255,0.3);
  transform: translateY(-1px);
}

/* ── KPI Cards ─────────────────────────────────── */
.bl-kpi-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 20px 0;
}
@media (max-width: 992px) { .bl-kpi-grid { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 576px) { .bl-kpi-grid { grid-template-columns: 1fr; } }

.bl-kpi-card {
  background: var(--bl-card-bg);
  border: 1px solid var(--bl-border);
  border-radius: var(--bl-radius);
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: var(--bl-shadow);
  transition: all 0.2s;
  border-left: 4px solid transparent;
}
.bl-kpi-card:hover {
  box-shadow: var(--bl-shadow-hover);
  transform: translateY(-2px);
}
.bl-kpi-card.kpi-primary { border-left-color: var(--bl-primary); }
.bl-kpi-card.kpi-success { border-left-color: var(--bl-success); }
.bl-kpi-card.kpi-warning { border-left-color: var(--bl-warning); }
.bl-kpi-card.kpi-danger  { border-left-color: var(--bl-danger); }

.bl-kpi-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  flex-shrink: 0;
}
.bl-kpi-icon.icon-primary { background: var(--bl-primary-light); color: var(--bl-primary); }
.bl-kpi-icon.icon-success { background: #F0FFF4; color: var(--bl-success); }
.bl-kpi-icon.icon-warning { background: #FFFBE6; color: var(--bl-warning); }
.bl-kpi-icon.icon-danger  { background: #FFF2F0; color: var(--bl-danger); }

.bl-kpi-info h3 {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: var(--bl-text);
  line-height: 1.2;
}
.bl-kpi-info p {
  margin: 2px 0 0 0;
  font-size: 12px;
  color: var(--bl-text-muted);
  font-weight: 400;
}

/* ── Add Record Form Panel ─────────────────────── */
.bl-form-panel {
  background: var(--bl-card-bg);
  border: 1.5px solid var(--bl-primary);
  border-radius: var(--bl-radius);
  margin-bottom: 20px;
  box-shadow: var(--bl-shadow);
  overflow: hidden;
  display: none;
}
.bl-form-panel.open { display: block; }

.bl-form-header {
  background: var(--bl-primary-light);
  padding: 14px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #D1ECEE;
}
.bl-form-header h4 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: var(--bl-primary-darker);
}
.bl-form-close {
  background: none;
  border: none;
  font-size: 20px;
  color: var(--bl-text-muted);
  cursor: pointer;
  padding: 0 4px;
  line-height: 1;
}
.bl-form-close:hover { color: var(--bl-danger); }

.bl-form-body {
  padding: 24px;
}
.bl-form-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}
@media (max-width: 768px) { .bl-form-grid { grid-template-columns: 1fr; } }

.bl-field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.bl-field label {
  font-size: 13px;
  font-weight: 500;
  color: var(--bl-text);
}
.bl-field label .bl-required {
  color: var(--bl-danger);
  margin-left: 2px;
}
.bl-field select,
.bl-field input,
.bl-field textarea {
  padding: 9px 12px;
  border: 1.5px solid var(--bl-border);
  border-radius: 8px;
  font-size: 13px;
  font-family: 'Poppins', sans-serif;
  color: var(--bl-text);
  background: #FAFBFC;
  outline: none;
  transition: all 0.2s;
  width: 100%;
  box-sizing: border-box;
}
.bl-field select:focus,
.bl-field input:focus,
.bl-field textarea:focus {
  border-color: var(--bl-primary);
  box-shadow: 0 0 0 3px rgba(42,171,179,0.12);
  background: #fff;
}
.bl-field input:disabled {
  background: #F3F4F6;
  color: var(--bl-text-muted);
  cursor: not-allowed;
}
.bl-field.span-2 { grid-column: span 2; }
@media (max-width: 768px) { .bl-field.span-2 { grid-column: span 1; } }

.bl-form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid var(--bl-border);
}
.bl-btn {
  padding: 9px 24px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  font-family: 'Poppins', sans-serif;
  transition: all 0.2s;
  border: 1.5px solid transparent;
}
.bl-btn-primary {
  background: var(--bl-primary);
  color: #fff;
  border-color: var(--bl-primary);
}
.bl-btn-primary:hover {
  background: var(--bl-primary-dark);
  border-color: var(--bl-primary-dark);
}
.bl-btn-cancel {
  background: #fff;
  color: var(--bl-text-muted);
  border-color: var(--bl-border);
}
.bl-btn-cancel:hover {
  background: #F9FAFB;
  color: var(--bl-text);
}

/* ── Table Panel ───────────────────────────────── */
.bl-table-panel {
  background: var(--bl-card-bg);
  border: 1px solid var(--bl-border);
  border-radius: var(--bl-radius);
  box-shadow: var(--bl-shadow);
  overflow: hidden;
}
.bl-table-toolbar {
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--bl-border);
  flex-wrap: wrap;
  gap: 12px;
}
.bl-table-toolbar h4 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: var(--bl-text);
}
.bl-toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}
.bl-search-box {
  position: relative;
}
.bl-search-box input {
  padding: 8px 12px 8px 34px;
  border: 1.5px solid var(--bl-border);
  border-radius: 8px;
  font-size: 13px;
  font-family: 'Poppins', sans-serif;
  width: 240px;
  outline: none;
  transition: all 0.2s;
  background: #FAFBFC;
}
.bl-search-box input:focus {
  border-color: var(--bl-primary);
  box-shadow: 0 0 0 3px rgba(42,171,179,0.12);
  background: #fff;
}
.bl-search-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--bl-text-muted);
  font-size: 14px;
}
.bl-export-btn {
  background: var(--bl-primary-light);
  color: var(--bl-primary-dark);
  border: 1.5px solid #B8E6EA;
  padding: 7px 16px;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  font-family: 'Poppins', sans-serif;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
}
.bl-export-btn:hover {
  background: #D1F0F3;
}

/* ── Table ─────────────────────────────────────── */
.bl-table-wrap {
  overflow-x: auto;
}
.bl-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}
.bl-table thead th {
  background: #F9FAFB;
  padding: 12px 14px;
  text-align: left;
  font-weight: 600;
  font-size: 12px;
  color: var(--bl-text-muted);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  border-bottom: 2px solid var(--bl-border);
  white-space: nowrap;
  cursor: pointer;
  user-select: none;
  position: relative;
}
.bl-table thead th:hover {
  background: #F3F4F6;
}
.bl-table thead th .sort-icon {
  margin-left: 4px;
  opacity: 0.3;
  font-size: 10px;
}
.bl-table thead th.sorted-asc .sort-icon,
.bl-table thead th.sorted-desc .sort-icon {
  opacity: 1;
  color: var(--bl-primary);
}
.bl-table tbody tr {
  border-bottom: 1px solid #F3F4F6;
  transition: background 0.15s;
}
.bl-table tbody tr:hover {
  background: #FAFCFD;
}
.bl-table tbody td {
  padding: 11px 14px;
  color: var(--bl-text);
  vertical-align: middle;
}
.bl-emp-cell {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 180px;
}
.bl-emp-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--bl-primary), var(--bl-primary-dark));
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}
.bl-emp-name {
  font-weight: 500;
  color: var(--bl-text);
  line-height: 1.3;
}
.bl-emp-id {
  font-size: 11px;
  color: var(--bl-text-muted);
}
.bl-balance-pos {
  color: var(--bl-success);
  font-weight: 600;
}
.bl-balance-neg {
  color: var(--bl-danger);
  font-weight: 600;
}
.bl-balance-zero {
  color: var(--bl-text-muted);
  font-weight: 500;
}
.bl-tag {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: 500;
}
.bl-tag-purple {
  background: #F9F0FF;
  color: var(--bl-purple);
  border: 1px solid #D3ADF7;
}
.bl-remarks-cell {
  max-width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--bl-text-muted);
  font-size: 12px;
}
.bl-logs-cell {
  max-width: 160px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--bl-text-muted);
  font-size: 11px;
}
.bl-delete-btn {
  background: #FFF2F0;
  color: var(--bl-danger);
  border: 1px solid #FFD6D6;
  padding: 5px 14px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  font-family: 'Poppins', sans-serif;
}
.bl-delete-btn:hover {
  background: var(--bl-danger);
  color: #fff;
}

/* ── Pagination ────────────────────────────────── */
.bl-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 20px;
  border-top: 1px solid var(--bl-border);
  flex-wrap: wrap;
  gap: 10px;
}
.bl-page-info {
  font-size: 13px;
  color: var(--bl-text-muted);
}
.bl-page-btns {
  display: flex;
  gap: 4px;
}
.bl-page-btn {
  min-width: 34px;
  height: 34px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--bl-border);
  border-radius: 6px;
  background: #fff;
  color: var(--bl-text);
  font-size: 13px;
  cursor: pointer;
  transition: all 0.15s;
  font-family: 'Poppins', sans-serif;
}
.bl-page-btn:hover { border-color: var(--bl-primary); color: var(--bl-primary); }
.bl-page-btn.active {
  background: var(--bl-primary);
  color: #fff;
  border-color: var(--bl-primary);
}
.bl-page-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}
.bl-per-page select {
  padding: 6px 10px;
  border: 1px solid var(--bl-border);
  border-radius: 6px;
  font-size: 13px;
  font-family: 'Poppins', sans-serif;
  outline: none;
  background: #fff;
}

/* ── Empty State ───────────────────────────────── */
.bl-empty {
  text-align: center;
  padding: 60px 20px;
  color: var(--bl-text-muted);
}
.bl-empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.4;
}
.bl-empty h4 {
  margin: 0 0 6px 0;
  font-size: 16px;
  color: var(--bl-text);
}
.bl-empty p {
  margin: 0;
  font-size: 13px;
}

/* ── Confirm Modal ─────────────────────────────── */
.bl-modal-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.45);
  z-index: 10000;
  display: none;
  align-items: center;
  justify-content: center;
}
.bl-modal-overlay.open { display: flex; }
.bl-modal {
  background: #fff;
  border-radius: 12px;
  padding: 28px;
  width: 400px;
  max-width: 90vw;
  box-shadow: 0 20px 60px rgba(0,0,0,0.2);
  text-align: center;
}
.bl-modal-icon {
  font-size: 48px;
  margin-bottom: 16px;
}
.bl-modal h4 {
  margin: 0 0 8px 0;
  font-size: 17px;
  font-weight: 600;
}
.bl-modal p {
  margin: 0 0 24px 0;
  font-size: 14px;
  color: var(--bl-text-muted);
}
.bl-modal-btns {
  display: flex;
  gap: 10px;
  justify-content: center;
}
.bl-btn-danger {
  background: var(--bl-danger);
  color: #fff;
  border-color: var(--bl-danger);
}
.bl-btn-danger:hover { background: #E8444C; }

/* ── Print styles ──────────────────────────────── */
@media print {
  @page { size: A4 landscape; margin: 10mm; }
  .bl-header, .bl-kpi-grid, .bl-form-panel, .bl-table-toolbar, .bl-pagination { display: none !important; }
  .bl-table-panel { border: none; box-shadow: none; }
  .bl-table { font-size: 10px; }
  .bl-delete-btn { display: none; }
}
</style>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"/>

<div class="bl-wrapper">

  <!-- ── Header Banner ──────────────────────── -->
  <div class="bl-header">
    <div class="bl-header-content">
      <div>
        <div class="bl-breadcrumb">
          <a href="index.php">Home</a>
          <span>›</span>
          <a href="index.php">HRM</a>
          <span>›</span>
          <span style="opacity:1">Bereavement Leave Register</span>
        </div>
        <h2><i class="fas fa-heart-broken" style="margin-right:10px;opacity:0.9"></i>Bereavement Leave Register</h2>
        <p>Track and manage bereavement leave balances for all employees</p>
        <div class="bl-date-badge">
          <i class="far fa-calendar-alt" style="margin-right:6px"></i><?php echo date('l, d M Y'); ?>
        </div>
      </div>
      <button class="bl-add-btn" onclick="toggleAddForm()">
        <i class="fas fa-plus"></i> Add Record
      </button>
    </div>
  </div>

  <!-- ── KPI Cards ──────────────────────────── -->
  <div class="bl-kpi-grid">
    <div class="bl-kpi-card kpi-primary">
      <div class="bl-kpi-icon icon-primary"><i class="fas fa-file-alt"></i></div>
      <div class="bl-kpi-info">
        <h3><?php echo $totalRecords; ?></h3>
        <p>Total Records</p>
      </div>
    </div>
    <div class="bl-kpi-card kpi-success">
      <div class="bl-kpi-icon icon-success"><i class="fas fa-users"></i></div>
      <div class="bl-kpi-info">
        <h3><?php echo $totalEmployees; ?></h3>
        <p>Employees with Records</p>
      </div>
    </div>
    <div class="bl-kpi-card kpi-warning">
      <div class="bl-kpi-icon icon-warning"><i class="fas fa-calculator"></i></div>
      <div class="bl-kpi-info">
        <h3><?php echo $totalAdjustments; ?></h3>
        <p>Total Adjustments</p>
      </div>
    </div>
    <div class="bl-kpi-card kpi-danger">
      <div class="bl-kpi-icon icon-danger"><i class="fas fa-exclamation-triangle"></i></div>
      <div class="bl-kpi-info">
        <h3><?php echo $negativeBalances; ?></h3>
        <p>Negative Balances</p>
      </div>
    </div>
  </div>

  <!-- ── Add Record Form ────────────────────── -->
  <div class="bl-form-panel" id="addFormPanel">
    <div class="bl-form-header">
      <h4><i class="fas fa-plus-circle" style="margin-right:8px;color:var(--bl-primary)"></i>Add New Bereavement Leave Record</h4>
      <button class="bl-form-close" onclick="toggleAddForm()">&times;</button>
    </div>
    <div class="bl-form-body">
      <form method="post" id="addLeaveForm">
        <input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />
        <input type="hidden" name="actionType" value="add" />

        <div class="bl-form-grid">
          <div class="bl-field">
            <label>Period <span class="bl-required">*</span></label>
            <select name="periodid" required>
              <option value="">-- Select Period --</option>
              <?php foreach ($periods as $p): ?>
                <option value="<?php echo $p['id']; ?>">#<?php echo $p['id']; ?> - <?php echo htmlspecialchars($p['period']); ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="bl-field">
            <label>Employee <span class="bl-required">*</span></label>
            <select name="employeeid" id="blEmployeeId" required onchange="blFetchOpening()">
              <option value="">-- Select Employee --</option>
              <?php foreach ($employees as $emp): ?>
                <option value="<?php echo $emp['employeeid']; ?>">#<?php echo $emp['employeeid']; ?> - <?php echo htmlspecialchars($emp['first_name'].' '.$emp['last_name']); ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="bl-field">
            <label>Type</label>
            <select name="type" id="blType" onchange="blFetchOpening()">
              <option>Bereavement Leave</option>
            </select>
          </div>

          <div class="bl-field">
            <label>Opening Balance</label>
            <input type="text" id="blOpening" value="0.00" disabled />
          </div>

          <div class="bl-field">
            <label>Accruals</label>
            <input type="text" id="blAccruals" value="0.00" disabled />
          </div>

          <div class="bl-field">
            <label>Adjustments <span class="bl-required">*</span></label>
            <input type="number" step="0.01" name="adjustments" id="blAdjustments" required oninput="blCalcBalance()" placeholder="Enter adjustment value" />
          </div>

          <div class="bl-field">
            <label>Balance</label>
            <input type="text" id="blBalance" value="0.00" disabled />
          </div>

          <div class="bl-field span-2">
            <label>Remarks</label>
            <textarea name="remarks" rows="2" placeholder="Optional remarks..."></textarea>
          </div>
        </div>

        <div class="bl-form-actions">
          <button type="button" class="bl-btn bl-btn-cancel" onclick="toggleAddForm()">Cancel</button>
          <button type="submit" class="bl-btn bl-btn-primary"><i class="fas fa-save" style="margin-right:6px"></i>Save Record</button>
        </div>
      </form>
    </div>
  </div>

  <!-- ── Table Panel ────────────────────────── -->
  <div class="bl-table-panel">
    <div class="bl-table-toolbar">
      <h4><i class="fas fa-list-alt" style="margin-right:8px;color:var(--bl-primary)"></i>Leave Records</h4>
      <div class="bl-toolbar-right">
        <div class="bl-search-box">
          <span class="bl-search-icon"><i class="fas fa-search"></i></span>
          <input type="text" id="blSearchInput" placeholder="Search records..." oninput="blFilterTable()" />
        </div>
        <button class="bl-export-btn" onclick="blExportCSV()">
          <i class="fas fa-download"></i> Export CSV
        </button>
        <div class="bl-per-page">
          <select id="blPerPage" onchange="blChangePerPage()">
            <option value="10">10 / page</option>
            <option value="25">25 / page</option>
            <option value="50">50 / page</option>
            <option value="100">100 / page</option>
          </select>
        </div>
      </div>
    </div>

    <div class="bl-table-wrap">
      <table class="bl-table" id="blTable">
        <thead>
          <tr>
            <th onclick="blSort(0)">ID <span class="sort-icon">▲▼</span></th>
            <th onclick="blSort(1)">Period <span class="sort-icon">▲▼</span></th>
            <th onclick="blSort(2)">Employee <span class="sort-icon">▲▼</span></th>
            <th onclick="blSort(3)">Type <span class="sort-icon">▲▼</span></th>
            <th onclick="blSort(4)">Opening <span class="sort-icon">▲▼</span></th>
            <th onclick="blSort(5)">Accruals <span class="sort-icon">▲▼</span></th>
            <th onclick="blSort(6)">Adjustments <span class="sort-icon">▲▼</span></th>
            <th onclick="blSort(7)">Balance <span class="sort-icon">▲▼</span></th>
            <th onclick="blSort(8)">Remarks <span class="sort-icon">▲▼</span></th>
            <th onclick="blSort(9)">Logs <span class="sort-icon">▲▼</span></th>
            <?php if ($isAdmin): ?><th>Actions</th><?php endif; ?>
          </tr>
        </thead>
        <tbody id="blTableBody">
          <?php
          $hasRows = false;
          while ($r = DB_fetch_array($res)):
            $hasRows = true;
            $bal = (float)$r['balance'];
            $balClass = ($bal > 0) ? 'bl-balance-pos' : (($bal < 0) ? 'bl-balance-neg' : 'bl-balance-zero');
            $empName = htmlspecialchars($r['emp_name']);
            $initials = '';
            $nameParts = explode(' ', trim($r['emp_name']));
            if (count($nameParts) >= 2) {
                $initials = strtoupper(substr($nameParts[0],0,1) . substr($nameParts[count($nameParts)-1],0,1));
            } else {
                $initials = strtoupper(substr($r['emp_name'],0,2));
            }
          ?>
          <tr data-leaveid="<?php echo $r['leaveid']; ?>">
            <td><strong>#<?php echo $r['leaveid']; ?></strong></td>
            <td>
              <div style="font-weight:500"><?php echo htmlspecialchars($r['period_label']); ?></div>
              <div style="font-size:11px;color:var(--bl-text-muted)">Cal #<?php echo $r['periodid']; ?><?php if($r['payid']){ echo ' · Pay #'.$r['payid']; } ?></div>
            </td>
            <td>
              <div class="bl-emp-cell">
                <div class="bl-emp-avatar"><?php echo $initials; ?></div>
                <div>
                  <div class="bl-emp-name"><?php echo $empName; ?></div>
                  <div class="bl-emp-id">#<?php echo htmlspecialchars($r['employeeid']); ?></div>
                </div>
              </div>
            </td>
            <td><span class="bl-tag bl-tag-purple"><?php echo htmlspecialchars($r['type']); ?></span></td>
            <td><?php echo number_format((float)$r['opening_balance'], 2); ?></td>
            <td><?php echo number_format((float)$r['accruals'], 2); ?></td>
            <td><?php echo number_format((float)$r['adjustments'], 2); ?></td>
            <td><span class="<?php echo $balClass; ?>"><?php echo number_format($bal, 2); ?></span></td>
            <td><div class="bl-remarks-cell" title="<?php echo htmlspecialchars($r['remarks']); ?>"><?php echo htmlspecialchars($r['remarks']); ?></div></td>
            <td><div class="bl-logs-cell" title="<?php echo htmlspecialchars($r['logs']); ?>"><?php echo htmlspecialchars($r['logs']); ?></div></td>
            <?php if ($isAdmin): ?>
            <td><button class="bl-delete-btn" onclick="blConfirmDelete(<?php echo $r['leaveid']; ?>)"><i class="fas fa-trash-alt" style="margin-right:4px"></i>Delete</button></td>
            <?php endif; ?>
          </tr>
          <?php endwhile; ?>
          <?php if (!$hasRows): ?>
          <tr class="bl-empty-row"><td colspan="<?php echo $isAdmin ? 11 : 10; ?>">
            <div class="bl-empty">
              <div class="bl-empty-icon">📋</div>
              <h4>No Records Found</h4>
              <p>Click "Add Record" to create the first bereavement leave entry.</p>
            </div>
          </td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <div class="bl-pagination" id="blPagination">
      <div class="bl-page-info" id="blPageInfo">Showing 0 records</div>
      <div class="bl-page-btns" id="blPageBtns"></div>
    </div>
  </div>

</div><!-- end bl-wrapper -->

<!-- ── Delete Confirm Modal ──────────────────── -->
<div class="bl-modal-overlay" id="blDeleteModal">
  <div class="bl-modal">
    <div class="bl-modal-icon">⚠️</div>
    <h4>Delete Record?</h4>
    <p>This action cannot be undone. Are you sure you want to delete this bereavement leave record?</p>
    <div class="bl-modal-btns">
      <button class="bl-btn bl-btn-cancel" onclick="blCloseModal()">Cancel</button>
      <button class="bl-btn bl-btn-danger" id="blConfirmDeleteBtn">
        <i class="fas fa-trash-alt" style="margin-right:6px"></i>Delete
      </button>
    </div>
  </div>
</div>

<script>
(function(){
  // ── Form Toggle ────────────────────────
  window.toggleAddForm = function() {
    var panel = document.getElementById('addFormPanel');
    panel.classList.toggle('open');
    if (panel.classList.contains('open')) {
      panel.scrollIntoView({behavior:'smooth', block:'start'});
    }
  };

  // ── Fetch Opening Balance ──────────────
  window.blFetchOpening = function() {
    var empId = document.getElementById('blEmployeeId').value;
    var type  = document.getElementById('blType').value;
    if (!empId || !type) return;

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'fetch_opening.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
      if (xhr.status === 200) {
        try {
          var d = JSON.parse(xhr.responseText);
          document.getElementById('blOpening').value  = (d.opening || 0).toFixed(2);
          document.getElementById('blAccruals').value  = (d.accruals || 0).toFixed(2);
          document.getElementById('blBalance').value   = (d.opening || 0).toFixed(2);
          blCalcBalance();
        } catch(e) {
          document.getElementById('blOpening').value = '0.00';
          document.getElementById('blAccruals').value = '0.00';
          document.getElementById('blBalance').value = '0.00';
        }
      }
    };
    xhr.send('employeeid=' + encodeURIComponent(empId) + '&type=' + encodeURIComponent(type));
  };

  // ── Calculate Balance ──────────────────
  window.blCalcBalance = function() {
    var o   = parseFloat(document.getElementById('blOpening').value) || 0;
    var a   = parseFloat(document.getElementById('blAccruals').value) || 0;
    var adj = parseFloat(document.getElementById('blAdjustments').value) || 0;
    document.getElementById('blBalance').value = (o + a + adj).toFixed(2);
  };

  // ── Delete Confirmation ────────────────
  var pendingDeleteId = null;
  window.blConfirmDelete = function(id) {
    pendingDeleteId = id;
    document.getElementById('blDeleteModal').classList.add('open');
  };
  window.blCloseModal = function() {
    document.getElementById('blDeleteModal').classList.remove('open');
    pendingDeleteId = null;
  };
  document.getElementById('blConfirmDeleteBtn').addEventListener('click', function(){
    if (!pendingDeleteId) return;
    var form = document.createElement('form');
    form.method = 'post';
    form.style.display = 'none';
    form.innerHTML = '<input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>">'
                   + '<input type="hidden" name="actionType" value="delete">'
                   + '<input type="hidden" name="leaveid" value="' + pendingDeleteId + '">';
    document.body.appendChild(form);
    form.submit();
  });

  // ── Table Search / Filter ──────────────
  var allRows = [];
  var filteredRows = [];
  var currentPage = 1;
  var perPage = 10;

  function initTable() {
    var tbody = document.getElementById('blTableBody');
    var rows = tbody.querySelectorAll('tr:not(.bl-empty-row)');
    allRows = Array.prototype.slice.call(rows);
    filteredRows = allRows.slice();
    renderPage();
  }

  window.blFilterTable = function() {
    var q = document.getElementById('blSearchInput').value.toLowerCase();
    filteredRows = allRows.filter(function(row) {
      return row.textContent.toLowerCase().indexOf(q) !== -1;
    });
    currentPage = 1;
    renderPage();
  };

  window.blChangePerPage = function() {
    perPage = parseInt(document.getElementById('blPerPage').value);
    currentPage = 1;
    renderPage();
  };

  function renderPage() {
    var tbody = document.getElementById('blTableBody');
    // Hide all
    allRows.forEach(function(r){ r.style.display = 'none'; });
    // Remove empty row
    var emptyRow = tbody.querySelector('.bl-empty-row');
    if (emptyRow) emptyRow.style.display = 'none';

    var total = filteredRows.length;
    if (total === 0) {
      if (emptyRow) emptyRow.style.display = '';
      document.getElementById('blPageInfo').textContent = 'No records found';
      document.getElementById('blPageBtns').innerHTML = '';
      return;
    }

    var totalPages = Math.ceil(total / perPage);
    if (currentPage > totalPages) currentPage = totalPages;

    var start = (currentPage - 1) * perPage;
    var end = Math.min(start + perPage, total);

    for (var i = start; i < end; i++) {
      filteredRows[i].style.display = '';
    }

    document.getElementById('blPageInfo').textContent = 'Showing ' + (start+1) + '-' + end + ' of ' + total + ' records';

    // Pagination buttons
    var html = '';
    html += '<button class="bl-page-btn" onclick="blGoPage(' + (currentPage-1) + ')" ' + (currentPage<=1?'disabled':'') + '>&laquo;</button>';
    
    var startP = Math.max(1, currentPage - 2);
    var endP = Math.min(totalPages, currentPage + 2);
    
    if (startP > 1) {
      html += '<button class="bl-page-btn" onclick="blGoPage(1)">1</button>';
      if (startP > 2) html += '<span style="padding:0 6px;color:#9CA3AF">...</span>';
    }
    for (var p = startP; p <= endP; p++) {
      html += '<button class="bl-page-btn ' + (p===currentPage?'active':'') + '" onclick="blGoPage(' + p + ')">' + p + '</button>';
    }
    if (endP < totalPages) {
      if (endP < totalPages-1) html += '<span style="padding:0 6px;color:#9CA3AF">...</span>';
      html += '<button class="bl-page-btn" onclick="blGoPage(' + totalPages + ')">' + totalPages + '</button>';
    }
    
    html += '<button class="bl-page-btn" onclick="blGoPage(' + (currentPage+1) + ')" ' + (currentPage>=totalPages?'disabled':'') + '>&raquo;</button>';
    document.getElementById('blPageBtns').innerHTML = html;
  }

  window.blGoPage = function(p) {
    var totalPages = Math.ceil(filteredRows.length / perPage);
    if (p < 1 || p > totalPages) return;
    currentPage = p;
    renderPage();
  };

  // ── Column Sort ────────────────────────
  var sortCol = -1;
  var sortAsc = true;
  window.blSort = function(col) {
    var ths = document.querySelectorAll('.bl-table thead th');
    ths.forEach(function(th){ th.classList.remove('sorted-asc','sorted-desc'); });

    if (sortCol === col) { sortAsc = !sortAsc; }
    else { sortCol = col; sortAsc = true; }

    ths[col].classList.add(sortAsc ? 'sorted-asc' : 'sorted-desc');

    filteredRows.sort(function(a,b) {
      var cellA = a.cells[col].textContent.trim().toLowerCase();
      var cellB = b.cells[col].textContent.trim().toLowerCase();
      var numA = parseFloat(cellA.replace(/[^0-9.\-]/g,''));
      var numB = parseFloat(cellB.replace(/[^0-9.\-]/g,''));

      if (!isNaN(numA) && !isNaN(numB)) {
        return sortAsc ? numA - numB : numB - numA;
      }
      if (cellA < cellB) return sortAsc ? -1 : 1;
      if (cellA > cellB) return sortAsc ? 1 : -1;
      return 0;
    });

    // Re-append sorted rows to DOM
    var tbody = document.getElementById('blTableBody');
    filteredRows.forEach(function(r){ tbody.appendChild(r); });

    currentPage = 1;
    renderPage();
  };

  // ── CSV Export ──────────────────────────
  window.blExportCSV = function() {
    var headers = ['ID','Period','Employee','Type','Opening','Accruals','Adjustments','Balance','Remarks','Logs'];
    var csv = [headers.join(',')];

    filteredRows.forEach(function(row) {
      var cells = row.querySelectorAll('td');
      var rowData = [];
      for (var i = 0; i < Math.min(cells.length, 10); i++) {
        var val = cells[i].textContent.trim().replace(/"/g,'""');
        rowData.push('"' + val + '"');
      }
      csv.push(rowData.join(','));
    });

    var blob = new Blob([csv.join('\n')], {type:'text/csv'});
    var a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'bereavement_leave_register_' + new Date().toISOString().slice(0,10) + '.csv';
    a.click();
  };

  // ── Init ───────────────────────────────
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initTable);
  } else {
    initTable();
  }
})();
</script>

<?php
echo '</div>';
?>
</div></div></div>

<!--end:: Widgets/Stats-->
<!--Begin::Section-->

<!-- end::Quick Sidebar -->
<div id="m_scroll_top" class="m-scroll-top">
  <i class="la la-arrow-up"></i>
</div>
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>
</body>
</html>
