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

session_start();
include 'config.php';

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

$conn->set_charset("utf8mb4");

$employee_id = $_SESSION['user_id'];
$username    = $_SESSION['username'] ?? 'User';
$reporting_manager_id = null;
$manager_warning = null;
$error   = null;
$success = isset($_GET['success']);

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

/*
 * ── GET REPORTING MANAGER ──
 * FIX: the old code read the employee's `reporting_manager` TEXT column
 * and tried to resolve it to a user by fuzzy-matching it against every
 * user's username OR "first_name last_name". That's fragile — it broke
 * on middle names, extra whitespace, or any name that wasn't stored
 * exactly the same way (e.g. "Artash Antony Raj" failing to match).
 *
 * More importantly, it was resolving the WRONG column: the admin
 * assignment panel (assign.php) only ever writes to reporting_manager_id
 * (the FK column), never to reporting_manager. So this page was
 * essentially guessing at a relationship that was already stored
 * directly, one column over.
 *
 * Fix: read reporting_manager_id directly off the employee's own row —
 * the exact column assign.php writes to and myteam.php reads from.
 * No text matching, no ambiguity.
 */
$stmt = $conn->prepare("SELECT reporting_manager_id FROM users WHERE id=?");
$stmt->bind_param("s", $employee_id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

$assigned_manager_id = trim($row['reporting_manager_id'] ?? '');

if ($assigned_manager_id !== '') {
    // Confirm the manager id still points at a real, active user
    // (handles the case where a manager account was later deactivated).
    $mgr_stmt = $conn->prepare("SELECT id, first_name, last_name FROM users WHERE id=? AND status='active' LIMIT 1");
    $mgr_stmt->bind_param("s", $assigned_manager_id);
    $mgr_stmt->execute();
    $mgr_row = $mgr_stmt->get_result()->fetch_assoc();
    $mgr_stmt->close();

    if (!empty($mgr_row['id'])) {
        $reporting_manager_id = $mgr_row['id']; // varchar(11), keep as string
    } else {
        $manager_warning = "Your assigned reporting manager's account could not be found or is inactive. Contact HR/Admin.";
    }
} else {
    $manager_warning = "No reporting manager assigned. Contact HR/Admin.";
}

/* ── DELEGATES ── */
$delegates = [];
$stmt = $conn->prepare("SELECT id, CONCAT(first_name,' ',last_name) AS name FROM users WHERE role='employee' AND id!=?");
$stmt->bind_param("s", $employee_id);
$stmt->execute();
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) $delegates[] = $r;
$stmt->close();

/* ── LEAVE BALANCE ── */
$leave_balance = ['CL' => 0, 'SL' => 0];
$stmt = $conn->prepare("SELECT leave_type, balance FROM leave_balance WHERE user_id=? AND leave_type IN('CL','SL')");
$stmt->bind_param("s", $employee_id);
$stmt->execute();
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) $leave_balance[$r['leave_type']] = (int)$r['balance'];
$stmt->close();

/* ── STATS ── */
$stmt = $conn->prepare("SELECT COUNT(*) total, SUM(status='Approved') approved, SUM(status='Rejected') rejected, SUM(status='Pending') pending FROM leave_requests WHERE employee_id=?");
$stmt->bind_param("s", $employee_id);
$stmt->execute();
$stats = array_map('intval', $stmt->get_result()->fetch_assoc());
$stmt->close();

