<?php
/* Sick Leave Register - Modernized with Ant Design Styling */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity = 0;
ob_start();
include('includes/session.inc');
$Title = _('Sick 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_sick_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_sick_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_sick_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_sick_leave"));
$totalRecords = $kpiTotal ? (int)$kpiTotal['cnt'] : 0;

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

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

$kpiNeg = DB_fetch_array(DB_query("SELECT COUNT(*) AS cnt FROM leave_register_sick_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_sick_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>
/* ========== Sick Leave Register - Ant Design Style ========== */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

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

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

/* ── Header Banner ─────────────────────────────── */
.sl-header {
  background: linear-gradient(135deg, var(--sl-primary-darker) 0%, var(--sl-primary-dark) 40%, var(--sl-primary) 100%);
  color: #fff;
  padding: 28px 32px 24px;
  border-radius: 14px 14px 0 0;
  position: relative;
  overflow: hidden;
  margin: -10px -10px 0 -10px;
}
.sl-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%;
}
.sl-header::after {
  content: '';
  position: absolute;
  bottom: -30%;
  left: 15%;
  width: 200px;
  height: 200px;
  background: radial-gradient(circle, rgba(250,140,22,0.12) 0%, transparent 70%);
  border-radius: 50%;
}
.sl-header-content {
  position: relative;
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}
.sl-header h2 {
  margin: 0 0 4px 0;
  font-size: 22px;
  font-weight: 600;
  letter-spacing: -0.3px;
  color: #fff;
}
.sl-header p {
  margin: 0;
  font-size: 13px;
  opacity: 0.85;
}
.sl-breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  opacity: 0.75;
  margin-bottom: 12px;
}
.sl-breadcrumb a { color: #fff; text-decoration: none; }
.sl-breadcrumb a:hover { text-decoration: underline; }
.sl-breadcrumb span { opacity: 0.6; }
.sl-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);
}
.sl-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);
}
.sl-add-btn:hover {
  background: rgba(255,255,255,0.3);
  transform: translateY(-1px);
}

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

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

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

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

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

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

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

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

.sl-form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid var(--sl-border);
}
.sl-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;
}
.sl-btn-primary {
  background: var(--sl-primary);
  color: #fff;
  border-color: var(--sl-primary);
}
.sl-btn-primary:hover {
  background: var(--sl-primary-dark);
  border-color: var(--sl-primary-dark);
}
.sl-btn-cancel {
  background: #fff;
  color: var(--sl-text-muted);
  border-color: var(--sl-border);
}
.sl-btn-cancel:hover {
  background: #F9FAFB;
  color: var(--sl-text);
}

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

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

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

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

