<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

session_start();
require 'config.php';

if (!isset($_SESSION['user_id'])) { header("Location: index.php"); exit; }

$user_id   = $_SESSION['user_id'];
$user_role = $_SESSION['role'];
$username  = $_SESSION['username'] ?? 'User';

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

$success = "";
$error   = "";

/* ── GET REPORTING & MD ── */
$stmt = $conn->prepare("SELECT reporting_manager_id, md_id FROM users WHERE id=? AND status='active'");
$stmt->bind_param("s", $user_id);
$stmt->execute();
$stmt->bind_result($reporting_manager_id, $md_id);
$stmt->fetch();
$stmt->close();

/* ── SUBMIT LEAVE ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $leave_type       = $_POST['leave_type'] ?? '';
    $reason           = trim($_POST['reason'] ?? '');
    $work_description = trim($_POST['work_description'] ?? '');
    $start_date       = $_POST['start_date'] ?? '';
    $end_date         = $_POST['end_date'] ?? '';
    $permission_date  = $_POST['permission_date'] ?: NULL;
    $permission_from  = $_POST['permission_time_from'] ?: NULL;
    $permission_to    = $_POST['permission_time_to'] ?: NULL;
    $permission_hours = $_POST['permission_hours'] ?: NULL;

    if (empty($leave_type) || empty($reason) || empty($start_date) || empty($end_date)) {
        $error = "All required fields must be filled.";
    } elseif (empty($md_id)) {
        $error = "MD not assigned to your profile.";
    } else {
        $manager_status  = 'Approved';
        $hr_status       = 'Approved';
        $status          = 'Pending';
        $forwarded_to_admin = 0;
        $delegate_to     = NULL;
        $manager_comment = NULL;
        $hr_comment      = NULL;
        $md_comment      = NULL;

        $stmt = $conn->prepare("INSERT INTO leave_requests (employee_id,delegate_to,leave_type,start_date,end_date,reason,permission_hours,permission_date,permission_time_from,permission_time_to,manager_status,manager_comment,forwarded_to_admin,work_description,hr_comment,md_comment,hr_status,reporting_manager_id,md_id,manager_action_on,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?)");
        if (!$stmt) die("Prepare failed: " . $conn->error);
        $stmt->bind_param("sisssssdssssssssisss", $user_id,$delegate_to,$leave_type,$start_date,$end_date,$reason,$permission_hours,$permission_date,$permission_from,$permission_to,$manager_status,$manager_comment,$forwarded_to_admin,$work_description,$hr_comment,$md_comment,$hr_status,$reporting_manager_id,$md_id,$status);
        if ($stmt->execute()) { $success = "Leave application submitted successfully to MD."; }
        else { $error = "Insert Error: " . $stmt->error; }
        $stmt->close();
    }
}

/* ── FETCH HISTORY ── */
$stmt = $conn->prepare("SELECT leave_type,start_date,end_date,permission_date,permission_time_from,permission_time_to,permission_hours,reason,status,md_comment,applied_on FROM leave_requests WHERE employee_id = ? ORDER BY applied_on DESC");
$stmt->bind_param("s", $user_id);
$stmt->execute();
$history = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>MPC · Apply Leave</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=DM+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --ink:#0f172a;--ink-2:#334155;--muted:#64748b;--border:#e2e8f0;
  --surface:#ffffff;--bg:#f0f4f8;--sidebar-bg:#111827;--sidebar-w:260px;
  --accent:#4f46e5;--accent-2:#06b6d4;--green:#059669;--red:#dc2626;--amber:#d97706;
  --radius:14px;--radius-sm:8px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.07);
  --shadow-md:0 4px 6px rgba(15,23,42,.07),0 12px 32px rgba(15,23,42,.10);
  font-family:'DM Sans',system-ui,sans-serif;
}
html,body{height:100%}
body{background:var(--bg);color:var(--ink);font-size:14px;-webkit-font-smoothing:antialiased}
.layout{display:flex;min-height:100vh}
.sidebar{width:var(--sidebar-w);background:var(--sidebar-bg);position:fixed;inset:0 auto 0 0;z-index:200;display:flex;flex-direction:column;overflow-y:auto;transition:transform .3s ease;scrollbar-width:none}
.sidebar::-webkit-scrollbar{display:none}
.sidebar.hidden{transform:translateX(-100%)}
.sidebar-brand{padding:22px 18px 14px;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.07);margin-bottom:6px}
.brand-logo{width:34px;height:34px;background:linear-gradient(135deg,var(--accent),var(--accent-2));border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;font-size:15px;flex-shrink:0}
.brand-name{font-size:14px;font-weight:700;color:#fff;letter-spacing:-.2px}
.brand-sub{font-size:9px;color:rgba(255,255,255,.35);letter-spacing:1.8px;text-transform:uppercase;margin-top:1px}
.nav-group-label{font-size:9px;font-weight:600;letter-spacing:1.8px;text-transform:uppercase;color:rgba(255,255,255,.25);padding:12px 18px 4px}
.nav-item{list-style:none}
.nav-link{display:flex;align-items:center;gap:9px;padding:8px 14px;margin:1px 8px;border-radius:8px;color:rgba(255,255,255,.6);text-decoration:none;font-size:13px;font-weight:500;transition:all .15s}
.nav-link:hover{background:rgba(255,255,255,.07);color:#fff}
.nav-link.active{background:rgba(79,70,229,.25);color:#a5b4fc}
.nav-link i{width:15px;text-align:center;font-size:12px;flex-shrink:0}
.nav-link.danger{color:#f87171}.nav-link.danger:hover{background:rgba(248,113,113,.1);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:10px 8px;border-top:1px solid rgba(255,255,255,.06)}
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column;transition:margin .3s ease}
.content.expanded{margin-left:0}
.topbar{height:58px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 22px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border)}
.hamburger-btn{width:34px;height:34px;border-radius:8px;border:1px solid var(--border);background:transparent;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink-2);font-size:14px;flex-shrink:0;transition:background .15s}
.hamburger-btn:hover{background:var(--bg)}
.topbar-breadcrumb{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted)}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600;font-size:13px}
.topbar-spacer{flex:1}
.topbar-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink-2);font-weight:500}
.topbar-avatar{width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-2));display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:700;flex-shrink:0}
.page{padding:22px;flex:1}
.page-header{margin-bottom:22px;display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:10px}
.page-title{font-size:20px;font-weight:700;color:var(--ink);letter-spacing:-.4px}
.page-subtitle{font-size:13px;color:var(--muted);margin-top:2px}
.dash-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:18px;overflow:hidden}
.dash-card-header{padding:16px 20px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
.dash-card-title{font-size:14px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:8px}
.dash-card-title i{color:var(--accent);font-size:13px}
.dash-card-body{padding:20px}
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.form-grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px}
.form-group{display:flex;flex-direction:column;gap:5px}
.form-label{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.form-label span{color:var(--red);margin-left:2px}
.form-control{width:100%;padding:9px 12px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:13px;font-family:'DM Sans',sans-serif;color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s,background .15s;-webkit-appearance:none}
.form-control:focus{border-color:var(--accent);background:var(--surface);box-shadow:0 0 0 3px rgba(79,70,229,.08)}
.form-control::placeholder{color:var(--muted)}
select.form-control{cursor:pointer}
textarea.form-control{resize:vertical;min-height:80px;line-height:1.6}
.section-divider{display:flex;align-items:center;gap:10px;margin:6px 0 14px}
.section-divider span{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);white-space:nowrap}
.section-divider::before,.section-divider::after{content:'';flex:1;height:1px;background:var(--border)}
.optional-badge{background:#f1f5f9;color:var(--muted);font-size:10px;font-weight:600;padding:2px 7px;border-radius:10px;letter-spacing:.3px}
.btn-submit{width:100%;padding:11px 20px;background:linear-gradient(135deg,var(--accent),#6366f1);color:#fff;border:none;border-radius:var(--radius-sm);font-size:14px;font-weight:700;font-family:'DM Sans',sans-serif;cursor:pointer;transition:opacity .15s,transform .15s;display:flex;align-items:center;justify-content:center;gap:8px;margin-top:6px}
.btn-submit:hover{opacity:.92;transform:translateY(-1px)}
.alert-custom{padding:12px 16px;border-radius:var(--radius-sm);font-size:13px;margin-bottom:16px;display:flex;align-items:flex-start;gap:10px}
.alert-success-custom{background:#d1fae5;border-left:3px solid var(--green);color:#065f46}
.alert-error-custom{background:#fee2e2;border-left:3px solid var(--red);color:#991b1b}
.tbl-wrap{overflow-x:auto}
.dash-table{width:100%;border-collapse:collapse;font-size:13px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.6px;padding:10px 14px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:11px 14px;border-bottom:1px solid var(--border);color:var(--ink-2);vertical-align:top}
.dash-table tbody tr:last-child td{border-bottom:none}
.dash-table tbody tr:hover td{background:#fafbfc}
.badge-custom{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600;white-space:nowrap}
.badge-success{background:#d1fae5;color:#065f46}
.badge-warning{background:#fef3c7;color:#92400e}
.badge-danger{background:#fee2e2;color:#991b1b}
.badge-purple{background:#ede9fe;color:#5b21b6}
.empty-state{text-align:center;padding:48px 24px;color:var(--muted)}
.empty-state i{font-size:36px;display:block;margin-bottom:12px;opacity:.35}
.back-btn{display:inline-flex;align-items:center;gap:7px;padding:8px 16px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-sm);font-size:13px;font-weight:600;color:var(--ink-2);text-decoration:none;box-shadow:var(--shadow);transition:background .15s}
.back-btn:hover{background:var(--bg);color:var(--ink);text-decoration:none}
@media(max-width:768px){.sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}.content{margin-left:0}.page{padding:14px}.form-grid,.form-grid-3{grid-template-columns:1fr}}


/* ═══ MOBILE SIDEBAR FIX - SAME AS DASHBOARD_MANAGER ═══ */
.sidebar-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:290;backdrop-filter:blur(2px);opacity:0;transition:opacity .28s}
.sidebar-overlay.active{display:block;opacity:1}
@media(max-width:768px){
  body{overflow-x:hidden}
  .layout{min-width:0;width:100%}
  .sidebar{transform:translateX(-100%) !important;left:0;top:0;bottom:0;height:100vh;z-index:300}
  .sidebar.open{transform:translateX(0) !important}
  .content{margin-left:0 !important;width:100%;max-width:100%;min-width:0}
  .content.expanded{margin-left:0 !important}
  .topbar{padding:0 12px;gap:8px}
  .page{padding:13px !important}
  .topbar-user span{max-width:115px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
}
@media(min-width:769px){
  .sidebar{transform:translateX(0) !important}
  .sidebar-overlay.active{display:none !important;opacity:0 !important}
  .content{margin-left:var(--sidebar-w)}
}

</style>
</head>
<body>

<!-- OVERLAY -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>

<div class="layout">

<!-- ═══ SIDEBAR ═══ -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC Portal</div>
      <div class="brand-sub">Manager</div>
    </div>
  </div>
  <div class="nav-group-label">Main</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="dashboard_manager.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a></li>
    <li class="nav-item"><a href="myteam.php" class="nav-link"><i class="fas fa-sitemap"></i> My Team</a></li>
  </ul>
  <div class="nav-group-label">Work</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="manager_daily_report.php" class="nav-link"><i class="fas fa-calendar-check"></i> Attendance</a></li>
    <li class="nav-item"><a href="daily_reports_manager.php" class="nav-link"><i class="fas fa-file-alt"></i> Daily Reports</a></li>
    <li class="nav-item"><a href="leave_dashboard_manager.php" class="nav-link"><i class="fas fa-umbrella-beach"></i> Team Leaves</a></li>
    <li class="nav-item"><a href="manager_hr_leave_apply.php" class="nav-link active"><i class="fas fa-plane-departure"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="tasks_manager.php" class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    <li class="nav-item"><a href="manager_expenses.php" class="nav-link"><i class="fas fa-receipt"></i> Claims</a></li>
   <li class="nav-item"><a href="apply_grievance_manager.php" class="nav-link"><i class="fas fa-exclamation-circle"></i> Grievance</a></li>
  </ul>
  
  <div class="sidebar-footer">
    <ul style="list-style:none;padding:0">
      <li class="nav-item"><a href="logout.php" class="nav-link danger" onclick="return confirm('Are you sure you want to logout?')"><i class="fas fa-right-from-bracket"></i> Logout</a></li>
    </ul>
  </div>
</nav>

<!-- ═══ CONTENT ═══ -->
<div class="content" id="content">
  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>Manager</span>
      <i class="fas fa-chevron-right" style="font-size:9px;margin:0 2px"></i>
      <span>Leave</span>
      <i class="fas fa-chevron-right" style="font-size:9px;margin:0 2px"></i>
      <span class="current">Apply Leave</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($username, 0, 1)) ?></div>
      <span><?= h($username) ?></span>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">Leave Application</div>
        <div class="page-subtitle"><?= strtoupper($user_role) ?> · Submit leave directly to MD</div>
      </div>
      <a href="dashboard_manager.php" class="back-btn"><i class="fas fa-arrow-left" style="font-size:11px"></i> Back to Dashboard</a>
    </div>

    <?php if ($success): ?>
      <div class="alert-custom alert-success-custom"><i class="fas fa-check-circle" style="margin-top:1px"></i><span><?= h($success) ?></span></div>
    <?php endif; ?>
    <?php if ($error): ?>
      <div class="alert-custom alert-error-custom"><i class="fas fa-exclamation-circle" style="margin-top:1px"></i><span><?= h($error) ?></span></div>
    <?php endif; ?>

    <!-- Leave Form -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-plane-departure"></i> New Leave Request</div>
        <span style="font-size:11px;font-weight:600;background:#ede9fe;color:#5b21b6;padding:3px 10px;border-radius:20px">Sent to MD</span>
      </div>
      <div class="dash-card-body">
        <form method="POST" id="leaveForm">
          <div class="form-group" style="margin-bottom:16px">
            <label class="form-label">Leave Type <span>*</span></label>
            <select name="leave_type" class="form-control" required id="leaveTypeSelect" onchange="togglePermission()">
              <option value="">— Select Leave Type —</option>
              <option value="CL">CL – Casual Leave</option>
              <option value="PL">PL – Privilege Leave</option>
              <option value="SL">SL – Sick Leave</option>
              <option value="Compensatory">Compensatory Leave</option>
              <option value="Custom">Custom Leave</option>
              <option value="Permission">Permission</option>
            </select>
          </div>

          <div id="dateRangeSection">
            <div class="section-divider"><span>Leave Dates</span></div>
            <div class="form-grid" style="margin-bottom:16px">
              <div class="form-group">
                <label class="form-label">Start Date <span>*</span></label>
                <input type="date" name="start_date" class="form-control" required>
              </div>
              <div class="form-group">
                <label class="form-label">End Date <span>*</span></label>
                <input type="date" name="end_date" class="form-control" required>
              </div>
            </div>
          </div>

          <div id="permissionSection" style="display:none">
            <div class="section-divider"><span>Permission Details <span class="optional-badge">Optional for other types</span></span></div>
            <div class="form-grid-3" style="margin-bottom:16px">
              <div class="form-group">
                <label class="form-label">Permission Date</label>
                <input type="date" name="permission_date" class="form-control">
              </div>
              <div class="form-group">
                <label class="form-label">From Time</label>
                <input type="time" name="permission_time_from" class="form-control">
              </div>
              <div class="form-group">
                <label class="form-label">To Time</label>
                <input type="time" name="permission_time_to" class="form-control">
              </div>
            </div>
            <div class="form-group" style="max-width:200px;margin-bottom:16px">
              <label class="form-label">Permission Hours</label>
              <input type="number" step="0.25" name="permission_hours" class="form-control" placeholder="e.g. 2.5">
            </div>
          </div>

          <div class="section-divider"><span>Details</span></div>
          <div class="form-grid" style="margin-bottom:0">
            <div class="form-group">
              <label class="form-label">Reason <span>*</span></label>
              <textarea name="reason" class="form-control" placeholder="Reason for leave…" required></textarea>
            </div>
            <div class="form-group">
              <label class="form-label">Work Delegation <span class="optional-badge">Optional</span></label>
              <textarea name="work_description" class="form-control" placeholder="Who will handle your work?"></textarea>
            </div>
          </div>
          <div style="margin-top:20px">
            <button type="submit" class="btn-submit"><i class="fas fa-paper-plane"></i> Submit Leave Application</button>
          </div>
        </form>
      </div>
    </div>

    <!-- Leave History -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-history"></i> Leave History</div>
        <?php if ($history->num_rows > 0): ?>
          <span style="font-size:11px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 10px;border-radius:20px"><?= $history->num_rows ?> records</span>
        <?php endif; ?>
      </div>
      <div class="dash-card-body" style="padding:0">
        <?php if ($history->num_rows === 0): ?>
          <div class="empty-state"><i class="fas fa-clipboard-list"></i><p>No leave records found yet.</p></div>
        <?php else: ?>
          <div class="tbl-wrap">
            <table class="dash-table">
              <thead>
                <tr><th>Leave Type</th><th>Date / Time</th><th>Reason</th><th>Status</th><th>MD Comment</th><th>Applied On</th></tr>
              </thead>
              <tbody>
                <?php while ($row = $history->fetch_assoc()): ?>
                  <tr>
                    <td><span class="badge-custom badge-purple"><?= h($row['leave_type']) ?></span></td>
                    <td style="white-space:nowrap">
                      <?php if ($row['leave_type'] === 'Permission'): ?>
                        <div style="font-weight:600;font-size:13px"><?= h($row['permission_date'] ?? '—') ?></div>
                        <div style="font-size:11px;color:var(--muted);margin-top:2px"><?= h($row['permission_time_from'] ?? '') ?><?php if (!empty($row['permission_time_to'])): ?> → <?= h($row['permission_time_to']) ?><?php endif; ?><?php if (!empty($row['permission_hours'])): ?><span style="background:#f1f5f9;border-radius:4px;padding:1px 5px;margin-left:4px"><?= h($row['permission_hours']) ?> hrs</span><?php endif; ?></div>
                      <?php else: ?>
                        <div style="font-weight:600;font-size:13px"><?= h($row['start_date'] ?? '—') ?></div>
                        <div style="font-size:11px;color:var(--muted);margin-top:2px">→ <?= h($row['end_date'] ?? '—') ?></div>
                      <?php endif; ?>
                    </td>
                    <td style="max-width:180px;font-size:12px"><?= h($row['reason'] ?? '') ?></td>
                    <td>
                      <?php $st=$row['status']??''; $cls=$st==='Approved'?'badge-success':($st==='Rejected'?'badge-danger':'badge-warning'); $ico=$st==='Approved'?'fa-check-circle':($st==='Rejected'?'fa-times-circle':'fa-hourglass-half'); ?>
                      <span class="badge-custom <?= $cls ?>"><i class="fas <?= $ico ?>"></i> <?= h($st) ?></span>
                    </td>
                    <td style="font-size:12px;max-width:180px"><?= !empty($row['md_comment']) ? h($row['md_comment']) : '<span style="color:var(--muted);font-style:italic">Not reviewed yet</span>' ?></td>
                    <td style="font-size:12px;color:var(--muted);white-space:nowrap"><?= h($row['applied_on'] ?? '') ?></td>
                  </tr>
                <?php endwhile; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>
</div>

<script>
function toggleSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (!sb || !ov) return;
  const isOpen = sb.classList.contains('open');
  sb.classList.toggle('open', !isOpen);
  ov.classList.toggle('active', !isOpen);
}
function closeSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (sb) sb.classList.remove('open');
  if (ov) ov.classList.remove('active');
}
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') closeSidebar();
});
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('#sidebar .nav-link').forEach(function(a) {
    a.addEventListener('click', function() {
      if (window.innerWidth <= 768) closeSidebar();
    });
  });
});
function togglePermission() {
  const val = document.getElementById('leaveTypeSelect').value;
  document.getElementById('permissionSection').style.display = val === 'Permission' ? 'block' : 'none';
  document.getElementById('dateRangeSection').style.opacity = val === 'Permission' ? '0.5' : '1';
}
document.querySelector('[name="start_date"]').addEventListener('change', function () {
  const end = document.querySelector('[name="end_date"]');
  if (!end.value) end.value = this.value;
});
function calcPermHours() {
  const from = document.querySelector('[name="permission_time_from"]').value;
  const to   = document.querySelector('[name="permission_time_to"]').value;
  if (!from || !to) return;
  const [fh,fm] = from.split(':').map(Number);
  const [th,tm] = to.split(':').map(Number);
  const diff = ((th*60+tm)-(fh*60+fm))/60;
  if (diff>0) document.querySelector('[name="permission_hours"]').value = diff.toFixed(2);
}
document.querySelector('[name="permission_time_from"]').addEventListener('change', calcPermHours);
document.querySelector('[name="permission_time_to"]').addEventListener('change', calcPermHours);
</script>
</body>
</html>