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

session_start();
require_once 'config.php';

if (!$conn) { die("Database connection failed!"); }

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

$employee_id = $_SESSION['user_id'];
$username    = $_SESSION['username'] ?? 'Unknown User';

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

/* ── SUBMIT ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_expense'])) {
    $expense_date = trim($_POST['expense_date']);
    $amount       = floatval($_POST['amount']);
    $description  = trim($_POST['description']);
    $category     = trim($_POST['category']);

    if (empty($expense_date) || $amount <= 0 || empty($description)) {
        $_SESSION['error_message'] = "Please fill all required fields correctly.";
    } else {
        $target_dir = "uploads/expenses/";
        if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);

        $file_extension = pathinfo($_FILES["bill_image"]["name"], PATHINFO_EXTENSION);
        $new_filename   = 'expense_' . $employee_id . '_' . time() . '.' . $file_extension;
        $target_file    = $target_dir . $new_filename;
        $uploadOk       = 1;
        $imageFileType  = strtolower($file_extension);

        if ($_FILES["bill_image"]["error"] === UPLOAD_ERR_OK) {
            if (getimagesize($_FILES["bill_image"]["tmp_name"]) === false) {
                $_SESSION['error_message'] = "File is not an image."; $uploadOk = 0;
            }
            if ($_FILES["bill_image"]["size"] > 5000000) {
                $_SESSION['error_message'] = "File too large. Max 5MB."; $uploadOk = 0;
            }
            if (!in_array($imageFileType, ['jpg','jpeg','png','gif'])) {
                $_SESSION['error_message'] = "Only JPG, JPEG, PNG, GIF allowed."; $uploadOk = 0;
            }
        } else {
            $_SESSION['error_message'] = "File upload error."; $uploadOk = 0;
        }

        if ($uploadOk == 1) {
            if (move_uploaded_file($_FILES["bill_image"]["tmp_name"], $target_file)) {
                $sql  = "INSERT INTO expenses (employee_id, employee_name, expense_date, amount, description, category, bill_image, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                $stmt = $conn->prepare($sql);
                if ($stmt) {
                    $status = 'pending';
                    $stmt->bind_param("sssdssss", $employee_id, $username, $expense_date, $amount, $description, $category, $target_file, $status);
                    if ($stmt->execute()) {
                        $_SESSION['success_message'] = "Expense ₹" . number_format($amount, 2) . " submitted successfully!";
                    } else {
                        $_SESSION['error_message'] = "Database error: " . $conn->error;
                        unlink($target_file);
                    }
                    $stmt->close();
                } else {
                    $_SESSION['error_message'] = "Prepare failed: " . $conn->error;
                    unlink($target_file);
                }
            } else {
                $_SESSION['error_message'] = "Upload failed.";
            }
        }
    }
    header("Location: expense.php");
    exit();
}

/* ── FETCH EXPENSES ── */
$sql  = "SELECT id, expense_date, amount, description, category, bill_image, status, created_at FROM expenses WHERE employee_id = ? ORDER BY created_at DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $employee_id);
$stmt->execute();
$result_expenses = $stmt->get_result();
$stmt->close();

$total_pending = $total_approved = $total_rejected = $total_amount = 0;
$expenses = [];
while ($row = $result_expenses->fetch_assoc()) {
    $expenses[] = $row;
    $total_amount += $row['amount'];
    switch ($row['status']) {
        case 'pending':  $total_pending++;  break;
        case 'approved': $total_approved++; break;
        case 'rejected': $total_rejected++; break;
    }
}

$success_msg = $_SESSION['success_message'] ?? null; unset($_SESSION['success_message']);
$error_msg   = $_SESSION['error_message']   ?? null; unset($_SESSION['error_message']);
?>
<!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 · Expenses</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&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-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:20px;font-weight:700;color:var(--ink);letter-spacing:-.5px;line-height:1.2}

/* ═══ 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-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:90px;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)}
.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)}
input[type="file"].form-control{padding:7px 12px;cursor:pointer}

/* ═══ 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}

/* ═══ 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:middle}
.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-slate{background:#f1f5f9;color:#475569}

/* ═══ BILL THUMBNAIL ═══ */
.bill-thumb{width:38px;height:38px;object-fit:cover;border-radius:7px;border:1px solid var(--border);cursor:pointer;transition:transform .15s,box-shadow .15s}
.bill-thumb:hover{transform:scale(1.1);box-shadow:var(--shadow-md)}

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