/* ── Confirm Modal ─────────────────────────────── */
.sl-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;
}
.sl-modal-overlay.open { display: flex; }
.sl-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;
}
.sl-modal-icon { font-size: 48px; margin-bottom: 16px; }
.sl-modal h4 { margin: 0 0 8px 0; font-size: 17px; font-weight: 600; }
.sl-modal p { margin: 0 0 24px 0; font-size: 14px; color: var(--sl-text-muted); }
.sl-modal-btns { display: flex; gap: 10px; justify-content: center; }
.sl-btn-danger {
  background: var(--sl-danger);
  color: #fff;
  border-color: var(--sl-danger);
}
.sl-btn-danger:hover { background: #E8444C; }

/* ── Print styles ──────────────────────────────── */
@media print {
  @page { size: A4 landscape; margin: 10mm; }
  .sl-header, .sl-kpi-grid, .sl-form-panel, .sl-table-toolbar, .sl-pagination { display: none !important; }
  .sl-table-panel { border: none; box-shadow: none; }
  .sl-table { font-size: 10px; }
  .sl-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="sl-wrapper">

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

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

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

        <div class="sl-form-grid">
          <div class="sl-field">
            <label>Period <span class="sl-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="sl-field">
            <label>Employee <span class="sl-required">*</span></label>
            <select name="employeeid" id="slEmployeeId" required onchange="slFetchOpening()">
              <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="sl-field">
            <label>Type</label>
            <select name="type" id="slType" onchange="slFetchOpening()">
              <option>Sick Leave</option>
            </select>
          </div>

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

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

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

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

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

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

  <!-- ── Table Panel ────────────────────────── -->
  <div class="sl-table-panel">
    <div class="sl-table-toolbar">
      <h4><i class="fas fa-list-alt" style="margin-right:8px;color:var(--sl-primary)"></i>Leave Records</h4>
      <div class="sl-toolbar-right">
        <div class="sl-search-box">
          <span class="sl-search-icon"><i class="fas fa-search"></i></span>
          <input type="text" id="slSearchInput" placeholder="Search records..." oninput="slFilterTable()" />
        </div>
        <button class="sl-export-btn" onclick="slExportCSV()">
          <i class="fas fa-download"></i> Export CSV
        </button>
        <div class="sl-per-page">
          <select id="slPerPage" onchange="slChangePerPage()">
            <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="sl-table-wrap">
      <table class="sl-table" id="slTable">
        <thead>
          <tr>
            <th onclick="slSort(0)">ID <span class="sort-icon">▲▼</span></th>
            <th onclick="slSort(1)">Period <span class="sort-icon">▲▼</span></th>
            <th onclick="slSort(2)">Employee <span class="sort-icon">▲▼</span></th>
            <th onclick="slSort(3)">Type <span class="sort-icon">▲▼</span></th>
            <th onclick="slSort(4)">Opening <span class="sort-icon">▲▼</span></th>
            <th onclick="slSort(5)">Accruals <span class="sort-icon">▲▼</span></th>
            <th onclick="slSort(6)">Adjustments <span class="sort-icon">▲▼</span></th>
            <th onclick="slSort(7)">Balance <span class="sort-icon">▲▼</span></th>
            <th onclick="slSort(8)">Remarks <span class="sort-icon">▲▼</span></th>
            <th onclick="slSort(9)">Logs <span class="sort-icon">▲▼</span></th>
            <?php if ($isAdmin): ?><th>Actions</th><?php endif; ?>
          </tr>
        </thead>
        <tbody id="slTableBody">
          <?php
          $hasRows = false;
          while ($r = DB_fetch_array($res)):
            $hasRows = true;
            $bal = (float)$r['balance'];
            $balClass = ($bal > 0) ? 'sl-balance-pos' : (($bal < 0) ? 'sl-balance-neg' : 'sl-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(--sl-text-muted)">Cal #<?php echo $r['periodid']; ?><?php if($r['payid']){ echo ' &middot; Pay #'.$r['payid']; } ?></div>
            </td>
            <td>
              <div class="sl-emp-cell">
                <div class="sl-emp-avatar"><?php echo $initials; ?></div>
                <div>
                  <div class="sl-emp-name"><?php echo $empName; ?></div>
                  <div class="sl-emp-id">#<?php echo htmlspecialchars($r['employeeid']); ?></div>
                </div>
              </div>
            </td>
            <td><span class="sl-tag sl-tag-orange"><?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="sl-remarks-cell" title="<?php echo htmlspecialchars($r['remarks']); ?>"><?php echo htmlspecialchars($r['remarks']); ?></div></td>
            <td><div class="sl-logs-cell" title="<?php echo htmlspecialchars($r['logs']); ?>"><?php echo htmlspecialchars($r['logs']); ?></div></td>
            <?php if ($isAdmin): ?>
            <td><button class="sl-delete-btn" onclick="slConfirmDelete(<?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="sl-empty-row"><td colspan="<?php echo $isAdmin ? 11 : 10; ?>">
            <div class="sl-empty">
              <div class="sl-empty-icon">🏥</div>
              <h4>No Records Found</h4>
              <p>Click "Add Record" to create the first sick leave entry.</p>
            </div>
          </td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <div class="sl-pagination" id="slPagination">
      <div class="sl-page-info" id="slPageInfo">Showing 0 records</div>
      <div class="sl-page-btns" id="slPageBtns"></div>
    </div>
  </div>

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

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

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

  // ── Fetch Opening Balance ──────────────
  window.slFetchOpening = function() {
    var empId = document.getElementById('slEmployeeId').value;
    var type  = document.getElementById('slType').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('slOpening').value  = (d.opening || 0).toFixed(2);
          document.getElementById('slAccruals').value  = (d.accruals || 0).toFixed(2);
          document.getElementById('slBalance').value   = (d.opening || 0).toFixed(2);
          slCalcBalance();
        } catch(e) {
          document.getElementById('slOpening').value = '0.00';
          document.getElementById('slAccruals').value = '0.00';
          document.getElementById('slBalance').value = '0.00';
        }
      }
    };
    xhr.send('employeeid=' + encodeURIComponent(empId) + '&type=' + encodeURIComponent(type));
  };

  // ── Calculate Balance ──────────────────
  window.slCalcBalance = function() {
    var o   = parseFloat(document.getElementById('slOpening').value) || 0;
    var a   = parseFloat(document.getElementById('slAccruals').value) || 0;
    var adj = parseFloat(document.getElementById('slAdjustments').value) || 0;
    document.getElementById('slBalance').value = (o + a + adj).toFixed(2);
  };

  // ── Delete Confirmation ────────────────
  var slPendingDeleteId = null;
  window.slConfirmDelete = function(id) {
    slPendingDeleteId = id;
    document.getElementById('slDeleteModal').classList.add('open');
  };
  window.slCloseModal = function() {
    document.getElementById('slDeleteModal').classList.remove('open');
    slPendingDeleteId = null;
  };
  document.getElementById('slConfirmDeleteBtn').addEventListener('click', function(){
    if (!slPendingDeleteId) 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="' + slPendingDeleteId + '">';
    document.body.appendChild(form);
    form.submit();
  });

  // ── Table Search / Filter / Pagination ─
  var slAllRows = [];
  var slFilteredRows = [];
  var slCurrentPage = 1;
  var slPerPage = 10;

  function slInitTable() {
    var tbody = document.getElementById('slTableBody');
    var rows = tbody.querySelectorAll('tr:not(.sl-empty-row)');
    slAllRows = Array.prototype.slice.call(rows);
    slFilteredRows = slAllRows.slice();
    slRenderPage();
  }

  window.slFilterTable = function() {
    var q = document.getElementById('slSearchInput').value.toLowerCase();
    slFilteredRows = slAllRows.filter(function(row) {
      return row.textContent.toLowerCase().indexOf(q) !== -1;
    });
    slCurrentPage = 1;
    slRenderPage();
  };

  window.slChangePerPage = function() {
    slPerPage = parseInt(document.getElementById('slPerPage').value);
    slCurrentPage = 1;
    slRenderPage();
  };

  function slRenderPage() {
    var tbody = document.getElementById('slTableBody');
    slAllRows.forEach(function(r){ r.style.display = 'none'; });
    var emptyRow = tbody.querySelector('.sl-empty-row');
    if (emptyRow) emptyRow.style.display = 'none';

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

    var totalPages = Math.ceil(total / slPerPage);
    if (slCurrentPage > totalPages) slCurrentPage = totalPages;

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

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

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

    var html = '';
    html += '<button class="sl-page-btn" onclick="slGoPage(' + (slCurrentPage-1) + ')" ' + (slCurrentPage<=1?'disabled':'') + '>&laquo;</button>';
    var startP = Math.max(1, slCurrentPage - 2);
    var endP = Math.min(totalPages, slCurrentPage + 2);
    if (startP > 1) {
      html += '<button class="sl-page-btn" onclick="slGoPage(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="sl-page-btn ' + (p===slCurrentPage?'active':'') + '" onclick="slGoPage(' + p + ')">' + p + '</button>';
    }
    if (endP < totalPages) {
      if (endP < totalPages-1) html += '<span style="padding:0 6px;color:#9CA3AF">...</span>';
      html += '<button class="sl-page-btn" onclick="slGoPage(' + totalPages + ')">' + totalPages + '</button>';
    }
    html += '<button class="sl-page-btn" onclick="slGoPage(' + (slCurrentPage+1) + ')" ' + (slCurrentPage>=totalPages?'disabled':'') + '>&raquo;</button>';
    document.getElementById('slPageBtns').innerHTML = html;
  }

  window.slGoPage = function(p) {
    var totalPages = Math.ceil(slFilteredRows.length / slPerPage);
    if (p < 1 || p > totalPages) return;
    slCurrentPage = p;
    slRenderPage();
  };

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

    if (slSortCol === col) { slSortAsc = !slSortAsc; }
    else { slSortCol = col; slSortAsc = true; }

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

    slFilteredRows.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 slSortAsc ? numA - numB : numB - numA;
      }
      if (cellA < cellB) return slSortAsc ? -1 : 1;
      if (cellA > cellB) return slSortAsc ? 1 : -1;
      return 0;
    });

    var tbody = document.getElementById('slTableBody');
    slFilteredRows.forEach(function(r){ tbody.appendChild(r); });

    slCurrentPage = 1;
    slRenderPage();
  };

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

    slFilteredRows.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 = 'sick_leave_register_' + new Date().toISOString().slice(0,10) + '.csv';
    a.click();
  };

  // ── Init ───────────────────────────────
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', slInitTable);
  } else {
    slInitTable();
  }
})();
</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>