/* ── SUBMIT ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $reporting_manager_id) {
    $type     = $_POST['leave_type'] ?? '';
    $reason   = trim($_POST['reason'] ?? '');
    $work     = trim($_POST['work_description'] ?? '');

    // FIX: delegate_to is a users.id (varchar) — don't require it to be
    // numeric. Just require it to be non-empty and fit the column.
    $delegateRaw = trim($_POST['delegate_to'] ?? '');
    $delegate    = ($delegateRaw !== '' && strlen($delegateRaw) <= 11) ? $delegateRaw : null;

    if (!$type)   { $error = "Select leave type"; }
    elseif (!$reason) { $error = "Reason required"; }

    if (!$error) {
        if ($type === 'Permission') {
            $date = $_POST['permission_date'] ?? '';
            $from = $_POST['time_from'] ?? '';
            $to   = $_POST['time_to'] ?? '';

            if (empty($date) || empty($from) || empty($to)) {
                $error = "All permission fields required";
            }

            if (!$error) {
                try {
                    $d1 = new DateTime("$date $from");
                    $d2 = new DateTime("$date $to");
                    if ($d2 <= $d1) { $error = "Invalid time range"; }
                    else {
                        $diff  = $d1->diff($d2);
                        $hours = $diff->h + ($diff->i / 60);
                        if ($hours <= 0 || $hours > 2) { $error = "Permission max 2 hours allowed"; }
                    }
                } catch (Exception $e) { $error = "Invalid time format"; }
            }

            if (!$error) {
                // FIX: reporting_manager_id and delegate_to are varchar(11)
                // (same as users.id) — bind as strings ("s"), not "i".
                $stmt = $conn->prepare("INSERT INTO leave_requests (employee_id,reporting_manager_id,delegate_to,leave_type,start_date,end_date,permission_date,permission_time_from,permission_time_to,permission_hours,reason,work_description,status,manager_status,hr_status,applied_on) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'Pending','Pending','Pending',NOW())");
                $stmt->bind_param("sssssssssdss", $employee_id, $reporting_manager_id, $delegate, $type, $date, $date, $date, $from, $to, $hours, $reason, $work);
                $stmt->execute();
                $stmt->close();
                header("Location: apply_leave.php?success=1");
                exit;
            }
        } else {
            $start = $_POST['start_date'] ?? '';
            $end   = $_POST['end_date'] ?? '';

            if (empty($start) || empty($end)) { $error = "Start and End date required"; }

            if (!$error) {
                try {
                    $d1 = new DateTime($start);
                    $d2 = new DateTime($end);
                    if ($d2 < $d1) { $error = "End date must be after start date"; }
                    else {
                        $days = $d1->diff($d2)->days + 1;
                        if (in_array($type, ['CL', 'SL']) && $days > $leave_balance[$type]) {
                            $error = "Insufficient $type balance";
                        }
                    }
                } catch (Exception $e) { $error = "Invalid date format"; }
            }

            if (!$error) {
                $stmt = $conn->prepare("INSERT INTO leave_requests (employee_id,reporting_manager_id,delegate_to,leave_type,start_date,end_date,reason,work_description,status,manager_status,hr_status,applied_on) VALUES (?,?,?,?,?,?,?,?,'Pending','Pending','Pending',NOW())");
                $stmt->bind_param("ssssssss", $employee_id, $reporting_manager_id, $delegate, $type, $start, $end, $reason, $work);
                $stmt->execute();
                $stmt->close();
                header("Location: apply_leave.php?success=1");
                exit;
            }
        }
    }
}

/* ── HISTORY ── */
$history = [];
$stmt = $conn->prepare("SELECT lr.*, CONCAT(u.first_name,' ',u.last_name) delegate_name FROM leave_requests lr LEFT JOIN users u ON lr.delegate_to=u.id WHERE lr.employee_id=? ORDER BY lr.applied_on DESC LIMIT 50");
$stmt->bind_param("s", $employee_id);
$stmt->execute();
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) $history[] = $r;
$stmt->close();
?>
<!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,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;1,9..40,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">
<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 ═══ */
.sidebar{
  width:var(--sidebar-w);background:var(--sidebar-bg);
  position:fixed;inset:0 auto 0 0;z-index:300;
  display:flex;flex-direction:column;overflow-y:auto;
  transition:transform .28s cubic-bezier(.4,0,.2,1);
  scrollbar-width:none;
}
.sidebar::-webkit-scrollbar{display:none}
.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:9px 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:16px;text-align:center;font-size:13px;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:12px 8px;border-top:1px solid rgba(255,255,255,.06)}
.sidebar-user-info{display:flex;align-items:center;gap:10px;padding:10px 14px;margin:0 8px 4px;border-radius:8px;background:rgba(255,255,255,.04)}
.sidebar-avatar{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-2));display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px;font-weight:700;flex-shrink:0}
.sidebar-uname{font-size:12px;font-weight:600;color:rgba(255,255,255,.8);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sidebar-role{font-size:10px;color:rgba(255,255,255,.35);text-transform:uppercase;letter-spacing:.8px}

/* ═══ OVERLAY ═══ */
.sidebar-overlay{
  display:none;position:fixed;inset:0;
  background:rgba(0,0,0,.55);z-index:290;
  backdrop-filter:blur(2px);
  transition:opacity .28s;opacity:0;
}
.sidebar-overlay.active{display:block;opacity:1}

/* ═══ CONTENT ═══ */
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column}
.topbar{height:56px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 18px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border)}
.hamburger-btn{width:36px;height:36px;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:15px;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);overflow:hidden}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600;font-size:13px;white-space:nowrap}
.topbar-breadcrumb span:not(.current){white-space:nowrap}
.topbar-spacer{flex:1}
.topbar-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink-2);font-weight:500;flex-shrink:0}
.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 ═══ */
.page{padding:18px;flex:1;max-width:100%}
.page-header{margin-bottom:18px;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:12px;color:var(--muted);margin-top:2px}

