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

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

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

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

:root {
  --al-primary: #2AABB3;
  --al-primary-dark: #1E8F96;
  --al-primary-darker: #187278;
  --al-primary-light: #E6F7F8;
  --al-accent: #13C2C2;
  --al-accent-dark: #006D75;
  --al-accent-light: #E6FFFB;
  --al-green: #52C41A;
  --al-green-dark: #389E0D;
  --al-green-light: #F6FFED;
  --al-success: #52C41A;
  --al-warning: #FAAD14;
  --al-danger: #FF4D4F;
  --al-text: #1F2937;
  --al-text-muted: #6B7280;
  --al-border: #E5E7EB;
  --al-card-bg: #FFFFFF;
  --al-radius: 10px;
  --al-shadow: 0 2px 8px rgba(0,0,0,0.06);
  --al-shadow-hover: 0 4px 16px rgba(0,0,0,0.1);
}

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

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

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

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

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

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

/* ── Add Record Form Panel ─────────────────────── */
.al-form-panel {
  background: var(--al-card-bg);
  border: 1.5px solid var(--al-primary);
  border-radius: var(--al-radius);
  margin-bottom: 20px;
  box-shadow: var(--al-shadow);
  overflow: hidden;
  display: none;
}
.al-form-panel.open { display: block; }
.al-form-header {
  background: var(--al-primary-light);
  padding: 14px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #D1ECEE;
}
.al-form-header h4 { margin: 0; font-size: 15px; font-weight: 600; color: var(--al-primary-darker); }
.al-form-close {
  background: none; border: none; font-size: 20px;
  color: var(--al-text-muted); cursor: pointer; padding: 0 4px; line-height: 1;
}
.al-form-close:hover { color: var(--al-danger); }
.al-form-body { padding: 24px; }
.al-form-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
@media (max-width: 768px) { .al-form-grid { grid-template-columns: 1fr; } }

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

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

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