/* ═══ 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)}

/* ═══ RESPONSIVE ═══ */
@media(max-width:992px){.stats-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:768px){
  .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{grid-template-columns:1fr}
  .page-header{flex-direction:column;gap:8px}
}
</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>

  <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"><i class="fas fa-calendar-minus"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="expense.php" class="nav-link active"><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>Finance</span>
      <i class="fas fa-chevron-right" style="font-size:8px;margin:0 2px;opacity:.5"></i>
      <span class="current">Expenses</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($username, 0, 1)) ?></div>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">Expense Management</div>
        <div class="page-subtitle">Submit and track your expense claims</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 ($success_msg): ?>
      <div class="alert-custom alert-success-custom"><i class="fas fa-check-circle" style="flex-shrink:0"></i><span><?= h($success_msg) ?></span></div>
    <?php endif; ?>
    <?php if ($error_msg): ?>
      <div class="alert-custom alert-error-custom"><i class="fas fa-exclamation-circle" style="flex-shrink:0"></i><span><?= h($error_msg) ?></span></div>
    <?php endif; ?>

    <!-- STATS -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-rupee-sign"></i></div>
        <div><div class="stat-label">Total</div><div class="stat-value" style="font-size:16px">₹<?= number_format($total_amount, 0) ?></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"><?= $total_pending ?></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"><?= $total_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"><?= $total_rejected ?></div></div>
      </div>
    </div>

    <!-- FORM -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-plus-circle"></i> New Expense 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" enctype="multipart/form-data">
          <div class="section-divider"><span>Expense Details</span></div>
          <div class="form-grid" style="margin-bottom:12px">
            <div class="form-group">
              <label class="form-label">Expense Date <span>*</span></label>
              <input type="date" name="expense_date" class="form-control" required value="<?= date('Y-m-d') ?>">
            </div>
            <div class="form-group">
              <label class="form-label">Amount (₹) <span>*</span></label>
              <input type="number" name="amount" class="form-control" step="0.01" min="0.01" placeholder="0.00" required>
            </div>
            <div class="form-group">
              <label class="form-label">Category <span>*</span></label>
              <select name="category" class="form-control" required>
                <option value="">— Select Category —</option>
                <option value="Travel">Travel</option>
                <option value="Meals">Meals</option>
                <option value="Office Supplies">Office Supplies</option>
                <option value="Communication">Communication</option>
                <option value="Client Meeting">Client Meeting</option>
                <option value="General">General</option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">Bill / Receipt <span>*</span></label>
              <input type="file" name="bill_image" class="form-control" accept="image/*" required>
              <span style="font-size:11px;color:var(--muted);margin-top:3px">JPG, PNG, GIF · Max 5 MB</span>
            </div>
          </div>

          <div class="section-divider"><span>Description</span></div>
          <div class="form-group">
            <label class="form-label">Description <span>*</span></label>
            <textarea name="description" class="form-control" placeholder="Enter expense details…" required></textarea>
          </div>

          <button type="submit" name="submit_expense" class="btn-submit"><i class="fas fa-paper-plane"></i> Submit Expense</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> Expense History</div>
        <?php if (!empty($expenses)): ?>
          <span style="font-size:10px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 9px;border-radius:20px"><?= count($expenses) ?> records</span>
        <?php endif; ?>
      </div>
      <div class="dash-card-body" style="padding:0">
        <?php if (empty($expenses)): ?>
          <div class="empty-state"><i class="fas fa-receipt"></i><p>No expenses yet.</p></div>
        <?php else: ?>
          <div class="tbl-wrap">
            <table class="dash-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Date</th>
                  <th>Amount</th>
                  <th>Category</th>
                  <th>Description</th>
                  <th>Bill</th>
                  <th>Status</th>
                  <th>Applied</th>
                </tr>
              </thead>
              <tbody>
                <?php $i = 1; foreach ($expenses as $exp): ?>
                  <?php
                    $st = $exp['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');
                  ?>
                  <tr>
                    <td style="color:var(--muted);font-size:11px"><?= $i++ ?></td>
                    <td style="font-weight:600;white-space:nowrap;font-size:12px"><?= h(date("d M Y", strtotime($exp['expense_date']))) ?></td>
                    <td style="font-weight:700;color:var(--ink);white-space:nowrap">₹<?= number_format($exp['amount'], 2) ?></td>
                    <td><span class="badge-custom badge-slate"><?= h($exp['category']) ?></span></td>
                    <td style="max-width:140px;font-size:11px;color:var(--ink-2)"><?= h(mb_strimwidth($exp['description'], 0, 45, '…')) ?></td>
                    <td>
                      <?php if (!empty($exp['bill_image']) && file_exists($exp['bill_image'])): ?>
                        <img src="<?= h($exp['bill_image']) ?>" class="bill-thumb" onclick="window.open(this.src,'_blank')" title="View bill">
                      <?php else: ?>
                        <span style="font-size:11px;color:var(--muted)">—</span>
                      <?php endif; ?>
                    </td>
                    <td><span class="badge-custom <?= $sc ?>"><i class="fas <?= $si ?>"></i> <?= ucfirst(h($st)) ?></span></td>
                    <td style="font-size:11px;color:var(--muted);white-space:nowrap"><?= h(date("d M Y", strtotime($exp['created_at']))) ?></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');
  if (sidebar.classList.contains('open')) {
    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');
}
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeSidebar(); });
</script>
</body>
</html>
<?php $conn->close(); ?>