<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Auth check — manager only
if (!isset($_SESSION['user_id']) || strtolower($_SESSION['role']) !== 'manager') {
    header('Location: index.php');
    exit();
}

require_once 'config.php';

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

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

$employee_id = $_SESSION['user_id'];
$username    = $_SESSION['username'] ?? 'Manager';

// Fetch manager full name
$stmt = $conn->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
$stmt->bind_param("s", $employee_id);
$stmt->execute();
$me = $stmt->get_result()->fetch_assoc();
$stmt->close();
$manager_name = trim(($me['first_name'] ?? '') . ' ' . ($me['last_name'] ?? ''));
if (!$manager_name) $manager_name = $username;

// ── FORM SUBMISSION ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_expense'])) {
    $expense_date = trim($_POST['expense_date'] ?? '');
    $amount       = floatval($_POST['amount'] ?? 0);
    $description  = trim($_POST['description'] ?? '');
    $category     = trim($_POST['category'] ?? 'General');

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

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

        if ($_FILES["bill_image"]["error"] === UPLOAD_ERR_OK) {
            if (getimagesize($_FILES["bill_image"]["tmp_name"]) === false) {
                $_SESSION['exp_error'] = "Uploaded file is not a valid image.";
                $uploadOk = 0;
            }
            if ($_FILES["bill_image"]["size"] > 5000000) {
                $_SESSION['exp_error'] = "File too large. Maximum allowed size is 5MB.";
                $uploadOk = 0;
            }
            if (!in_array($file_extension, ['jpg','jpeg','png','gif'])) {
                $_SESSION['exp_error'] = "Only JPG, JPEG, PNG, and GIF files are allowed.";
                $uploadOk = 0;
            }
        } else {
            $_SESSION['exp_error'] = "File upload error. Please try again.";
            $uploadOk = 0;
        }

        if ($uploadOk && 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,
                    $manager_name,
                    $expense_date,
                    $amount,
                    $description,
                    $category,
                    $target_file,
                    $status
                );
                if ($stmt->execute()) {
                    $_SESSION['exp_success'] = "Expense of ₹" . number_format($amount, 2) . " submitted successfully!";
                } else {
                    $_SESSION['exp_error'] = "Database error: " . $conn->error;
                    unlink($target_file);
                }
                $stmt->close();
            } else {
                $_SESSION['exp_error'] = "Prepare failed: " . $conn->error;
                unlink($target_file);
            }
        } elseif ($uploadOk) {
            $_SESSION['exp_error'] = "Failed to move uploaded file.";
        }
    }
    header('Location: manager_expenses.php');
    exit();
}

// ── FETCH EXPENSES ──
$expenses = [];
$hstmt = $conn->prepare("SELECT id, expense_date, amount, description, category, bill_image, status, created_at
                          FROM expenses WHERE employee_id = ? ORDER BY created_at DESC");
if ($hstmt) {
    $hstmt->bind_param("s", $employee_id);
    $hstmt->execute();
    $expenses = $hstmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $hstmt->close();
}

// ── STATS ──
$total_pending = $total_approved = $total_rejected = $total_amount = 0;
foreach ($expenses as $e) {
    $total_amount += $e['amount'];
    match($e['status']) {
        'pending'  => $total_pending++,
        'approved' => $total_approved++,
        'rejected' => $total_rejected++,
        default    => null
    };
}
$total_count = count($expenses);
?>
<!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 · Expense Claims</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">
<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);
  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 ─── */
.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 ─── */
.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 ─── */
.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}