/* ═══ STAT CARDS ═══ */
.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 16px;box-shadow:var(--shadow);display:flex;align-items:center;gap:12px}
.stat-icon{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:15px;flex-shrink:0}
.stat-icon.blue{background:#dbeafe;color:#1d4ed8}
.stat-icon.green{background:#d1fae5;color:#059669}
.stat-icon.red{background:#fee2e2;color:#dc2626}
.stat-icon.amber{background:#fef3c7;color:#d97706}
.stat-label{font-size:10px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.stat-value{font-size:22px;font-weight:700;color:var(--ink);letter-spacing:-.5px;line-height:1.2}

/* ═══ BALANCE CARDS ═══ */
.balance-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px}
.balance-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 16px;box-shadow:var(--shadow);display:flex;align-items:center;justify-content:space-between}
.balance-label{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.balance-value{font-size:26px;font-weight:800;letter-spacing:-1px;color:var(--ink)}
.balance-sub{font-size:11px;color:var(--muted);margin-top:1px}
.balance-pill{width:44px;height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:800;flex-shrink:0}
.balance-pill.cl{background:linear-gradient(135deg,#4f46e5,#6366f1);color:#fff}
.balance-pill.sl{background:linear-gradient(135deg,#0891b2,#06b6d4);color:#fff}

/* ═══ DASH CARD ═══ */
.dash-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:16px;overflow:hidden}
.dash-card-header{padding:14px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
.dash-card-title{font-size:13px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:7px}
.dash-card-title i{color:var(--accent);font-size:12px}
.dash-card-body{padding:18px}

/* ═══ FORM ═══ */
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.form-grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px}
.form-group{display:flex;flex-direction:column;gap:5px}
.form-label{font-size:11px;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:14px;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 12px}
.section-divider span{font-size:10px;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;text-transform:none;margin-left:6px}
.btn-submit{width:100%;padding:12px 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:8px}
.btn-submit:hover{opacity:.92;transform:translateY(-1px)}
.btn-submit:active{transform:translateY(0)}
.btn-submit:disabled{opacity:.5;cursor:not-allowed;transform:none}

/* ═══ ALERTS ═══ */
.alert-custom{padding:12px 14px;border-radius:var(--radius-sm);font-size:13px;margin-bottom:14px;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}
.alert-warning-custom{background:#fef3c7;border-left:3px solid var(--amber);color:#78350f}

/* ═══ TABLE ═══ */
.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch}
.dash-table{width:100%;border-collapse:collapse;font-size:12.5px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:10px;text-transform:uppercase;letter-spacing:.6px;padding:10px 12px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:10px 12px;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}

/* ═══ BADGES ═══ */
.badge-custom{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:20px;font-size:10.5px;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}
.badge-blue{background:#dbeafe;color:#1e40af}

/* ═══ BACK BTN ═══ */
.back-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 14px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-sm);font-size:12px;font-weight:600;color:var(--ink-2);text-decoration:none;box-shadow:var(--shadow);transition:background .15s;white-space:nowrap}
.back-btn:hover{background:var(--bg);color:var(--ink)}

/* ═══ EMPTY STATE ═══ */
.empty-state{text-align:center;padding:40px 24px;color:var(--muted)}
.empty-state i{font-size:32px;display:block;margin-bottom:10px;opacity:.3}

/* ═══ RESPONSIVE ═══ */
@media(max-width:992px){
  .stats-grid{grid-template-columns:repeat(2,1fr)}
}
@media(max-width:768px){
  /* Sidebar slides out on mobile */
  .sidebar{transform:translateX(-100%)}
  .sidebar.open{transform:translateX(0)}
  .content{margin-left:0}
  .page{padding:14px}
  .stats-grid{grid-template-columns:repeat(2,1fr)}
  .form-grid,.form-grid-3,.balance-grid{grid-template-columns:1fr}
  .topbar-breadcrumb span:not(.current):not(:last-child){display:none}
  .page-header{flex-direction:column;gap:8px}
  .page-header .back-btn{align-self:flex-start}
}
@media(max-width:400px){
  .stats-grid{grid-template-columns:1fr 1fr}
  .stat-value{font-size:18px}
}
</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">Employee</div>
    </div>
  </div>

  <!-- User Info inside sidebar -->
  <div class="sidebar-user-info">
    <div class="sidebar-avatar"><?= strtoupper(substr($username, 0, 1)) ?></div>
    <div>
      <div class="sidebar-uname"><?= h($username) ?></div>
      <div class="sidebar-role">Employee</div>
    </div>
  </div>

  <div class="nav-group-label">Main</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="dashboard_employee.php" class="nav-link"><i class="fas fa-gauge-high"></i> Dashboard</a></li>
  </ul>
  <div class="nav-group-label">Work</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="apply_leave.php" class="nav-link active"><i class="fas fa-calendar-minus"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="expense.php" class="nav-link"><i class="fas fa-receipt"></i> Expenses</a></li>
    <li class="nav-item"><a href="tasks_employee.php" class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    <li class="nav-item"><a href="daily_report.php" class="nav-link"><i class="fas fa-file-lines"></i> Attendance &amp; Daily Report</a></li>
    <li class="nav-item"><a href="employee_grievance.php" class="nav-link"><i class="fas fa-exclamation-triangle"></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()" aria-label="Toggle menu">
      <i class="fas fa-bars"></i>
    </button>
    <div class="topbar-breadcrumb">
      <span>Employee</span>
      <i class="fas fa-chevron-right" style="font-size:8px;margin:0 2px;opacity:.5"></i>
      <span>Leave</span>
      <i class="fas fa-chevron-right" style="font-size:8px;margin:0 2px;opacity:.5"></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 style="display:none" class="d-sm-inline"><?= h($username) ?></span>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">Leave Application</div>
        <div class="page-subtitle">Submit leave to your reporting manager</div>
      </div>
      <a href="dashboard_employee.php" class="back-btn"><i class="fas fa-arrow-left" style="font-size:10px"></i> Dashboard</a>
    </div>

    <?php if ($manager_warning): ?>
      <div class="alert-custom alert-warning-custom"><i class="fas fa-exclamation-triangle" style="margin-top:1px;flex-shrink:0"></i><span><?= h($manager_warning) ?></span></div>
    <?php endif; ?>
    <?php if ($success): ?>
      <div class="alert-custom alert-success-custom"><i class="fas fa-check-circle" style="margin-top:1px;flex-shrink:0"></i><span>Leave application submitted successfully.</span></div>
    <?php endif; ?>
    <?php if ($error): ?>
      <div class="alert-custom alert-error-custom"><i class="fas fa-exclamation-circle" style="margin-top:1px;flex-shrink:0"></i><span><?= h($error) ?></span></div>
    <?php endif; ?>

    <!-- STATS -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-calendar-alt"></i></div>
        <div><div class="stat-label">Total</div><div class="stat-value"><?= $stats['total'] ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon green"><i class="fas fa-check-circle"></i></div>
        <div><div class="stat-label">Approved</div><div class="stat-value"><?= $stats['approved'] ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon red"><i class="fas fa-times-circle"></i></div>
        <div><div class="stat-label">Rejected</div><div class="stat-value"><?= $stats['rejected'] ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon amber"><i class="fas fa-hourglass-half"></i></div>
        <div><div class="stat-label">Pending</div><div class="stat-value"><?= $stats['pending'] ?></div></div>
      </div>
    </div>

    <!-- BALANCE -->
    <div class="balance-grid">
      <div class="balance-card">
        <div>
          <div class="balance-label">CL Balance</div>
          <div class="balance-value"><?= $leave_balance['CL'] ?></div>
          <div class="balance-sub">Casual Leave days remaining</div>
        </div>
        <div class="balance-pill cl">CL</div>
      </div>
      <div class="balance-card">
        <div>
          <div class="balance-label">SL Balance</div>
          <div class="balance-value"><?= $leave_balance['SL'] ?></div>
          <div class="balance-sub">Sick Leave days remaining</div>
        </div>
        <div class="balance-pill sl">SL</div>
      </div>
    </div>

    <!-- 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:10px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 9px;border-radius:20px">→ Manager</span>
      </div>
      <div class="dash-card-body">
        <form method="POST" id="leaveForm">

          <div class="form-group" style="margin-bottom:14px">
            <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="SL">SL – Sick 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:14px">
              <div class="form-group">
                <label class="form-label">Start Date <span>*</span></label>
                <input type="date" name="start_date" class="form-control">
              </div>
              <div class="form-group">
                <label class="form-label">End Date <span>*</span></label>
                <input type="date" name="end_date" class="form-control">
              </div>
            </div>
          </div>

          <div id="permissionSection" style="display:none">
            <div class="section-divider"><span>Permission Details</span></div>
            <div class="form-grid-3" style="margin-bottom:14px">
              <div class="form-group">
                <label class="form-label">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="time_from" class="form-control" id="permFrom">
              </div>
              <div class="form-group">
                <label class="form-label">To Time</label>
                <input type="time" name="time_to" class="form-control" id="permTo">
              </div>
            </div>
            <div style="background:#fef3c7;border:1px solid #fde68a;border-radius:var(--radius-sm);padding:10px 12px;font-size:12px;color:#78350f;margin-bottom:14px">
              <i class="fas fa-info-circle" style="margin-right:5px"></i>Maximum permission: <strong>2 hours</strong> per request.
            </div>
          </div>

          <div class="section-divider"><span>Details</span></div>
          <div class="form-grid" style="margin-bottom:12px">
            <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 Description<span class="optional-badge">Optional</span></label>
              <textarea name="work_description" class="form-control" placeholder="Who will handle your work?"></textarea>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">Delegate To<span class="optional-badge">Optional</span></label>
            <select name="delegate_to" class="form-control">
              <option value="">— Select a colleague —</option>
              <?php foreach ($delegates as $d): ?>
                <option value="<?= h($d['id']) ?>"><?= h($d['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <button type="submit" class="btn-submit" <?= $reporting_manager_id ? '' : 'disabled' ?>><i class="fas fa-paper-plane"></i> Submit Leave Application</button>
        </form>
      </div>
    </div>

    <!-- 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 (!empty($history)): ?>
          <span style="font-size:10px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 9px;border-radius:20px"><?= count($history) ?> records</span>
        <?php endif; ?>
      </div>
      <div class="dash-card-body" style="padding:0">
        <?php if (empty($history)): ?>
          <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>#</th>
                  <th>Type</th>
                  <th>Date / Time</th>
                  <th>Delegate</th>
                  <th>Reason</th>
                  <th>Manager</th>
                  <th>HR</th>
                  <th>Status</th>
                  <th>Comments</th>
                  <th>Applied</th>
                </tr>
              </thead>
              <tbody>
                <?php $i = 1; foreach ($history as $row): ?>
                  <tr>
                    <td style="color:var(--muted);font-size:11px"><?= $i++ ?></td>
                    <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"><?= h($row['permission_date'] ?? '—') ?></div>
                        <div style="font-size:11px;color:var(--muted);margin-top:1px"><?= h($row['permission_time_from'] ?? '') ?><?php if (!empty($row['permission_time_to'])): ?> → <?= h($row['permission_time_to']) ?><?php endif; ?></div>
                      <?php else: ?>
                        <div style="font-weight:600"><?= h($row['start_date'] ?? '—') ?></div>
                        <div style="font-size:11px;color:var(--muted);margin-top:1px">→ <?= h($row['end_date'] ?? '—') ?></div>
                      <?php endif; ?>
                    </td>
                    <td style="font-size:11px"><?= !empty($row['delegate_name']) ? h($row['delegate_name']) : '<span style="color:var(--muted)">—</span>' ?></td>
                    <td style="max-width:140px;font-size:11px"><?= h($row['reason'] ?? '') ?></td>
                    <td>
                      <?php $ms = $row['manager_status'] ?? 'Pending'; $mc = $ms === 'Approved' ? 'badge-success' : ($ms === 'Rejected' ? 'badge-danger' : 'badge-warning'); ?>
                      <span class="badge-custom <?= $mc ?>"><?= h($ms) ?></span>
                    </td>
                    <td>
                      <?php $hs = $row['hr_status'] ?? 'Pending'; $hc = $hs === 'Approved' ? 'badge-success' : ($hs === 'Rejected' ? 'badge-danger' : 'badge-warning'); ?>
                      <span class="badge-custom <?= $hc ?>"><?= h($hs) ?></span>
                    </td>
                    <td>
                      <?php $st = $row['status'] ?? 'Pending'; $sc = $st === 'Approved' ? 'badge-success' : ($st === 'Rejected' ? 'badge-danger' : 'badge-warning'); $si = $st === 'Approved' ? 'fa-check-circle' : ($st === 'Rejected' ? 'fa-times-circle' : 'fa-hourglass-half'); ?>
                      <span class="badge-custom <?= $sc ?>"><i class="fas <?= $si ?>"></i> <?= h($st) ?></span>
                    </td>
                    <td style="font-size:11px;max-width:150px">
                      <?php
                        $printed = false;
                        if (!empty($row['manager_comment'])) { echo '<strong>Mgr:</strong> ' . h($row['manager_comment']) . '<br>'; $printed = true; }
                        if (!empty($row['hr_comment']))      { echo '<strong>HR:</strong> '   . h($row['hr_comment']);              $printed = true; }
                        if (!$printed) echo '<span style="color:var(--muted);font-style:italic">—</span>';
                      ?>
                    </td>
                    <td style="font-size:11px;color:var(--muted);white-space:nowrap"><?= h($row['applied_on'] ?? '') ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>

  </div>
</div>
</div>

<script>
function toggleSidebar() {
  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('sidebarOverlay');
  const isOpen  = sidebar.classList.contains('open');
  if (isOpen) {
    sidebar.classList.remove('open');
    overlay.classList.remove('active');
  } else {
    sidebar.classList.add('open');
    overlay.classList.add('active');
  }
}

function closeSidebar() {
  document.getElementById('sidebar').classList.remove('open');
  document.getElementById('sidebarOverlay').classList.remove('active');
}

// Close sidebar on Escape key
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeSidebar(); });

function togglePermission() {
  const val = document.getElementById('leaveTypeSelect').value;
  const isPerm = val === 'Permission';
  document.getElementById('permissionSection').style.display = isPerm ? 'block' : 'none';
  document.getElementById('dateRangeSection').style.opacity  = isPerm ? '0.35' : '1';
  document.getElementById('dateRangeSection').style.pointerEvents = isPerm ? 'none' : 'auto';
}

document.querySelector('[name="start_date"]').addEventListener('change', function () {
  const end = document.querySelector('[name="end_date"]');
  if (!end.value) end.value = this.value;
});
</script>
</body>
</html>