/* ── Table ─────────────────────────────────────── */
.al-table-wrap { overflow-x: auto; }
.al-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.al-table thead th {
  background: #F9FAFB; padding: 12px 14px; text-align: left;
  font-weight: 600; font-size: 12px; color: var(--al-text-muted);
  text-transform: uppercase; letter-spacing: 0.5px;
  border-bottom: 2px solid var(--al-border);
  white-space: nowrap; cursor: pointer; user-select: none;
}
.al-table thead th:hover { background: #F3F4F6; }
.al-table thead th .sort-icon { margin-left: 4px; opacity: 0.3; font-size: 10px; }
.al-table thead th.sorted-asc .sort-icon,
.al-table thead th.sorted-desc .sort-icon { opacity: 1; color: var(--al-primary); }
.al-table tbody tr { border-bottom: 1px solid #F3F4F6; transition: background 0.15s; }
.al-table tbody tr:hover { background: #FAFCFD; }
.al-table tbody td { padding: 11px 14px; color: var(--al-text); vertical-align: middle; }

.al-emp-cell { display: flex; align-items: center; gap: 10px; min-width: 180px; }
.al-emp-avatar {
  width: 32px; height: 32px; border-radius: 50%;
  background: linear-gradient(135deg, var(--al-green), var(--al-green-dark));
  color: #fff; display: flex; align-items: center; justify-content: center;
  font-size: 12px; font-weight: 600; flex-shrink: 0;
}
.al-emp-name { font-weight: 500; color: var(--al-text); line-height: 1.3; }
.al-emp-id { font-size: 11px; color: var(--al-text-muted); }

.al-balance-pos { color: var(--al-success); font-weight: 600; }
.al-balance-neg { color: var(--al-danger); font-weight: 600; }
.al-balance-zero { color: var(--al-text-muted); font-weight: 500; }

.al-tag { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 500; }
.al-tag-green { background: var(--al-green-light); color: var(--al-green-dark); border: 1px solid #B7EB8F; }

.al-remarks-cell { max-width: 180px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--al-text-muted); font-size: 12px; }
.al-logs-cell { max-width: 160px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--al-text-muted); font-size: 11px; }

.al-delete-btn {
  background: #FFF2F0; color: var(--al-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;
}
.al-delete-btn:hover { background: var(--al-danger); color: #fff; }

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

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

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

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

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

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

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

        <div class="al-form-grid">
          <div class="al-field">
            <label>Period <span class="al-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="al-field">
            <label>Employee <span class="al-required">*</span></label>
            <select name="employeeid" id="alEmployeeId" required onchange="alFetchOpening()">
              <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="al-field">
            <label>Type</label>
            <select name="type" id="alType" onchange="alFetchOpening()">
              <option>Annual Leave</option>
            </select>
          </div>

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

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

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

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

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

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

  <!-- ── Table Panel ────────────────────────── -->
  <div class="al-table-panel">
    <div class="al-table-toolbar">
      <h4><i class="fas fa-list-alt" style="margin-right:8px;color:var(--al-primary)"></i>Leave Records</h4>
      <div class="al-toolbar-right">
        <div class="al-search-box">
          <span class="al-search-icon"><i class="fas fa-search"></i></span>
          <input type="text" id="alSearchInput" placeholder="Search records..." oninput="alFilterTable()" />
        </div>
        <button class="al-export-btn" onclick="alExportCSV()">
          <i class="fas fa-download"></i> Export CSV
        </button>
        <div class="al-per-page">
          <select id="alPerPage" onchange="alChangePerPage()">
            <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="al-table-wrap">
      <table class="al-table" id="alTable">
        <thead>
          <tr>
            <th onclick="alSort(0)">ID <span class="sort-icon">&#9650;&#9660;</span></th>
            <th onclick="alSort(1)">Period <span class="sort-icon">&#9650;&#9660;</span></th>
            <th onclick="alSort(2)">Employee <span class="sort-icon">&#9650;&#9660;</span></th>
            <th onclick="alSort(3)">Type <span class="sort-icon">&#9650;&#9660;</span></th>
            <th onclick="alSort(4)">Opening <span class="sort-icon">&#9650;&#9660;</span></th>
            <th onclick="alSort(5)">Accruals <span class="sort-icon">&#9650;&#9660;</span></th>
            <th onclick="alSort(6)">Adjustments <span class="sort-icon">&#9650;&#9660;</span></th>
            <th onclick="alSort(7)">Balance <span class="sort-icon">&#9650;&#9660;</span></th>
            <th onclick="alSort(8)">Remarks <span class="sort-icon">&#9650;&#9660;</span></th>
            <th onclick="alSort(9)">Logs <span class="sort-icon">&#9650;&#9660;</span></th>
            <?php if ($isAdmin): ?><th>Actions</th><?php endif; ?>
          </tr>
        </thead>
        <tbody id="alTableBody">
          <?php
          $hasRows = false;
          while ($r = DB_fetch_array($res)):
            $hasRows = true;
            $bal = (float)$r['balance'];
            $balClass = ($bal > 0) ? 'al-balance-pos' : (($bal < 0) ? 'al-balance-neg' : 'al-balance-zero');
            $empName = htmlspecialchars($r['emp_name']);
            $nameParts = explode(' ', trim($r['emp_name']));
            $initials = (count($nameParts) >= 2)
              ? strtoupper(substr($nameParts[0],0,1) . substr($nameParts[count($nameParts)-1],0,1))
              : 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(--al-text-muted)">Cal #<?php echo $r['periodid']; ?><?php if($r['payid']){ echo ' &middot; Pay #'.$r['payid']; } ?></div>
            </td>
            <td>
              <div class="al-emp-cell">
                <div class="al-emp-avatar"><?php echo $initials; ?></div>
                <div>
                  <div class="al-emp-name"><?php echo $empName; ?></div>
                  <div class="al-emp-id">#<?php echo htmlspecialchars($r['employeeid']); ?></div>
                </div>
              </div>
            </td>
            <td><span class="al-tag al-tag-green"><?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="al-remarks-cell" title="<?php echo htmlspecialchars($r['remarks']); ?>"><?php echo htmlspecialchars($r['remarks']); ?></div></td>
            <td><div class="al-logs-cell" title="<?php echo htmlspecialchars($r['logs']); ?>"><?php echo htmlspecialchars($r['logs']); ?></div></td>
            <?php if ($isAdmin): ?>
            <td><button class="al-delete-btn" onclick="alConfirmDelete(<?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="al-empty-row"><td colspan="<?php echo $isAdmin ? 11 : 10; ?>">
            <div class="al-empty">
              <div class="al-empty-icon">🌴</div>
              <h4>No Records Found</h4>
              <p>Click "Add Record" to create the first annual leave entry.</p>
            </div>
          </td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <div class="al-pagination" id="alPagination">
      <div class="al-page-info" id="alPageInfo">Showing 0 records</div>
      <div class="al-page-btns" id="alPageBtns"></div>
    </div>
  </div>

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

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

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

  /* ── Fetch Opening Balance ────────────── */
  window.alFetchOpening = function() {
    var empId = document.getElementById('alEmployeeId').value;
    var type  = document.getElementById('alType').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('alOpening').value  = (d.opening||0).toFixed(2);
          document.getElementById('alAccruals').value  = (d.accruals||0).toFixed(2);
          document.getElementById('alBalance').value   = (d.opening||0).toFixed(2);
          alCalcBalance();
        } catch(e) {
          document.getElementById('alOpening').value='0.00';
          document.getElementById('alAccruals').value='0.00';
          document.getElementById('alBalance').value='0.00';
        }
      }
    };
    xhr.send('employeeid='+encodeURIComponent(empId)+'&type='+encodeURIComponent(type));
  };

  /* ── Calc Balance ─────────────────────── */
  window.alCalcBalance = function() {
    var o = parseFloat(document.getElementById('alOpening').value)||0;
    var a = parseFloat(document.getElementById('alAccruals').value)||0;
    var adj = parseFloat(document.getElementById('alAdjustments').value)||0;
    document.getElementById('alBalance').value = (o+a+adj).toFixed(2);
  };

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

  /* ── Table: Search / Pagination / Sort ── */
  var alAll=[],alFiltered=[],alPage=1,alPP=10;

  function alInit(){
    var rows=document.getElementById('alTableBody').querySelectorAll('tr:not(.al-empty-row)');
    alAll=Array.prototype.slice.call(rows);
    alFiltered=alAll.slice();
    alRender();
  }

  window.alFilterTable = function(){
    var q=document.getElementById('alSearchInput').value.toLowerCase();
    alFiltered=alAll.filter(function(r){return r.textContent.toLowerCase().indexOf(q)!==-1;});
    alPage=1; alRender();
  };

  window.alChangePerPage = function(){ alPP=parseInt(document.getElementById('alPerPage').value); alPage=1; alRender(); };

  function alRender(){
    alAll.forEach(function(r){r.style.display='none';});
    var er=document.getElementById('alTableBody').querySelector('.al-empty-row');
    if(er) er.style.display='none';
    var t=alFiltered.length;
    if(t===0){ if(er) er.style.display=''; document.getElementById('alPageInfo').textContent='No records found'; document.getElementById('alPageBtns').innerHTML=''; return; }
    var tp=Math.ceil(t/alPP); if(alPage>tp) alPage=tp;
    var s=(alPage-1)*alPP, e=Math.min(s+alPP,t);
    for(var i=s;i<e;i++) alFiltered[i].style.display='';
    document.getElementById('alPageInfo').textContent='Showing '+(s+1)+'-'+e+' of '+t+' records';

    var h='';
    h+='<button class="al-page-btn" onclick="alGoPage('+(alPage-1)+')" '+(alPage<=1?'disabled':'')+'>&#171;</button>';
    var sp=Math.max(1,alPage-2),ep=Math.min(tp,alPage+2);
    if(sp>1){h+='<button class="al-page-btn" onclick="alGoPage(1)">1</button>';if(sp>2)h+='<span style="padding:0 6px;color:#9CA3AF">...</span>';}
    for(var p=sp;p<=ep;p++) h+='<button class="al-page-btn '+(p===alPage?'active':'')+'" onclick="alGoPage('+p+')">'+p+'</button>';
    if(ep<tp){if(ep<tp-1)h+='<span style="padding:0 6px;color:#9CA3AF">...</span>';h+='<button class="al-page-btn" onclick="alGoPage('+tp+')">'+tp+'</button>';}
    h+='<button class="al-page-btn" onclick="alGoPage('+(alPage+1)+')" '+(alPage>=tp?'disabled':'')+'>&#187;</button>';
    document.getElementById('alPageBtns').innerHTML=h;
  }

  window.alGoPage = function(p){ var tp=Math.ceil(alFiltered.length/alPP); if(p<1||p>tp)return; alPage=p; alRender(); };

  /* ── Sort ──────────────────────────────── */
  var alSC=-1,alSA=true;
  window.alSort = function(col){
    var ths=document.querySelectorAll('.al-table thead th');
    ths.forEach(function(th){th.classList.remove('sorted-asc','sorted-desc');});
    if(alSC===col){alSA=!alSA;}else{alSC=col;alSA=true;}
    ths[col].classList.add(alSA?'sorted-asc':'sorted-desc');
    alFiltered.sort(function(a,b){
      var cA=a.cells[col].textContent.trim().toLowerCase(),cB=b.cells[col].textContent.trim().toLowerCase();
      var nA=parseFloat(cA.replace(/[^0-9.\-]/g,'')),nB=parseFloat(cB.replace(/[^0-9.\-]/g,''));
      if(!isNaN(nA)&&!isNaN(nB)) return alSA?nA-nB:nB-nA;
      if(cA<cB)return alSA?-1:1; if(cA>cB)return alSA?1:-1; return 0;
    });
    var tb=document.getElementById('alTableBody');
    alFiltered.forEach(function(r){tb.appendChild(r);});
    alPage=1; alRender();
  };

  /* ── CSV Export ────────────────────────── */
  window.alExportCSV = function(){
    var hd=['ID','Period','Employee','Type','Opening','Accruals','Adjustments','Balance','Remarks','Logs'];
    var csv=[hd.join(',')];
    alFiltered.forEach(function(row){
      var cells=row.querySelectorAll('td'),rd=[];
      for(var i=0;i<Math.min(cells.length,10);i++){var v=cells[i].textContent.trim().replace(/"/g,'""');rd.push('"'+v+'"');}
      csv.push(rd.join(','));
    });
    var b=new Blob([csv.join('\n')],{type:'text/csv'});
    var a=document.createElement('a'); a.href=URL.createObjectURL(b);
    a.download='annual_leave_register_'+new Date().toISOString().slice(0,10)+'.csv'; a.click();
  };

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