/* ─── STATS ─── */
.stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px;box-shadow:var(--shadow);display:flex;align-items:center;gap:13px;border-left:4px solid transparent}
.stat-card.c-blue{border-color:var(--accent)}
.stat-card.c-amber{border-color:var(--amber)}
.stat-card.c-red{border-color:var(--red)}
.stat-card.c-green{border-color:var(--green)}
.stat-icon{width:42px;height:42px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
.c-blue .stat-icon{background:#eff6ff;color:var(--accent)}
.c-amber .stat-icon{background:#fef3c7;color:var(--amber)}
.c-red .stat-icon{background:#fee2e2;color:var(--red)}
.c-green .stat-icon{background:#d1fae5;color:var(--green)}
.stat-num{font-size:22px;font-weight:800;color:var(--ink);line-height:1;font-family:'DM Mono',monospace}
.stat-lbl{font-size:11px;color:var(--muted);margin-top:3px;font-weight:500}

/* ─── DASH CARD ─── */
.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 ─── */
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.form-group{display:flex;flex-direction:column;gap:5px;margin-bottom:16px}
.form-label{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.form-label .req{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:110px;line-height:1.6}
.file-hint{font-size:11px;color:var(--muted);margin-top:4px}
.section-divider{display:flex;align-items:center;gap:10px;margin:4px 0 16px}
.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)}

/* ─── BUTTONS ─── */
.btn-submit{padding:11px 28px;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:inline-flex;align-items:center;gap:8px}
.btn-submit:hover{opacity:.92;transform:translateY(-1px)}
.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}

/* ─── ALERTS ─── */
.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}

/* ─── TABLE ─── */
.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: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 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-secondary{background:#f1f5f9;color:#475569}

/* ─── BILL IMAGE ─── */
.bill-thumb{width:44px;height:44px;object-fit:cover;border-radius:6px;cursor:pointer;border:1px solid var(--border);transition:transform .15s,box-shadow .15s}
.bill-thumb:hover{transform:scale(1.08);box-shadow:0 4px 12px rgba(15,23,42,.15)}

/* ─── AMOUNT HIGHLIGHT ─── */
.amount-val{font-family:'DM Mono',monospace;font-weight:700;color:var(--ink);font-size:13px}

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

@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}
  .content{margin-left:0}.page{padding:14px}
  .form-grid{grid-template-columns:1fr}
  .stats-row{grid-template-columns:repeat(2,1fr)}
  .page-header{flex-direction:column}
}


/* ═══ 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"><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 class="current">Expense Claims</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($manager_name, 0, 1)) ?></div>
      <span><?= h($manager_name) ?></span>
    </div>
  </div>

  <div class="page">

    <!-- Header -->
    <div class="page-header">
      <div>
        <div class="page-title">
          <i class="fas fa-receipt" style="color:var(--accent);margin-right:8px;font-size:18px"></i>Expense Claims
        </div>
        <div class="page-subtitle"><?= date('l, F j, Y') ?> · Submit and track your expense claims</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>

    <!-- Alerts -->
    <?php if (isset($_SESSION['exp_success'])): ?>
      <div class="alert-custom alert-success-custom">
        <i class="fas fa-check-circle" style="margin-top:1px"></i>
        <span><?= h($_SESSION['exp_success']); unset($_SESSION['exp_success']); ?></span>
      </div>
    <?php endif; ?>
    <?php if (isset($_SESSION['exp_error'])): ?>
      <div class="alert-custom alert-error-custom">
        <i class="fas fa-exclamation-circle" style="margin-top:1px"></i>
        <span><?= h($_SESSION['exp_error']); unset($_SESSION['exp_error']); ?></span>
      </div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-row">
      <div class="stat-card c-blue">
        <div class="stat-icon"><i class="fas fa-file-invoice-dollar"></i></div>
        <div>
          <div class="stat-num">₹<?= number_format($total_amount, 0) ?></div>
          <div class="stat-lbl">Total Claimed</div>
        </div>
      </div>
      <div class="stat-card c-amber">
        <div class="stat-icon"><i class="fas fa-hourglass-half"></i></div>
        <div>
          <div class="stat-num"><?= $total_pending ?></div>
          <div class="stat-lbl">Pending</div>
        </div>
      </div>
      <div class="stat-card c-green">
        <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
        <div>
          <div class="stat-num"><?= $total_approved ?></div>
          <div class="stat-lbl">Approved</div>
        </div>
      </div>
      <div class="stat-card c-red">
        <div class="stat-icon"><i class="fas fa-times-circle"></i></div>
        <div>
          <div class="stat-num"><?= $total_rejected ?></div>
          <div class="stat-lbl">Rejected</div>
        </div>
      </div>
    </div>

    <!-- Expense Form -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title">
          <i class="fas fa-plus-circle"></i> Submit New Expense
        </div>
        <span style="font-size:11px;font-weight:600;background:#ede9fe;color:#5b21b6;padding:3px 12px;border-radius:20px">
          <?= $total_count ?> claim<?= $total_count !== 1 ? 's' : '' ?> submitted
        </span>
      </div>
      <div class="dash-card-body">
        <form action="manager_expenses.php" method="POST" enctype="multipart/form-data">

          <div class="section-divider"><span>Expense Details</span></div>

          <div class="form-grid" style="margin-bottom:0">
            <div class="form-group">
              <label class="form-label">Date <span class="req">*</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 class="req">*</span></label>
              <input type="number" name="amount" class="form-control" step="0.01" min="0.01" required placeholder="0.00">
            </div>
            <div class="form-group">
              <label class="form-label">Category <span class="req">*</span></label>
              <select name="category" class="form-control" required>
                <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 class="req">*</span></label>
              <input type="file" name="bill_image" class="form-control" accept="image/*" required>
              <span class="file-hint"><i class="fas fa-info-circle"></i> JPG, PNG, GIF · Max 5MB</span>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">Description <span class="req">*</span></label>
            <textarea name="description" class="form-control" required placeholder="Describe the expense — include purpose, vendor, and any relevant details…"></textarea>
          </div>

          <div style="display:flex;justify-content:flex-end;margin-top:4px">
            <button type="submit" name="submit_expense" class="btn-submit">
              <i class="fas fa-paper-plane"></i> Submit Expense
            </button>
          </div>

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

    <!-- Expense 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 ($total_count > 0): ?>
          <span style="font-size:11px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 10px;border-radius:20px">
            <?= $total_count ?> record<?= $total_count !== 1 ? 's' : '' ?>
          </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 submitted yet. Add your first claim above!</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>Submitted</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($expenses as $i => $e):
                  $st  = $e['status'] ?? 'pending';
                  $cls = match($st) {
                    'approved' => 'badge-success',
                    'rejected' => 'badge-danger',
                    default    => 'badge-warning'
                  };
                  $ico = match($st) {
                    'approved' => 'fa-check-circle',
                    'rejected' => 'fa-times-circle',
                    default    => 'fa-hourglass-half'
                  };
                ?>
                <tr>
                  <td style="color:var(--muted);font-family:'DM Mono',monospace;font-size:12px;width:36px"><?= $i + 1 ?></td>
                  <td style="white-space:nowrap;font-size:13px">
                    <?= date('d M Y', strtotime($e['expense_date'])) ?>
                  </td>
                  <td>
                    <span class="amount-val">₹<?= number_format($e['amount'], 2) ?></span>
                  </td>
                  <td>
                    <span class="badge-custom badge-secondary">
                      <?= h($e['category']) ?>
                    </span>
                  </td>
                  <td style="max-width:220px">
                    <span style="font-size:12px;color:var(--muted)" title="<?= h($e['description']) ?>">
                      <?= h(mb_substr($e['description'], 0, 60)) ?><?= mb_strlen($e['description']) > 60 ? '…' : '' ?>
                    </span>
                  </td>
                  <td>
                    <?php if (!empty($e['bill_image']) && file_exists($e['bill_image'])): ?>
                      <img src="<?= h($e['bill_image']) ?>"
                           class="bill-thumb"
                           onclick="window.open(this.src, '_blank')"
                           title="Click to view full image"
                           alt="Bill">
                    <?php else: ?>
                      <span style="font-size:12px;color:var(--muted)">—</span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <span class="badge-custom <?= $cls ?>">
                      <i class="fas <?= $ico ?>"></i> <?= ucfirst(h($st)) ?>
                    </span>
                  </td>
                  <td style="white-space:nowrap;font-size:12px;color:var(--muted)">
                    <?= date('d M Y', strtotime($e['created_at'])) ?><br>
                    <span style="font-size:11px"><?= date('h:i A', strtotime($e['created_at'])) ?></span>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>

  </div><!-- /page -->
</div><!-- /content -->
</div><!-- /layout -->

<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();
    });
  });
});
</script>
</body>
</html>
<?php $conn->close(); ?>