<?php
require_once __DIR__ . '/Includes.php';

$sessionRole = (string)($_SESSION['role'] ?? '');
$isAdminReadOnlyView = $sessionRole === 'admin' && (string)($_GET['admin_view'] ?? '') === '1';
if ($sessionRole === 'admin' && !$isAdminReadOnlyView) {
  header('Location: admin.php');
  exit;
}
check_login(['ancillary', 'admin']);

$pdo->exec("CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(150) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  role ENUM('admin', 'teacher', 'hop', 'accountant', 'ancillary', 'parent') NOT NULL DEFAULT 'teacher',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

try {
  $pdo->exec("ALTER TABLE users MODIFY role ENUM('admin', 'teacher', 'hop', 'accountant', 'ancillary', 'parent') NOT NULL DEFAULT 'teacher'");
} catch (PDOException $e) {
  // Ignore when schema is already updated.
}

$pdo->exec("CREATE TABLE IF NOT EXISTS staff_profiles (
  user_id INT NOT NULL PRIMARY KEY,
  sex ENUM('Male','Female','Other') NULL,
  date_of_birth DATE NULL,
  ec_number VARCHAR(80) NULL,
  national_id VARCHAR(80) NULL,
  work_profile VARCHAR(255) NULL,
  qualifications TEXT NULL,
  subject_specialization VARCHAR(255) NULL,
  updated_by INT NULL,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_staff_profiles_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_staff_profiles_updated_by FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS ancillary_leave_requests (
  id INT AUTO_INCREMENT PRIMARY KEY,
  ancillary_id INT NOT NULL,
  leave_type VARCHAR(60) NOT NULL,
  start_date DATE NOT NULL,
  end_date DATE NOT NULL,
  reason TEXT NOT NULL,
  supporting_document_path VARCHAR(255) NULL,
  supporting_document_name VARCHAR(255) NULL,
  supporting_document_mime VARCHAR(120) NULL,
  supporting_document_size BIGINT NULL,
  status ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  admin_comment TEXT NULL,
  reviewed_by INT NULL,
  reviewed_at DATETIME NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_alr_ancillary FOREIGN KEY (ancillary_id) REFERENCES users(id) ON DELETE CASCADE,
  INDEX idx_alr_ancillary (ancillary_id),
  INDEX idx_alr_status (status)
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS ancillary_salary_register (
  id INT AUTO_INCREMENT PRIMARY KEY,
  ancillary_id INT NOT NULL,
  salary_month CHAR(7) NOT NULL,
  base_salary DECIMAL(12,2) NOT NULL DEFAULT 0,
  allowance_amount DECIMAL(12,2) NOT NULL DEFAULT 0,
  deduction_amount DECIMAL(12,2) NOT NULL DEFAULT 0,
  net_salary DECIMAL(12,2) NOT NULL DEFAULT 0,
  pay_date DATE NULL,
  note VARCHAR(255) NULL,
  recorded_by INT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_asr_ancillary FOREIGN KEY (ancillary_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_asr_recorded_by FOREIGN KEY (recorded_by) REFERENCES users(id) ON DELETE SET NULL,
  UNIQUE KEY uq_asr_worker_month (ancillary_id, salary_month),
  INDEX idx_asr_month (salary_month)
)");

$defaultSchoolName = 'MAVELA GOVERNMENT HIGH SCHOOL';
$defaultSchoolAddress = 'P.O.Box 12 Tsholotsho';
$defaultSchoolContact = 'Phone: +263 77 000 0000 | Email: admin@mavelahigh.org';
$defaultSchoolMotto = 'Imfundo Yinsika Yesizwe';
$defaultSchoolLogoPath = 'Uploads/Mavela_Logo.png';

$schoolName = trim(get_app_setting($pdo, 'school_name', $defaultSchoolName));
$schoolAddress = trim(get_app_setting($pdo, 'school_address', $defaultSchoolAddress));
$schoolContact = trim(get_app_setting($pdo, 'school_contact', $defaultSchoolContact));
$schoolMotto = trim(get_app_setting($pdo, 'school_motto', $defaultSchoolMotto));
$schoolLogoPath = trim(get_app_setting($pdo, 'school_logo_path', $defaultSchoolLogoPath));

if ($schoolName === '') {
  $schoolName = $defaultSchoolName;
}
if ($schoolAddress === '') {
  $schoolAddress = $defaultSchoolAddress;
}
if ($schoolContact === '') {
  $schoolContact = $defaultSchoolContact;
}
if ($schoolMotto === '') {
  $schoolMotto = $defaultSchoolMotto;
}
if ($schoolLogoPath === '') {
  $schoolLogoPath = $defaultSchoolLogoPath;
}

$themePalette = get_school_theme_palette($pdo);
$paletteBgCream = (string)($themePalette['bg_cream'] ?? '#f7fbf7');
$paletteBgSand = (string)($themePalette['bg_sand'] ?? '#e5f0e6');
$paletteInk = (string)($themePalette['ink'] ?? '#173122');
$paletteMuted = (string)($themePalette['muted'] ?? '#4f6656');
$paletteBrandNavy = (string)($themePalette['brand_navy'] ?? '#2e8b45');
$paletteBrandNavyDeep = (string)($themePalette['brand_navy_deep'] ?? '#1d6a33');
$paletteBrandGold = (string)($themePalette['brand_gold'] ?? '#1e1a1b');
$paletteBrandIce = (string)($themePalette['brand_ice'] ?? '#eef7ef');
$palettePatchSkySoft = (string)($themePalette['patch_sky_soft'] ?? '#dff2ff');

$resolvedSchoolLogoPath = $schoolLogoPath;
$resolvedSchoolLogoAbsolute = $resolvedSchoolLogoPath !== '' ? (__DIR__ . '/' . ltrim($resolvedSchoolLogoPath, '/\\')) : '';
if ($resolvedSchoolLogoPath === '' || !is_file($resolvedSchoolLogoAbsolute)) {
  $fallbackAbsolute = __DIR__ . '/' . ltrim($defaultSchoolLogoPath, '/\\');
  if (is_file($fallbackAbsolute)) {
    $resolvedSchoolLogoPath = $defaultSchoolLogoPath;
    $resolvedSchoolLogoAbsolute = $fallbackAbsolute;
  }
}

$alerts = [];
$activeUserId = (int)($_SESSION['user_id'] ?? 0);
$activeAncillaryId = $activeUserId;

if ($isAdminReadOnlyView) {
  $previewAncillaryId = (int)($_GET['ancillary_user_id'] ?? 0);
  if ($previewAncillaryId > 0) {
    $activeAncillaryId = $previewAncillaryId;
  }
}

$ancillaryProfileStmt = $pdo->prepare("SELECT u.id, u.name, u.email, u.password_hash, u.role,
    sp.sex, sp.date_of_birth, sp.ec_number, sp.national_id, sp.work_profile, sp.qualifications,
    sp.updated_at AS profile_updated_at
  FROM users u
  LEFT JOIN staff_profiles sp ON sp.user_id = u.id
  WHERE u.id = ? AND u.role = 'ancillary'
  LIMIT 1");
$ancillaryProfileStmt->execute([$activeAncillaryId]);
$ancillaryProfile = $ancillaryProfileStmt->fetch();

if (!$ancillaryProfile) {
  if ($isAdminReadOnlyView) {
    $alerts[] = ['type' => 'error', 'text' => 'No ancillary staff profile found for preview.'];
  } else {
    logout_user();
    header('Location: index.php');
    exit;
  }
}

if ($isAdminReadOnlyView && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
  $_POST = [];
  $_FILES = [];
  $alerts[] = ['type' => 'error', 'text' => 'Admin view is read-only. Changes are not allowed in ancillary staff desk preview mode.'];
}

if ($isAdminReadOnlyView) {
  $alerts[] = ['type' => 'success', 'text' => 'Admin read-only preview mode is active for ancillary staff desk.'];
}

$forcePasswordChange = !$isAdminReadOnlyView
  && is_array($ancillaryProfile)
  && !empty($_SESSION['must_change_password']);

if ($forcePasswordChange) {
  $alerts[] = ['type' => 'error', 'text' => 'First login security step: change your temporary password before using the desk.'];
}

if (!$isAdminReadOnlyView && $ancillaryProfile) {
  if ($forcePasswordChange && !isset($_POST['change_ancillary_password'])) {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
      $alerts[] = ['type' => 'error', 'text' => 'Please change your temporary password first.'];
    }
    $_POST = [];
    $_FILES = [];
  }

  if (isset($_POST['save_ancillary_profile'])) {
    $profileName = trim((string)($_POST['profile_name'] ?? ''));
    $profileEmail = trim((string)($_POST['profile_email'] ?? ''));
    $profileSex = trim((string)($_POST['profile_sex'] ?? ''));
    $profileDob = trim((string)($_POST['profile_dob'] ?? ''));
    $profileEc = trim((string)($_POST['profile_ec_number'] ?? ''));
    $profileNationalId = trim((string)($_POST['profile_national_id'] ?? ''));
    $profileWork = trim((string)($_POST['profile_work_profile'] ?? ''));
    $profileQualifications = trim((string)($_POST['profile_qualifications'] ?? ''));
    $allowedSex = ['Male', 'Female', 'Other'];

    if ($profileName === '' || $profileEmail === '') {
      $alerts[] = ['type' => 'error', 'text' => 'Profile name and email are required.'];
    } elseif (!filter_var($profileEmail, FILTER_VALIDATE_EMAIL)) {
      $alerts[] = ['type' => 'error', 'text' => 'Please provide a valid email address.'];
    } elseif ($profileSex !== '' && !in_array($profileSex, $allowedSex, true)) {
      $alerts[] = ['type' => 'error', 'text' => 'Invalid sex value selected.'];
    } elseif ($profileDob !== '' && !preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $profileDob)) {
      $alerts[] = ['type' => 'error', 'text' => 'Date of birth must use YYYY-MM-DD format.'];
    } else {
      $emailExistsStmt = $pdo->prepare("SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id <> ? LIMIT 1");
      $emailExistsStmt->execute([$profileEmail, $activeAncillaryId]);

      if ($emailExistsStmt->fetch()) {
        $alerts[] = ['type' => 'error', 'text' => 'That email is already used by another account.'];
      } else {
        try {
          $pdo->beginTransaction();

          $updateUserStmt = $pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ? AND role = 'ancillary' LIMIT 1");
          $updateUserStmt->execute([$profileName, $profileEmail, $activeAncillaryId]);

          $upsertProfileStmt = $pdo->prepare("INSERT INTO staff_profiles
            (user_id, sex, date_of_birth, ec_number, national_id, work_profile, qualifications, subject_specialization, updated_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?)
            ON DUPLICATE KEY UPDATE
              sex = VALUES(sex),
              date_of_birth = VALUES(date_of_birth),
              ec_number = VALUES(ec_number),
              national_id = VALUES(national_id),
              work_profile = VALUES(work_profile),
              qualifications = VALUES(qualifications),
              updated_by = VALUES(updated_by)");
          $upsertProfileStmt->execute([
            $activeAncillaryId,
            $profileSex === '' ? null : $profileSex,
            $profileDob === '' ? null : $profileDob,
            $profileEc === '' ? null : $profileEc,
            $profileNationalId === '' ? null : $profileNationalId,
            $profileWork === '' ? null : $profileWork,
            $profileQualifications === '' ? null : $profileQualifications,
            $activeAncillaryId
          ]);

          $pdo->commit();
          $_SESSION['name'] = $profileName;
          $alerts[] = ['type' => 'success', 'text' => 'Profile details saved successfully.'];

          $ancillaryProfileStmt->execute([$activeAncillaryId]);
          $ancillaryProfile = $ancillaryProfileStmt->fetch();
        } catch (Throwable $e) {
          if ($pdo->inTransaction()) {
            $pdo->rollBack();
          }
          $alerts[] = ['type' => 'error', 'text' => 'Could not save profile details: ' . mavela_exception_detail($e)];
        }
      }
    }
  }

  if (isset($_POST['change_ancillary_password'])) {
    $currentPassword = (string)($_POST['current_password'] ?? '');
    $newPassword = (string)($_POST['new_password'] ?? '');
    $confirmPassword = (string)($_POST['confirm_password'] ?? '');

    if ($currentPassword === '' || $newPassword === '' || $confirmPassword === '') {
      $alerts[] = ['type' => 'error', 'text' => 'Current password, new password, and confirmation are required.'];
    } elseif (!password_verify($currentPassword, (string)$ancillaryProfile['password_hash'])) {
      $alerts[] = ['type' => 'error', 'text' => 'Current password is incorrect.'];
    } elseif (!mavela_password_is_strong($newPassword)) {
      $alerts[] = ['type' => 'error', 'text' => 'Use at least 10 characters with uppercase, lowercase, and a number.'];
    } elseif ($newPassword !== $confirmPassword) {
      $alerts[] = ['type' => 'error', 'text' => 'New password and confirmation do not match.'];
    } else {
      $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
      $updatePasswordStmt = $pdo->prepare("UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ? AND role = 'ancillary' LIMIT 1");
      $updatePasswordStmt->execute([$newHash, $activeAncillaryId]);
      $_SESSION['must_change_password'] = false;
      $ancillaryProfile['password_hash'] = $newHash;
      $forcePasswordChange = false;
      $alerts[] = ['type' => 'success', 'text' => 'Password changed successfully.'];
    }
  }

  if (isset($_POST['submit_ancillary_leave_request'])) {
    $leaveType = trim((string)($_POST['leave_type'] ?? ''));
    $startDate = trim((string)($_POST['leave_start_date'] ?? ''));
    $endDate = trim((string)($_POST['leave_end_date'] ?? ''));
    $leaveReason = trim((string)($_POST['leave_reason'] ?? ''));
    $allowedLeaveTypes = ['sick', 'annual', 'maternity', 'compassionate', 'unpaid', 'other'];

    if (!in_array($leaveType, $allowedLeaveTypes, true)) {
      $alerts[] = ['type' => 'error', 'text' => 'Please choose a valid leave type.'];
    } elseif ($startDate === '' || $endDate === '') {
      $alerts[] = ['type' => 'error', 'text' => 'Leave start and end dates are required.'];
    } elseif ($leaveReason === '') {
      $alerts[] = ['type' => 'error', 'text' => 'Please provide a reason for leave.'];
    } elseif ($endDate < $startDate) {
      $alerts[] = ['type' => 'error', 'text' => 'Leave end date cannot be earlier than start date.'];
    } else {
      $documentError = (int)($_FILES['leave_document']['error'] ?? UPLOAD_ERR_NO_FILE);
      $documentPath = null;
      $documentName = null;
      $documentMime = null;
      $documentSize = null;

      if ($documentError === UPLOAD_ERR_NO_FILE) {
        $alerts[] = ['type' => 'error', 'text' => 'Please attach your leave form document (PDF or image).'];
      } elseif ($documentError !== UPLOAD_ERR_OK) {
        $alerts[] = ['type' => 'error', 'text' => 'Leave form upload failed. Please retry.'];
      } else {
        $docOriginalName = (string)($_FILES['leave_document']['name'] ?? '');
        $docTmpName = (string)($_FILES['leave_document']['tmp_name'] ?? '');
        $docSize = (int)($_FILES['leave_document']['size'] ?? 0);
        $docExt = strtolower(pathinfo($docOriginalName, PATHINFO_EXTENSION));
        $allowedDocExt = ['pdf', 'jpg', 'jpeg', 'png', 'webp'];

        if ($docOriginalName === '' || $docTmpName === '') {
          $alerts[] = ['type' => 'error', 'text' => 'Invalid leave form payload.'];
        } elseif ($docSize <= 0 || $docSize > 10 * 1024 * 1024) {
          $alerts[] = ['type' => 'error', 'text' => 'Leave form must be between 1 byte and 10 MB.'];
        } elseif (!in_array($docExt, $allowedDocExt, true)) {
          $alerts[] = ['type' => 'error', 'text' => 'Leave form must be PDF, JPG, PNG, or WEBP.'];
        } else {
          $finfo = finfo_open(FILEINFO_MIME_TYPE);
          $docMime = $finfo ? (string)finfo_file($finfo, $docTmpName) : '';
          if ($finfo) {
            finfo_close($finfo);
          }

          $allowedMime = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'];
          if ($docMime !== '' && !in_array($docMime, $allowedMime, true)) {
            $alerts[] = ['type' => 'error', 'text' => 'Uploaded leave form is not a valid PDF or image file.'];
          } else {
            $uploadDir = __DIR__ . '/Uploads/leave_forms';
            if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true)) {
              $alerts[] = ['type' => 'error', 'text' => 'Could not prepare leave forms upload folder.'];
            } else {
              $baseName = preg_replace('/[^A-Za-z0-9._-]/', '_', pathinfo($docOriginalName, PATHINFO_FILENAME));
              $baseName = trim((string)$baseName, '._-');
              if ($baseName === '') {
                $baseName = 'leave_form';
              }
              $docFileName = 'leave_form_ancillary_' . date('Ymd_His') . '_' . bin2hex(random_bytes(3)) . '_' . $baseName . '.' . $docExt;
              $destPath = $uploadDir . '/' . $docFileName;

              if (!move_uploaded_file($docTmpName, $destPath)) {
                $alerts[] = ['type' => 'error', 'text' => 'Could not save uploaded leave form document.'];
              } else {
                $documentPath = 'Uploads/leave_forms/' . $docFileName;
                $documentName = $docOriginalName;
                $documentMime = $docMime === '' ? null : $docMime;
                $documentSize = $docSize;
              }
            }
          }
        }
      }

      if (empty($alerts)) {
        $insertStmt = $pdo->prepare("INSERT INTO ancillary_leave_requests
          (ancillary_id, leave_type, start_date, end_date, reason, supporting_document_path, supporting_document_name, supporting_document_mime, supporting_document_size, status)
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')");
        $insertStmt->execute([
          $activeAncillaryId,
          $leaveType,
          $startDate,
          $endDate,
          $leaveReason,
          $documentPath,
          $documentName,
          $documentMime,
          $documentSize
        ]);
        $alerts[] = ['type' => 'success', 'text' => 'Leave request submitted to admin desk for approval.'];
      }
    }
  }
}

$mySalaryRows = [];
$myLeaveRequests = [];
if ($ancillaryProfile) {
  $salaryStmt = $pdo->prepare("SELECT asr.id, asr.salary_month, asr.base_salary, asr.allowance_amount,
      asr.deduction_amount, asr.net_salary, asr.pay_date, asr.note, asr.updated_at,
      rb.name AS recorded_by_name
    FROM ancillary_salary_register asr
    LEFT JOIN users rb ON rb.id = asr.recorded_by
    WHERE asr.ancillary_id = ?
    ORDER BY asr.salary_month DESC, asr.updated_at DESC");
  $salaryStmt->execute([(int)$ancillaryProfile['id']]);
  $mySalaryRows = $salaryStmt->fetchAll();

  $leaveStmt = $pdo->prepare("SELECT alr.id, alr.leave_type, alr.start_date, alr.end_date, alr.reason,
      alr.supporting_document_path, alr.supporting_document_name,
      alr.status, alr.admin_comment, alr.reviewed_at, alr.created_at
    FROM ancillary_leave_requests alr
    WHERE alr.ancillary_id = ?
    ORDER BY FIELD(alr.status, 'pending', 'approved', 'rejected'), alr.created_at DESC");
  $leaveStmt->execute([(int)$ancillaryProfile['id']]);
  $myLeaveRequests = $leaveStmt->fetchAll();
}

$payslipId = (int)($_GET['payslip_id'] ?? 0);
$activePayslip = null;
if ($payslipId > 0 && !empty($mySalaryRows)) {
  foreach ($mySalaryRows as $salaryRow) {
    if ((int)$salaryRow['id'] === $payslipId) {
      $activePayslip = $salaryRow;
      break;
    }
  }
}
if ($activePayslip === null && !empty($mySalaryRows)) {
  $activePayslip = $mySalaryRows[0];
}

$totalNetSalary = 0.0;
foreach ($mySalaryRows as $salaryRow) {
  $totalNetSalary += (float)$salaryRow['net_salary'];
}

$printableStaffName = (string)($ancillaryProfile['name'] ?? 'Ancillary Staff');
$activePayslipMonth = is_array($activePayslip) ? (string)($activePayslip['salary_month'] ?? date('Y-m')) : date('Y-m');
$activePayslipId = is_array($activePayslip) ? (int)($activePayslip['id'] ?? 0) : 0;
$activePayslipBase = is_array($activePayslip) ? (float)($activePayslip['base_salary'] ?? 0) : 0.0;
$activePayslipAllowance = is_array($activePayslip) ? (float)($activePayslip['allowance_amount'] ?? 0) : 0.0;
$activePayslipDeduction = is_array($activePayslip) ? (float)($activePayslip['deduction_amount'] ?? 0) : 0.0;
$activePayslipGross = $activePayslipBase + $activePayslipAllowance;
$activePayslipNet = is_array($activePayslip) ? (float)($activePayslip['net_salary'] ?? 0) : 0.0;
$activePayslipPayDate = is_array($activePayslip) ? trim((string)($activePayslip['pay_date'] ?? '')) : '';
$activePayslipNote = is_array($activePayslip) ? trim((string)($activePayslip['note'] ?? '')) : '';
$activePayslipRecordedBy = is_array($activePayslip) ? trim((string)($activePayslip['recorded_by_name'] ?? '')) : '';
$activePayslipNumber = $activePayslipId > 0
  ? ('PSL-' . str_replace('-', '', $activePayslipMonth) . '-' . str_pad((string)$activePayslipId, 4, '0', STR_PAD_LEFT))
  : ('PSL-' . str_replace('-', '', $activePayslipMonth) . '-PENDING');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ancillary Staff Desk</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg-cream: <?= h($paletteBgCream) ?>;
      --bg-sand: <?= h($paletteBgSand) ?>;
      --ink: <?= h($paletteInk) ?>;
      --muted: <?= h($paletteMuted) ?>;
      --brand-navy: <?= h($paletteBrandNavy) ?>;
      --brand-navy-deep: <?= h($paletteBrandNavyDeep) ?>;
      --brand-gold: <?= h($paletteBrandGold) ?>;
      --brand-ice: <?= h($paletteBrandIce) ?>;
      --patch-sky: <?= h($palettePatchSkySoft) ?>;
      --patch-yellow: <?= h($paletteBrandGold) ?>;
      --line: #d6d3cb;
      --panel: #ffffff;
      --shadow: 0 18px 45px rgba(10, 47, 99, 0.14);
      --radius-xl: 20px;
      --radius-lg: 14px;
      --success: #166534;
      --danger: #9f1239;
    }

    * { box-sizing: border-box; }

    body {
      margin: 0;
      font-family: 'Outfit', sans-serif;
      min-height: 100vh;
      color: var(--ink);
      background:
        radial-gradient(circle at 10% 15%, rgba(248, 180, 0, 0.2) 0, rgba(248, 180, 0, 0) 42%),
        radial-gradient(circle at 82% 12%, rgba(124, 201, 255, 0.24) 0, rgba(124, 201, 255, 0) 38%),
        linear-gradient(170deg, var(--bg-cream) 0%, var(--bg-sand) 100%);
      padding: 20px;
    }

    .shell {
      max-width: 1240px;
      margin: 0 auto;
      display: grid;
      gap: 16px;
      animation: rise 420ms ease-out;
    }

    @keyframes rise {
      from { opacity: 0; transform: translateY(12px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .header {
      background: linear-gradient(122deg, var(--brand-navy-deep), var(--brand-navy) 55%, var(--patch-sky));
      color: #fff;
      border-radius: var(--radius-xl);
      padding: 20px;
      box-shadow: var(--shadow);
      position: relative;
      overflow: hidden;
      display: grid;
      gap: 14px;
    }

    .header::after {
      content: '';
      position: absolute;
      width: 230px;
      height: 230px;
      right: -65px;
      top: -90px;
      border-radius: 50%;
      background: rgba(255, 212, 71, 0.2);
      border: 1px solid rgba(255, 212, 71, 0.34);
    }

    .top-row {
      display: flex;
      justify-content: space-between;
      gap: 10px;
      align-items: center;
      flex-wrap: wrap;
      position: relative;
      z-index: 1;
    }

    .brand { display: flex; align-items: center; gap: 12px; }
    .brand img {
      width: 64px;
      height: 64px;
      border-radius: 12px;
      object-fit: contain;
      border: 1px solid rgba(255, 255, 255, 0.3);
      background: rgba(255, 255, 255, 0.1);
      padding: 6px;
    }

    h1 {
      margin: 0;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-size: clamp(1.3rem, 2.2vw, 1.9rem);
      font-weight: 800;
      color: #fff;
    }
    .header .sub {
      color: rgba(255, 255, 255, 0.9);
      margin: 5px 0 0;
      font-size: 0.96rem;
    }
    .panel .sub {
      color: var(--muted);
      margin: 8px 0 14px;
      font-size: 0.93rem;
    }

    .chips { display: flex; gap: 8px; flex-wrap: wrap; position: relative; z-index: 1; }
    .chip {
      border-radius: 999px;
      padding: 7px 12px;
      font-size: 0.82rem;
      font-weight: 700;
      background: #ffd447;
      border: 1px solid #f8b400;
      color: #12386d;
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      gap: 8px;
    }

    .alert {
      border-radius: 11px;
      padding: 10px 12px;
      border: 1px solid;
      font-size: 0.92rem;
      font-weight: 600;
      margin-bottom: 10px;
    }
    .alert.success { background: #ecfdf3; color: var(--success); border-color: #86efac; }
    .alert.error { background: #fff1f2; color: var(--danger); border-color: #fda4af; }

    .layout {
      display: grid;
      grid-template-columns: 250px minmax(0, 1fr);
      gap: 14px;
      align-items: start;
    }

    .nav {
      position: sticky;
      top: 14px;
      background: #fff;
      border: 1px solid var(--line);
      border-radius: 16px;
      box-shadow: var(--shadow);
      padding: 12px;
      display: grid;
      gap: 6px;
    }

    .nav button {
      width: 100%;
      border: 1px solid #d8def0;
      background: #f8fbff;
      color: #12386d;
      border-radius: 10px;
      padding: 8px 10px;
      cursor: pointer;
      text-align: left;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-weight: 700;
      font-size: 0.84rem;
      box-shadow: 0 0 0 1px rgba(124, 201, 255, 0.45), 0 0 0 3px rgba(255, 212, 71, 0.22);
      transition: transform 140ms ease, background 140ms ease, color 140ms ease;
    }

    .nav button.active {
      background: linear-gradient(115deg, var(--brand-navy), var(--brand-navy-deep));
      color: #fff;
      border-color: #0a3b79;
    }

    .nav button:hover {
      background: #dff4ff;
      color: #083b78;
      box-shadow: 0 0 0 2px rgba(124, 201, 255, 0.7), 0 0 0 5px rgba(223, 242, 255, 0.95);
    }

    .section { display: none; }
    .section.active { display: grid; gap: 12px; }

    .panel {
      position: relative;
      background: var(--panel);
      border: 1px solid var(--line);
      border-radius: var(--radius-xl);
      box-shadow: var(--shadow);
      padding: 18px;
      overflow: hidden;
    }

    .panel::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 5px;
      background: linear-gradient(90deg, rgba(124, 201, 255, 0.5), rgba(255, 212, 71, 0.5));
    }

    .panel h2 {
      margin: 0;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-size: 1.1rem;
      color: var(--ink);
    }

    .stats {
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 12px;
    }

    .stat {
      background: #fff;
      color: var(--ink);
      border-radius: var(--radius-lg);
      border: 1px solid rgba(10, 59, 121, 0.2);
      box-shadow: 0 8px 24px rgba(10, 59, 121, 0.08);
      padding: 14px;
      position: relative;
      overflow: hidden;
    }

    .stat::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 4px;
      background: linear-gradient(90deg, rgba(124, 201, 255, 0.5), rgba(255, 212, 71, 0.5));
    }

    .stat small {
      text-transform: uppercase;
      letter-spacing: 0.07em;
      color: var(--muted);
      font-size: 0.78rem;
      font-weight: 700;
      display: block;
      margin-bottom: 7px;
    }

    .stat strong {
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-size: 1.5rem;
      color: var(--brand-navy-deep);
    }

    .grid-two {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 10px;
    }

    .field { display: grid; gap: 5px; margin-bottom: 11px; }
    .field label {
      font-size: 0.82rem;
      text-transform: uppercase;
      letter-spacing: 0.06em;
      color: var(--muted);
      font-weight: 700;
    }

    input, select, textarea {
      width: 100%;
      font-family: inherit;
      font-size: 0.95rem;
      border: 1px solid #c8c8be;
      border-radius: 10px;
      padding: 10px 11px;
      color: var(--ink);
      background: #fff;
    }

    textarea { min-height: 92px; resize: vertical; }

    input:focus, select:focus, textarea:focus {
      outline: none;
      border-color: var(--brand-navy);
      box-shadow: 0 0 0 3px rgba(10, 59, 121, 0.17);
    }

    .btn {
      border: 0;
      border-radius: 11px;
      padding: 10px 14px;
      font-family: 'Plus Jakarta Sans', sans-serif;
      font-weight: 700;
      cursor: pointer;
      transition: background 160ms ease, color 160ms ease, transform 120ms ease;
      box-shadow: 0 0 0 2px rgba(124, 201, 255, 0.55), 0 0 0 4px rgba(255, 212, 71, 0.35);
      text-decoration: none;
      display: inline-block;
    }

    .btn:hover {
      background: #7cc9ff;
      color: #083b78;
      transform: translateY(-1px);
      box-shadow: 0 0 0 2px rgba(124, 201, 255, 0.85), 0 0 0 5px rgba(255, 212, 71, 0.55);
    }

    .btn.primary, .btn {
      background: linear-gradient(115deg, var(--brand-navy), var(--brand-navy-deep));
      color: #fff;
    }

    .btn.alt {
      background: #fff;
      color: var(--brand-navy-deep);
      border: 1px solid #bfd4f4;
      box-shadow: none;
    }

    .btn.alt:hover {
      background: #ecf6ff;
      color: var(--brand-navy-deep);
      transform: translateY(-1px);
    }

    .table-wrap { overflow: auto; border-radius: 14px; border: 1px solid var(--line); background: #fff; }
    table { width: 100%; border-collapse: collapse; min-width: 760px; }
    th, td { border-bottom: 1px solid #e3ecf0; text-align: left; padding: 8px; font-size: 0.92rem; vertical-align: top; }
    th {
      background: linear-gradient(95deg, #eef3fb, #f8edd1);
      color: #173b70;
      font-size: 0.8rem;
      text-transform: uppercase;
      letter-spacing: 0.06em;
    }
    tr:nth-child(even) td { background: #fbfdff; }

    .status-chip {
      border-radius: 999px;
      padding: 3px 8px;
      border: 1px solid var(--line);
      font-size: 0.78rem;
      font-weight: 700;
      display: inline-block;
      text-transform: uppercase;
    }

    .status-ok { color: #206a31; border-color: #99d4ac; background: #e9f8ed; }
    .status-warn { color: #9d3c2d; border-color: #e4b1a8; background: #fff0ec; }

    .payslip {
      border: 1px dashed var(--line);
      border-radius: 12px;
      padding: 14px;
      background: #fff;
    }

    .payslip-paper {
      border: 1px solid #dbe8ee;
      border-radius: 12px;
      padding: 14px;
      background: #fff;
    }
    .payslip-title-row {
      display: flex;
      justify-content: space-between;
      gap: 12px;
      align-items: flex-start;
      flex-wrap: wrap;
      margin-bottom: 10px;
    }
    .payslip-title-row h3 {
      margin: 0;
      color: var(--brand-navy-deep);
      font-size: 1.25rem;
      font-family: 'Plus Jakarta Sans', sans-serif;
    }
    .payslip-ref {
      border: 1px solid var(--line);
      border-radius: 10px;
      padding: 8px 10px;
      background: #f8fbfd;
      min-width: 240px;
      font-size: 0.9rem;
    }
    .payslip-meta-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
      gap: 10px;
      margin: 12px 0;
    }
    .payslip-meta-card {
      border: 1px solid #e4edf1;
      border-radius: 10px;
      padding: 10px;
      background: #fcfeff;
    }
    .payslip-meta-card h4 {
      margin: 0 0 6px;
      font-size: 0.95rem;
      color: var(--brand-navy-deep);
    }
    .payslip-meta-card p {
      margin: 4px 0;
      font-size: 0.9rem;
    }
    .payslip-ledger {
      width: 100%;
      border-collapse: collapse;
      margin-top: 10px;
      min-width: 0;
    }
    .payslip-ledger th,
    .payslip-ledger td {
      border: 1px solid #dfe9ee;
      padding: 8px;
      font-size: 0.9rem;
    }
    .payslip-ledger th {
      background: #f4f9fb;
      color: var(--brand-navy-deep);
      text-align: left;
    }
    .money { text-align: right; font-variant-numeric: tabular-nums; }
    .payslip-total-row td {
      font-weight: 700;
      background: #f7fbfc;
    }
    .payslip-signoff {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
      gap: 18px;
      margin-top: 18px;
    }
    .payslip-sign-line {
      border-top: 1px solid #6f8693;
      padding-top: 6px;
      font-size: 0.88rem;
      color: #405965;
      min-height: 28px;
    }

    @media (max-width: 980px) {
      .layout { grid-template-columns: 1fr; }
      .nav { position: static; }
      .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
      table { min-width: 640px; }
    }

    @media (max-width: 640px) {
      body { padding: 12px; }
      .stats { grid-template-columns: 1fr; }
      .header { padding: 16px; }
      .top-row { align-items: flex-start; }
    }

    @media print {
      .no-print { display: none !important; }
      body { background: #fff; }
      .shell { max-width: none; }
      .panel, .header { border-color: #ddd; }
    }
  </style>
</head>
<body>
  <div class="shell">
    <header class="header no-print">
      <div class="top-row">
        <div class="brand">
          <img src="<?= h($resolvedSchoolLogoPath !== '' ? $resolvedSchoolLogoPath : $defaultSchoolLogoPath) ?>" alt="School logo">
          <div>
            <h1>Ancillary Staff Desk</h1>
            <?php if ($isAdminReadOnlyView): ?>
              <p class="sub"><?= h($schoolName) ?> | Admin read-only preview mode for ancillary worker desk.</p>
            <?php else: ?>
              <p class="sub"><?= h($schoolName) ?> | Salary register, payslips, leave applications, and full profile.</p>
            <?php endif; ?>
          </div>
        </div>
        <div class="chips">
          <span class="chip"><?= h($ancillaryProfile['name'] ?? 'Ancillary Staff') ?></span>
          <?php if ($isAdminReadOnlyView): ?>
            <a class="chip" href="admin.php">Back to Admin Portal</a>
          <?php endif; ?>
          <a class="chip" href="logout.php">Logout</a>
        </div>
      </div>
    </header>

    <?php foreach ($alerts as $alert): ?>
      <div class="alert <?= $alert['type'] === 'success' ? 'success' : 'error' ?>"><?= h($alert['text']) ?></div>
    <?php endforeach; ?>

    <div class="layout">
      <aside class="nav no-print">
        <?php if ($forcePasswordChange): ?>
          <button type="button" class="desk-nav-btn active" data-target="profileSection">Update Password First</button>
        <?php else: ?>
          <button type="button" class="desk-nav-btn active" data-target="overviewSection">Overview</button>
          <button type="button" class="desk-nav-btn" data-target="salarySection">Salary Register</button>
          <button type="button" class="desk-nav-btn" data-target="leaveSection">Leave Applications</button>
          <button type="button" class="desk-nav-btn" data-target="profileSection">My Profile</button>
        <?php endif; ?>
      </aside>

      <main>
        <section id="overviewSection" class="section<?= $forcePasswordChange ? '' : ' active' ?>">
          <article class="panel">
            <h2 style="margin-top:0;">Desk Summary</h2>
            <div class="stats">
              <div class="stat"><small>Total Payslips</small><strong><?= h((string)count($mySalaryRows)) ?></strong></div>
              <div class="stat"><small>Paid Net Salary (USD)</small><strong>$<?= h(number_format($totalNetSalary, 2)) ?></strong></div>
              <div class="stat"><small>Leave Requests</small><strong><?= h((string)count($myLeaveRequests)) ?></strong></div>
              <div class="stat"><small>Pending Leaves</small><strong><?= h((string)count(array_filter($myLeaveRequests, static fn($row) => ($row['status'] ?? '') === 'pending'))) ?></strong></div>
            </div>
          </article>

          <article class="panel">
            <h2 style="margin-top:0;">Staff Details Snapshot</h2>
            <div class="grid-two">
              <div>
                <p><strong>Full Name:</strong> <?= h((string)($ancillaryProfile['name'] ?? '-')) ?></p>
                <p><strong>Email:</strong> <?= h((string)($ancillaryProfile['email'] ?? '-')) ?></p>
                <p><strong>Sex:</strong> <?= h((string)($ancillaryProfile['sex'] ?? '-')) ?></p>
                <p><strong>Date of Birth:</strong> <?= h((string)($ancillaryProfile['date_of_birth'] ?? '-')) ?></p>
              </div>
              <div>
                <p><strong>EC Number:</strong> <?= h((string)($ancillaryProfile['ec_number'] ?? '-')) ?></p>
                <p><strong>National ID:</strong> <?= h((string)($ancillaryProfile['national_id'] ?? '-')) ?></p>
                <p><strong>Work Profile:</strong> <?= h((string)($ancillaryProfile['work_profile'] ?? '-')) ?></p>
                <p><strong>Qualifications:</strong> <?= h((string)($ancillaryProfile['qualifications'] ?? '-')) ?></p>
              </div>
            </div>
          </article>
        </section>

        <section id="salarySection" class="section">
          <article class="panel">
            <div class="no-print" style="display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;align-items:center;">
              <h2 style="margin:0;">My Salary Register</h2>
              <div style="display:flex;gap:6px;flex-wrap:wrap;">
                <button class="btn alt" type="button" id="printSalaryRegisterBtn">Print Register</button>
              </div>
            </div>
            <p class="sub">Monthly salary records created by the accounts office for your individual worker account.</p>
            <div class="table-wrap">
              <table id="salaryRegisterTable">
                <thead>
                  <tr>
                    <th>Month</th>
                    <th>Base Salary</th>
                    <th>Allowances</th>
                    <th>Deductions</th>
                    <th>Net Salary</th>
                    <th>Pay Date</th>
                    <th>Note</th>
                    <th>Payslip</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (empty($mySalaryRows)): ?>
                    <tr><td colspan="8">No salary records posted yet.</td></tr>
                  <?php else: ?>
                    <?php foreach ($mySalaryRows as $salaryRow): ?>
                      <tr>
                        <td><?= h((string)$salaryRow['salary_month']) ?></td>
                        <td>$<?= h(number_format((float)$salaryRow['base_salary'], 2)) ?></td>
                        <td>$<?= h(number_format((float)$salaryRow['allowance_amount'], 2)) ?></td>
                        <td>$<?= h(number_format((float)$salaryRow['deduction_amount'], 2)) ?></td>
                        <td><strong>$<?= h(number_format((float)$salaryRow['net_salary'], 2)) ?></strong></td>
                        <td><?= h((string)($salaryRow['pay_date'] ?? '-')) ?></td>
                        <td><?= h((string)($salaryRow['note'] ?? '-')) ?></td>
                        <td>
                          <a class="btn alt no-print" href="ancillary.php?payslip_id=<?= h((string)$salaryRow['id']) ?>">Open Payslip</a>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </article>

          <article class="panel" id="payslipPanel">
            <div class="no-print" style="display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;align-items:center;">
              <h2 style="margin:0;">Worker Payslip</h2>
              <div style="display:flex;gap:6px;flex-wrap:wrap;">
                <button class="btn alt" type="button" id="printPayslipBtn">Print Payslip</button>
                <button class="btn alt" type="button" id="downloadPayslipBtn">Download Payslip</button>
              </div>
            </div>
            <?php if (!$activePayslip): ?>
              <p class="sub">No payslip available yet.</p>
            <?php else: ?>
              <div class="payslip" id="payslipDocument">
                <div class="payslip-paper">
                  <div class="payslip-title-row">
                    <div>
                      <h3><?= h($schoolName) ?></h3>
                      <div class="sub" style="margin-top:4px;"><?= h($schoolAddress) ?></div>
                      <div class="sub"><?= h($schoolContact) ?></div>
                      <div class="sub"><?= h($schoolMotto) ?></div>
                    </div>
                    <div class="payslip-ref">
                      <div><strong>PAYSLIP</strong></div>
                      <div>Payslip No: <?= h($activePayslipNumber) ?></div>
                      <div>Salary Month: <?= h($activePayslipMonth) ?></div>
                      <div>Pay Date: <?= h($activePayslipPayDate !== '' ? $activePayslipPayDate : '-') ?></div>
                    </div>
                  </div>

                  <div class="payslip-meta-grid">
                    <div class="payslip-meta-card">
                      <h4>Employee Details</h4>
                      <p><strong>Name:</strong> <?= h($printableStaffName) ?></p>
                      <p><strong>Role:</strong> Ancillary Staff</p>
                      <p><strong>Work Profile:</strong> <?= h((string)($ancillaryProfile['work_profile'] ?? '-')) ?></p>
                    </div>
                    <div class="payslip-meta-card">
                      <h4>Employment Details</h4>
                      <p><strong>EC Number:</strong> <?= h((string)($ancillaryProfile['ec_number'] ?? '-')) ?></p>
                      <p><strong>National ID:</strong> <?= h((string)($ancillaryProfile['national_id'] ?? '-')) ?></p>
                      <p><strong>Email:</strong> <?= h((string)($ancillaryProfile['email'] ?? '-')) ?></p>
                    </div>
                  </div>

                  <table class="payslip-ledger" aria-label="payslip breakdown">
                    <thead>
                      <tr>
                        <th>Item</th>
                        <th class="money">Amount (USD)</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td>Base Salary</td>
                        <td class="money"><?= h(number_format($activePayslipBase, 2)) ?></td>
                      </tr>
                      <tr>
                        <td>Allowances</td>
                        <td class="money"><?= h(number_format($activePayslipAllowance, 2)) ?></td>
                      </tr>
                      <tr class="payslip-total-row">
                        <td>Gross Salary</td>
                        <td class="money"><?= h(number_format($activePayslipGross, 2)) ?></td>
                      </tr>
                      <tr>
                        <td>Deductions</td>
                        <td class="money"><?= h(number_format($activePayslipDeduction, 2)) ?></td>
                      </tr>
                      <tr class="payslip-total-row">
                        <td>Net Salary Payable</td>
                        <td class="money"><?= h(number_format($activePayslipNet, 2)) ?></td>
                      </tr>
                    </tbody>
                  </table>

                  <div style="margin-top:12px;">
                    <strong>Payroll Notes:</strong> <?= h($activePayslipNote !== '' ? $activePayslipNote : '-') ?><br>
                    <strong>Recorded By:</strong> <?= h($activePayslipRecordedBy !== '' ? $activePayslipRecordedBy : '-') ?>
                  </div>

                  <div class="payslip-signoff">
                    <div class="payslip-sign-line">Prepared By (Accounts Office)</div>
                    <div class="payslip-sign-line">Employee Signature</div>
                    <div class="payslip-sign-line">Date Received</div>
                  </div>
                </div>
              </div>
            <?php endif; ?>
          </article>
        </section>

        <section id="leaveSection" class="section">
          <article class="panel">
            <h2 style="margin-top:0;">Apply For Leave</h2>
            <p class="sub">Submit leave forms for admin approval. Upload document to keep printable and downloadable records.</p>
            <form method="POST" enctype="multipart/form-data">
              <div class="grid-two">
                <div class="field">
                  <label for="leave_type">Leave Type</label>
                  <select id="leave_type" name="leave_type" required>
                    <option value="">Choose leave type</option>
                    <option value="sick">Sick Leave</option>
                    <option value="annual">Annual Leave</option>
                    <option value="maternity">Maternity Leave</option>
                    <option value="compassionate">Compassionate Leave</option>
                    <option value="unpaid">Unpaid Leave</option>
                    <option value="other">Other</option>
                  </select>
                </div>
                <div class="field">
                  <label for="leave_start_date">Start Date</label>
                  <input type="date" id="leave_start_date" name="leave_start_date" required>
                </div>
                <div class="field">
                  <label for="leave_end_date">End Date</label>
                  <input type="date" id="leave_end_date" name="leave_end_date" required>
                </div>
                <div class="field">
                  <label for="leave_document">Leave Form (PDF/JPG/PNG/WEBP)</label>
                  <input id="leave_document" name="leave_document" type="file" accept="application/pdf,image/jpeg,image/png,image/webp" required>
                </div>
              </div>
              <div class="field">
                <label for="leave_reason">Reason</label>
                <textarea id="leave_reason" name="leave_reason" required placeholder="Provide details for your leave application"></textarea>
              </div>
              <button class="btn" type="submit" name="submit_ancillary_leave_request">Submit Leave Application</button>
            </form>
          </article>

          <article class="panel">
            <h2 style="margin-top:0;">My Leave Register</h2>
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Submitted</th>
                    <th>Leave Type</th>
                    <th>Period</th>
                    <th>Reason</th>
                    <th>Document</th>
                    <th>Status</th>
                    <th>Admin Comment</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (empty($myLeaveRequests)): ?>
                    <tr><td colspan="7">No leave requests submitted yet.</td></tr>
                  <?php else: ?>
                    <?php foreach ($myLeaveRequests as $leaveRequest): ?>
                      <?php
                        $leaveDocumentPath = trim((string)($leaveRequest['supporting_document_path'] ?? ''));
                        $leaveDocumentAbsolute = $leaveDocumentPath !== '' ? (__DIR__ . '/' . ltrim($leaveDocumentPath, '/\\')) : '';
                        $hasLeaveDocument = $leaveDocumentPath !== '' && is_file($leaveDocumentAbsolute);
                        $leaveDocumentName = trim((string)($leaveRequest['supporting_document_name'] ?? ''));
                        if ($leaveDocumentName === '') {
                          $leaveDocumentName = $hasLeaveDocument ? basename($leaveDocumentPath) : 'No document';
                        }
                      ?>
                      <tr>
                        <td><?= h((string)$leaveRequest['created_at']) ?></td>
                        <td><?= h(ucfirst(str_replace('_', ' ', (string)$leaveRequest['leave_type']))) ?></td>
                        <td><?= h((string)$leaveRequest['start_date']) ?> to <?= h((string)$leaveRequest['end_date']) ?></td>
                        <td><?= h((string)$leaveRequest['reason']) ?></td>
                        <td>
                          <?php if ($hasLeaveDocument): ?>
                            <span style="display:block; margin-bottom:6px;"><?= h($leaveDocumentName) ?></span>
                            <a class="btn alt" href="<?= h($leaveDocumentPath) ?>" download="<?= h($leaveDocumentName) ?>">Download</a>
                            <a class="btn alt" href="<?= h($leaveDocumentPath) ?>" target="_blank" rel="noopener">Open / Print</a>
                          <?php else: ?>
                            <span class="sub">No file</span>
                          <?php endif; ?>
                        </td>
                        <td>
                          <span class="status-chip <?= $leaveRequest['status'] === 'approved' ? 'status-ok' : (($leaveRequest['status'] === 'rejected') ? 'status-warn' : '') ?>">
                            <?= h((string)$leaveRequest['status']) ?>
                          </span>
                        </td>
                        <td>
                          <?= h((string)($leaveRequest['admin_comment'] ?: '-')) ?>
                          <?php if (!empty($leaveRequest['reviewed_at'])): ?>
                            <br><small><?= h((string)$leaveRequest['reviewed_at']) ?></small>
                          <?php endif; ?>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </article>
        </section>

        <section id="profileSection" class="section<?= $forcePasswordChange ? ' active' : '' ?>">
          <article class="panel">
            <h2 style="margin-top:0;">My Profile</h2>
            <?php if ($isAdminReadOnlyView): ?>
              <p class="sub">Profile editing is disabled in admin read-only preview mode.</p>
            <?php else: ?>
              <form method="POST" autocomplete="off">
                <div class="grid-two">
                  <div class="field">
                    <label for="profile_name">Full Name</label>
                    <input id="profile_name" name="profile_name" value="<?= h((string)($ancillaryProfile['name'] ?? '')) ?>" required>
                  </div>
                  <div class="field">
                    <label for="profile_email">Email</label>
                    <input id="profile_email" type="email" name="profile_email" value="<?= h((string)($ancillaryProfile['email'] ?? '')) ?>" required>
                  </div>
                  <div class="field">
                    <label for="profile_sex">Sex</label>
                    <select id="profile_sex" name="profile_sex">
                      <option value="">Choose sex</option>
                      <option value="Male" <?= (string)($ancillaryProfile['sex'] ?? '') === 'Male' ? 'selected' : '' ?>>Male</option>
                      <option value="Female" <?= (string)($ancillaryProfile['sex'] ?? '') === 'Female' ? 'selected' : '' ?>>Female</option>
                      <option value="Other" <?= (string)($ancillaryProfile['sex'] ?? '') === 'Other' ? 'selected' : '' ?>>Other</option>
                    </select>
                  </div>
                  <div class="field">
                    <label for="profile_dob">Date of Birth</label>
                    <input id="profile_dob" type="date" name="profile_dob" value="<?= h((string)($ancillaryProfile['date_of_birth'] ?? '')) ?>">
                  </div>
                  <div class="field">
                    <label for="profile_ec_number">EC Number</label>
                    <input id="profile_ec_number" name="profile_ec_number" value="<?= h((string)($ancillaryProfile['ec_number'] ?? '')) ?>">
                  </div>
                  <div class="field">
                    <label for="profile_national_id">National ID</label>
                    <input id="profile_national_id" name="profile_national_id" value="<?= h((string)($ancillaryProfile['national_id'] ?? '')) ?>">
                  </div>
                  <div class="field">
                    <label for="profile_work_profile">Work Profile</label>
                    <input id="profile_work_profile" name="profile_work_profile" value="<?= h((string)($ancillaryProfile['work_profile'] ?? '')) ?>" placeholder="e.g. Grounds, Security, Transport, Office Support">
                  </div>
                </div>
                <div class="field">
                  <label for="profile_qualifications">Qualifications</label>
                  <textarea id="profile_qualifications" name="profile_qualifications"><?= h((string)($ancillaryProfile['qualifications'] ?? '')) ?></textarea>
                </div>
                <button class="btn" type="submit" name="save_ancillary_profile">Save Profile</button>
              </form>
            <?php endif; ?>
          </article>

          <article class="panel no-print">
            <h2 style="margin-top:0;">Change Password</h2>
            <?php if ($isAdminReadOnlyView): ?>
              <p class="sub">Password update is disabled in admin read-only preview mode.</p>
            <?php else: ?>
              <form method="POST" autocomplete="off">
                <div class="grid-two">
                  <div class="field">
                    <label for="current_password">Current Password</label>
                    <input id="current_password" type="password" name="current_password" required>
                  </div>
                  <div class="field">
                    <label for="new_password">New Password</label>
                    <input id="new_password" type="password" name="new_password" minlength="10" autocomplete="new-password" required>
                  </div>
                  <div class="field">
                    <label for="confirm_password">Confirm New Password</label>
                    <input id="confirm_password" type="password" name="confirm_password" minlength="10" autocomplete="new-password" required>
                  </div>
                </div>
                <button class="btn" type="submit" name="change_ancillary_password">Change Password</button>
              </form>
            <?php endif; ?>
          </article>
        </section>
      </main>
    </div>
  </div>

  <script>
    const navButtons = Array.from(document.querySelectorAll('.desk-nav-btn'));
    const sections = Array.from(document.querySelectorAll('.section'));

    function setActiveSection(targetId) {
      sections.forEach(section => {
        section.classList.toggle('active', section.id === targetId);
      });
      navButtons.forEach(button => {
        button.classList.toggle('active', button.dataset.target === targetId);
      });
    }

    navButtons.forEach(button => {
      button.addEventListener('click', function () {
        setActiveSection(this.dataset.target || 'overviewSection');
      });
    });

    const printSalaryRegisterBtn = document.getElementById('printSalaryRegisterBtn');
    if (printSalaryRegisterBtn) {
      printSalaryRegisterBtn.addEventListener('click', function () {
        setActiveSection('salarySection');
        window.print();
      });
    }

    const printPayslipBtn = document.getElementById('printPayslipBtn');
    if (printPayslipBtn) {
      printPayslipBtn.addEventListener('click', function () {
        const payslipPanel = document.getElementById('payslipPanel');
        if (!payslipPanel) {
          return;
        }
        setActiveSection('salarySection');
        window.print();
      });
    }

    const downloadPayslipBtn = document.getElementById('downloadPayslipBtn');
    if (downloadPayslipBtn) {
      downloadPayslipBtn.addEventListener('click', function () {
        const payslipDoc = document.getElementById('payslipDocument');
        if (!payslipDoc) {
          window.alert('No payslip selected.');
          return;
        }
        const fileName = ('<?= h((string)($ancillaryProfile['name'] ?? 'worker')) ?>_<?= h($activePayslipMonth) ?>_payslip')
          .toLowerCase()
          .replace(/[^a-z0-9_-]+/g, '_');
        const html = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Official Payslip</title>'
          + '<style>'
          + 'body{font-family:Arial,sans-serif;margin:0;padding:16px;background:#f7fbfc;color:#163645;}'
          + '.payslip{max-width:900px;margin:0 auto;background:#fff;border:1px solid #d3e2e9;border-radius:12px;padding:14px;}'
          + '.payslip-paper{border:1px solid #dbe8ee;border-radius:12px;padding:14px;background:#fff;}'
          + '.payslip-title-row{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;flex-wrap:wrap;margin-bottom:10px;}'
          + '.payslip-title-row h3{margin:0;color:#0f3a59;font-size:1.25rem;}'
          + '.payslip-ref{border:1px solid #d7e6ed;border-radius:10px;padding:8px 10px;background:#f8fbfd;min-width:240px;font-size:.9rem;}'
          + '.payslip-meta-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:10px;margin:12px 0;}'
          + '.payslip-meta-card{border:1px solid #e4edf1;border-radius:10px;padding:10px;background:#fcfeff;}'
          + '.payslip-meta-card h4{margin:0 0 6px;font-size:.95rem;color:#0f3a59;}'
          + '.payslip-meta-card p{margin:4px 0;font-size:.9rem;}'
          + '.payslip-ledger{width:100%;border-collapse:collapse;margin-top:10px;}'
          + '.payslip-ledger th,.payslip-ledger td{border:1px solid #dfe9ee;padding:8px;font-size:.9rem;}'
          + '.payslip-ledger th{background:#f4f9fb;color:#0f3a59;text-align:left;}'
          + '.money{text-align:right;font-variant-numeric:tabular-nums;}'
          + '.payslip-total-row td{font-weight:700;background:#f7fbfc;}'
          + '.payslip-signoff{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:18px;margin-top:18px;}'
          + '.payslip-sign-line{border-top:1px solid #6f8693;padding-top:6px;font-size:.88rem;color:#405965;min-height:28px;}'
          + '@media print{body{background:#fff;padding:0}.payslip{border:none;padding:0;max-width:none}}'
          + '</style></head><body>'
          + payslipDoc.outerHTML + '</body></html>';
        const blob = new Blob([html], { type: 'text/html;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const anchor = document.createElement('a');
        anchor.href = url;
        anchor.download = fileName + '.html';
        document.body.appendChild(anchor);
        anchor.click();
        anchor.remove();
        URL.revokeObjectURL(url);
      });
    }
  </script>

  <?php output_auto_capitalize_script(); ?>
  <?php output_select_search_script(); ?>
</body>
</html>
