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

if (!file_exists('config.php')) die("Config file missing.");
require_once 'config.php';
if ($conn->connect_error) die("DB connection failed: " . $conn->connect_error);

if (
    !isset($_SESSION['user_id'], $_SESSION['role']) ||
    !in_array($_SESSION['role'], ['hr', 'superadmin', 'md'])
) {
    header("Location: login.php");
    exit;
}

$hr_id       = $_SESSION['user_id'];
$hr_username = $_SESSION['username'] ?? 'Admin';
$hr_role     = $_SESSION['role'];
$success_msg = "";
$error_msg   = "";

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['advance_id'])) {
    $advance_id = (int)$_POST['advance_id'];
    $action     = $_POST['action'] ?? '';
    $safe_remarks = trim($_POST['remarks'] ?? '');

    if ($action === 'reject') {
        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("UPDATE salary_advances SET approval_status='Rejected', remarks=? WHERE advance_id=? AND approval_status='Pending'");
            $stmt->bind_param('si', $safe_remarks, $advance_id);
            $stmt->execute();
            if ($stmt->affected_rows > 0) {
                $msg = "Your salary advance request was REJECTED.\nReason: $safe_remarks";
                $n = $conn->prepare("INSERT INTO notifications (employee_id, message, type, created_at) SELECT employee_id, ?, 'salary_advance', NOW() FROM salary_advances WHERE advance_id=?");
                $n->bind_param('si', $msg, $advance_id);
                $n->execute(); $n->close();
                $conn->commit();
                $success_msg = "Request rejected.";
            } else { $conn->rollback(); $error_msg = "Already processed or invalid request."; }
            $stmt->close();
        } catch (Exception $e) { $conn->rollback(); $error_msg = "Reject Error: " . $e->getMessage(); }
    } elseif ($action === 'approve') {
        $installments = max(1, min(24, (int)($_POST['installments'] ?? 3)));
        $start_raw = $_POST['repayment_start'] ?? date('Y-m', strtotime('+1 month'));
        $repayment_start_date = preg_match('/^\d{4}-\d{2}$/', $start_raw) ? $start_raw . "-01" : date('Y-m-01', strtotime('+1 month'));

        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("SELECT sa.*, u.username FROM salary_advances sa JOIN users u ON sa.employee_id = u.id WHERE sa.advance_id=? AND sa.approval_status='Pending' LIMIT 1");
            $stmt->bind_param('i', $advance_id);
            $stmt->execute();
            $req = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if (!$req) { $conn->rollback(); $error_msg = "Already processed or invalid request."; }
            else {
                $amount  = (float)$req['amount'];
                $monthly = round($amount / $installments, 2);
                $upd = $conn->prepare("UPDATE salary_advances SET approval_status='Approved', installments=?, monthly_deduction=?, repayment_start_date=?, approved_by=?, approved_at=NOW(), remarks=? WHERE advance_id=? AND approval_status='Pending'");
                $upd->bind_param('idsssi', $installments, $monthly, $repayment_start_date, $hr_username, $safe_remarks, $advance_id);
                $upd->execute(); $upd->close();
                $msg = "Your salary advance of ₹" . number_format($amount, 2) . " has been APPROVED.\nMonthly deduction: ₹" . number_format($monthly, 2) . " × $installments months";
                $emp_id = (int)$req['employee_id'];
                $n = $conn->prepare("INSERT INTO notifications (employee_id, message, type, created_at) VALUES (?, ?, 'salary_advance', NOW())");
                $n->bind_param('is', $emp_id, $msg);
                $n->execute(); $n->close();
                $conn->commit();
                $success_msg = "Advance approved successfully.";
            }
        } catch (Exception $e) { $conn->rollback(); $error_msg = "Approve Error: " . $e->getMessage(); }
    }
}

$search        = trim($_GET['search'] ?? '');
$status_filter = $_GET['status'] ?? 'all';
$where = ["sa.approval_status != 'Cancelled'"]; $params = []; $types = "";

if ($search !== '') { $like = "%$search%"; $where[] = "(u.username LIKE ? OR sa.employee_id LIKE ? OR u.email LIKE ?)"; $params = array_merge($params, [$like, $like, $like]); $types .= 'sss'; }
if ($status_filter !== 'all') { $where[] = "sa.approval_status = ?"; $params[] = $status_filter; $types .= 's'; }
$where_clause = implode(" AND ", $where);

$sql = "SELECT sa.*, u.username, u.email, u.division FROM salary_advances sa JOIN users u ON sa.employee_id = u.id WHERE $where_clause ORDER BY sa.created_at DESC";
$stmt = $conn->prepare($sql);
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$requests = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$stats = ['pending'=>0,'approved'=>0,'rejected'=>0,'total'=>count($requests)];
foreach ($requests as $r) {
    $s = strtolower($r['approval_status']);
    if (isset($stats[$s])) $stats[$s]++;
}

ob_end_clean();
?>
<!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 · Advance Dashboard</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=Sora:wght@300;400;500;600;700&family=JetBrains+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: #94a3b8; --border: #e2e8f0;
  --surface: #ffffff; --bg: #f1f5f9; --sidebar-bg: #0f172a; --sidebar-w: 260px;
  --radius: 12px; --shadow: 0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  font-family: 'Sora', system-ui, sans-serif;
}
html, body { height: 100%; }
body { background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.6; -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; overflow-x: hidden; transition: transform .3s cubic-bezier(.4,0,.2,1); scrollbar-width: none; }
.sidebar::-webkit-scrollbar { display: none; }
.sidebar.hidden { transform: translateX(-100%); }
.sidebar-brand { padding: 24px 20px 16px; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 8px; }
.brand-logo { width: 36px; height: 36px; background: linear-gradient(135deg, #3b82f6, #6366f1); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 16px; font-weight: 700; color: #fff; flex-shrink: 0; }
.brand-name { font-size: 15px; font-weight: 700; color: #fff; }
.brand-sub  { font-size: 10px; color: rgba(255,255,255,.4); letter-spacing: 1.5px; text-transform: uppercase; margin-top: 1px; }
.nav-section { padding: 0 12px 6px; }
.nav-item { list-style: none; }
.nav-link, .nav-dropdown-toggle { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; color: rgba(255,255,255,.65); text-decoration: none; font-size: 13px; font-weight: 500; cursor: pointer; border: none; background: none; width: 100%; text-align: left; transition: background .15s, color .15s; }
.nav-link:hover, .nav-dropdown-toggle:hover { background: rgba(255,255,255,.07); color: #fff; }
.nav-link.active { background: rgba(59,130,246,.2); color: #60a5fa; }
.nav-link i, .nav-dropdown-toggle i { width: 16px; text-align: center; font-size: 13px; }
.nav-dropdown-toggle .arrow { margin-left: auto; transition: transform .2s; font-size: 10px; }
.nav-dropdown-toggle.open .arrow { transform: rotate(180deg); }
.nav-submenu { list-style:none; overflow:hidden; max-height:0; transition:max-height .3s ease; padding-left:26px; }
.nav-submenu.open { max-height: 600px; }
.nav-submenu .nav-link { font-size: 12px; padding: 6px 10px; color: rgba(255,255,255,.5); }
.nav-submenu .nav-link:hover { color: #fff; background: rgba(255,255,255,.05); }
.sidebar-footer { margin-top: auto; padding: 12px; 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 cubic-bezier(.4,0,.2,1); }
.content.expanded { margin-left: 0; }
.topbar { height: 60px; background: var(--surface); border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; padding: 0 24px; position: sticky; top: 0; z-index: 100; }
.hamburger-btn { width: 36px; height: 36px; border-radius: 8px; border: 1px solid var(--border); background: var(--surface); 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:13px; color:var(--muted); }
.topbar-breadcrumb .current { color:var(--ink); font-weight:600; }
.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, #3b82f6, #6366f1); display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; font-weight: 700; }

.page { padding: 24px; flex: 1; }
.page-header { margin-bottom: 20px; }
.page-title  { font-size: 22px; font-weight: 700; color: var(--ink); letter-spacing: -.4px; }
.page-subtitle { font-size: 13px; color: var(--muted); margin-top: 2px; }

.alert { padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 500; display: flex; align-items: flex-start; gap: 10px; margin-bottom: 20px; border: 1px solid transparent; animation: fadeUp .25s ease; }
.alert-success { background: #d1fae5; border-color: #6ee7b7; color: #065f46; }
.alert-danger   { background: #fee2e2; border-color: #fca5a5; color: #991b1b; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }

.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 16px; margin-bottom: 24px; }
.stat-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); padding: 20px; display: flex; flex-direction: column; gap: 4px; }
.stat-card .stat-num { font-size: 28px; font-weight: 700; line-height: 1; }
.stat-card .stat-label { font-size: 12px; color: var(--muted); font-weight: 500; }
.stat-card.pending   { border-top: 3px solid #f59e0b; }
.stat-card.pending   .stat-num { color: #92400e; }
.stat-card.approved  { border-top: 3px solid #10b981; }
.stat-card.approved  .stat-num { color: #065f46; }
.stat-card.rejected  { border-top: 3px solid #ef4444; }
.stat-card.rejected  .stat-num { color: #991b1b; }
.stat-card.total     { border-top: 3px solid #6366f1; }
.stat-card.total     .stat-num { color: #3730a3; }

.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; margin-bottom: 20px; }
.card-header { display: flex; align-items: center; gap: 8px; padding: 16px 20px; border-bottom: 1px solid var(--border); }
.card-title { font-size: 15px; font-weight: 700; color: var(--ink); }
.card-body { padding: 20px; }

.filter-row { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; }
.filter-group { display: flex; flex-direction: column; gap: 4px; }
.filter-label { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .8px; color: var(--muted); }
.form-control, .form-select { height: 38px; border: 1px solid var(--border); border-radius: 8px; padding: 0 12px; font-size: 13px; font-family: 'Sora', sans-serif; color: var(--ink); background: var(--bg); outline: none; transition: border-color .15s; }
.form-control:focus, .form-select:focus { border-color: #3b82f6; background: var(--surface); }

.btn-mpc { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; border-radius: 8px; border: none; font-size: 13px; font-weight: 600; font-family: 'Sora', sans-serif; cursor: pointer; transition: opacity .15s; text-decoration: none; }
.btn-mpc-primary  { background: #1d4ed8; color: #fff; }
.btn-mpc-success  { background: #059669; color: #fff; }
.btn-mpc-danger   { background: #dc2626; color: #fff; }
.btn-mpc-sm { padding: 5px 10px; font-size: 12px; border-radius: 6px; }
.btn-mpc:hover { opacity: .88; }

.table-wrap { overflow-x: auto; }
table.mpc-table { width: 100%; border-collapse: collapse; font-size: 13px; }
table.mpc-table thead th { background: #f8fafc; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: .6px; color: var(--muted); padding: 10px 14px; border-bottom: 1px solid var(--border); white-space: nowrap; }
table.mpc-table tbody td { padding: 12px 14px; border-bottom: 1px solid var(--border); color: var(--ink-2); vertical-align: middle; }
table.mpc-table tbody tr:last-child td { border-bottom: none; }
table.mpc-table tbody tr:hover { background: #f8fafc; }

.badge-status { display: inline-flex; align-items: center; padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
.badge-Approved { background: #d1fae5; color: #065f46; }
.badge-Rejected { background: #fee2e2; color: #991b1b; }
.badge-Pending  { background: #fef3c7; color: #92400e; }

.deduction-preview { background: #eff6ff; border: 1px solid #bfdbfe; padding: 10px 14px; border-radius: 8px; color: #1e40af; font-weight: 600; font-size: 13px; margin-top: 12px; }

@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 16px; }
}
</style>
</head>
<body>
<div class="layout">

<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div><div class="brand-name">MPC</div><div class="brand-sub">Admin Portal</div></div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item"><a href="dashboard_admin.php" class="nav-link"><i class="fas fa-sitemap"></i> Organisation Chart</a></li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="manage_users.php"         class="nav-link"><i class="fas fa-users"></i>        Employee Details</a></li>
          <li><a href="manage_documents.php"     class="nav-link"><i class="fas fa-file-alt"></i>     Policies Rolled Out</a></li>
          <li><a href="division_designation.php" class="nav-link"><i class="fas fa-tag"></i>          Division / Designation</a></li>
          <li><a href="digital.php"              class="nav-link"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="change_password.php"      class="nav-link"><i class="fas fa-key"></i>          Change Password</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle open" onclick="toggleMenu(this)"><i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu open">
          <li><a href="attendance.php"              class="nav-link"><i class="fas fa-clock"></i>             Attendance Dashboard</a></li>
          <li><a href="payroll.php"                 class="nav-link"><i class="fas fa-money-bill"></i>        Payroll Dashboard</a></li>
          <li><a href="mobile_attendance.php"       class="nav-link"><i class="fas fa-mobile-alt"></i>       Daily Attendance Report</a></li>
          <li><a href="task_dashboard.php"          class="nav-link"><i class="fas fa-tasks"></i>            Task Dashboard</a></li>
          <li><a href="daily_reports_dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>       Daily Report Dashboard</a></li>
          <li><a href="ot_dashboard.php"            class="nav-link"><i class="fas fa-hourglass-half"></i>   OT Dashboard</a></li>
          <li><a href="company_holidays.php"        class="nav-link"><i class="fas fa-star"></i>             Company Holidays</a></li>
          <li><a href="hr_approval_salary.php"      class="nav-link active"><i class="fas fa-hand-holding-usd"></i> Advance Dashboard</a></li>
          <li><a href="expense_dashboard.php"       class="nav-link"><i class="fas fa-receipt"></i>          Expenses Dashboard</a></li>
          <li><a href="manager_hr_leave_apply.php"  class="nav-link"><i class="fas fa-calendar-plus"></i>    Apply Leave</a></li>
          <li><a href="leave_dashboard.php"         class="nav-link"><i class="fas fa-umbrella-beach"></i>   Leave Dashboard</a></li>
          <li><a href="grievance_dashboard.php"     class="nav-link"><i class="fas fa-comment-alt"></i>      Grievance Dashboard</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="individual_rr.php"     class="nav-link"><i class="fas fa-trophy"></i>   Individual R &amp; R</a></li>
          <li><a href="individual_kpi.php"    class="nav-link"><i class="fas fa-bullseye"></i> Individual KPI</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>  Login Credentials</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="incident_employee.php"  class="nav-link"><i class="fas fa-exclamation-triangle"></i> Incident Portal</a></li>
          <li><a href="training_dashboard.php" class="nav-link"><i class="fas fa-chalkboard-teacher"></i>   Training Portal</a></li>
          <li><a href="rr.php"                 class="nav-link"><i class="fas fa-award"></i>                Rewards &amp; Recognition</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)"><i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-submenu">
          <li><a href="employee_tiy.php"      class="nav-link"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>    Login Credentials</a></li>
        </ul>
      </li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171;"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </div>
</nav>

<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>CAB</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Advance Dashboard</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($hr_username ?: 'A', 0, 1)); ?></div>
      <?php echo h($hr_username); ?>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title">Salary Advance Approvals</div>
      <div class="page-subtitle">Welcome, <?php echo h($hr_username); ?> &middot; <?php echo strtoupper($hr_role); ?></div>
    </div>

    <?php if ($success_msg): ?>
      <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo h($success_msg); ?></div>
    <?php endif; ?>
    <?php if ($error_msg): ?>
      <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?php echo h($error_msg); ?></div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-grid">
      <div class="stat-card pending">
        <div class="stat-num"><?php echo $stats['pending']; ?></div>
        <div class="stat-label"><i class="fas fa-clock"></i> Pending</div>
      </div>
      <div class="stat-card approved">
        <div class="stat-num"><?php echo $stats['approved']; ?></div>
        <div class="stat-label"><i class="fas fa-check"></i> Approved</div>
      </div>
      <div class="stat-card rejected">
        <div class="stat-num"><?php echo $stats['rejected']; ?></div>
        <div class="stat-label"><i class="fas fa-times"></i> Rejected</div>
      </div>
      <div class="stat-card total">
        <div class="stat-num"><?php echo $stats['total']; ?></div>
        <div class="stat-label"><i class="fas fa-layer-group"></i> Total Requests</div>
      </div>
    </div>

    <!-- Filters -->
    <div class="card">
      <div class="card-header">
        <i class="fas fa-filter" style="color:var(--muted)"></i>
        <div class="card-title">Filter Requests</div>
      </div>
      <div class="card-body">
        <form method="GET">
          <div class="filter-row">
            <div class="filter-group">
              <label class="filter-label">Search</label>
              <input type="text" name="search" class="form-control" style="min-width:220px;" placeholder="Name, ID, email…" value="<?php echo h($search); ?>">
            </div>
            <div class="filter-group">
              <label class="filter-label">Status</label>
              <select name="status" class="form-select">
                <option value="all">All Status</option>
                <?php foreach (['Pending','Approved','Rejected'] as $s): ?>
                  <option value="<?php echo $s; ?>" <?php echo $status_filter === $s ? 'selected' : ''; ?>><?php echo $s; ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div style="display:flex;align-items:flex-end;">
              <button type="submit" class="btn-mpc btn-mpc-primary"><i class="fas fa-search"></i> Filter</button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- Table -->
    <div class="card">
      <div class="card-header">
        <i class="fas fa-hand-holding-usd" style="color:var(--muted)"></i>
        <div class="card-title">Advance Requests <span style="color:var(--muted);font-weight:400;font-size:13px;">(<?php echo count($requests); ?> records)</span></div>
      </div>
      <?php if (empty($requests)): ?>
        <div style="text-align:center;padding:48px;color:var(--muted);"><i class="fas fa-inbox" style="font-size:32px;display:block;margin-bottom:8px;"></i>No requests found.</div>
      <?php else: ?>
      <div class="table-wrap">
        <table class="mpc-table">
          <thead>
            <tr><th>#ID</th><th>Employee</th><th>Dept</th><th>Amount</th><th>Reason</th><th>Status</th><th>Action</th></tr>
          </thead>
          <tbody>
            <?php
            $modalHtml = '';
            foreach ($requests as $r):
            ?>
            <tr>
              <td style="font-weight:600;font-family:'JetBrains Mono',monospace;">#<?php echo $r['advance_id']; ?></td>
              <td><?php echo h($r['username']); ?><br><span style="font-size:11px;color:var(--muted);"><?php echo h($r['employee_id']); ?></span></td>
              <td><?php echo h($r['division'] ?? '—'); ?></td>
              <td style="font-weight:700;">₹<?php echo number_format($r['amount'], 2); ?></td>
              <td><?php echo h(substr($r['reason'], 0, 40)); ?><?php echo strlen($r['reason']) > 40 ? '…' : ''; ?></td>
              <td><span class="badge-status badge-<?php echo h($r['approval_status']); ?>"><?php echo h($r['approval_status']); ?></span></td>
              <td>
                <?php if ($r['approval_status'] === 'Pending'): ?>
                  <button class="btn-mpc btn-mpc-success btn-mpc-sm" data-bs-toggle="modal" data-bs-target="#approve<?php echo $r['advance_id']; ?>" data-amount="<?php echo h($r['amount']); ?>"><i class="fas fa-check"></i> Approve</button>
                  <button class="btn-mpc btn-mpc-danger btn-mpc-sm" data-bs-toggle="modal" data-bs-target="#reject<?php echo $r['advance_id']; ?>"><i class="fas fa-times"></i> Reject</button>
                <?php else: ?>
                  <span style="color:var(--muted);font-size:12px;">Processed</span>
                <?php endif; ?>
              </td>
            </tr>
            <?php
            if ($r['approval_status'] === 'Pending') {
                $aid = (int)$r['advance_id'];
                $defaultStart = date('Y-m', strtotime('+1 month'));
                $modalHtml .= '
                <div class="modal fade" id="approve'.$aid.'" tabindex="-1">
                  <div class="modal-dialog modal-lg">
                    <form method="POST" class="approve-form">
                      <div class="modal-content" style="border-radius:12px;border:1px solid #e2e8f0;">
                        <div class="modal-header" style="background:#059669;color:#fff;border-radius:12px 12px 0 0;">
                          <h5 class="modal-title" style="font-family:Sora,sans-serif;font-weight:700;">Approve Salary Advance</h5>
                          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body" style="font-family:Sora,sans-serif;">
                          <input type="hidden" name="advance_id" value="'.$aid.'">
                          <input type="hidden" name="action" value="approve">
                          <p><strong>Employee:</strong> '.h($r['username']).' &middot; <strong>Amount:</strong> ₹'.number_format($r['amount'],2).'</p>
                          <div class="row g-3">
                            <div class="col-md-6">
                              <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:#94a3b8;">Installments</label>
                              <select name="installments" id="inst'.$aid.'" class="form-select mt-1 inst-select" data-advance-id="'.$aid.'">';
                              for ($i = 1; $i <= 24; $i++) {
                                  $sel = $i == 3 ? ' selected' : '';
                                  $modalHtml .= '<option value="'.$i.'"'.$sel.'>'.$i.' month'.($i>1?'s':'').'</option>';
                              }
                $modalHtml .= '</select></div>
                            <div class="col-md-6">
                              <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:#94a3b8;">Start Month</label>
                              <input type="month" name="repayment_start" class="form-control mt-1" value="'.$defaultStart.'" required>
                            </div>
                          </div>
                          <div class="deduction-preview mt-3"><i class="fas fa-calculator"></i> Monthly Deduction: ₹<span id="mon'.$aid.'">0.00</span></div>
                          <div class="mt-3">
                            <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:#94a3b8;">Remarks (Optional)</label>
                            <textarea name="remarks" class="form-control mt-1" rows="2" style="font-family:Sora,sans-serif;font-size:13px;"></textarea>
                          </div>
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn-mpc" style="background:#f1f5f9;color:#334155;border:1px solid #e2e8f0;" data-bs-dismiss="modal">Cancel</button>
                          <button type="submit" class="btn-mpc btn-mpc-success"><i class="fas fa-check"></i> Approve</button>
                        </div>
                      </div>
                    </form>
                  </div>
                </div>

                <div class="modal fade" id="reject'.$aid.'" tabindex="-1">
                  <div class="modal-dialog">
                    <form method="POST">
                      <div class="modal-content" style="border-radius:12px;border:1px solid #e2e8f0;">
                        <div class="modal-header" style="background:#dc2626;color:#fff;border-radius:12px 12px 0 0;">
                          <h5 class="modal-title" style="font-family:Sora,sans-serif;font-weight:700;">Reject Advance</h5>
                          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body" style="font-family:Sora,sans-serif;">
                          <input type="hidden" name="advance_id" value="'.$aid.'">
                          <input type="hidden" name="action" value="reject">
                          <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:#94a3b8;">Reason for Rejection <span style="color:#dc2626">*</span></label>
                          <textarea name="remarks" class="form-control mt-1" required rows="3" style="font-family:Sora,sans-serif;font-size:13px;"></textarea>
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn-mpc" style="background:#f1f5f9;color:#334155;border:1px solid #e2e8f0;" data-bs-dismiss="modal">Cancel</button>
                          <button type="submit" class="btn-mpc btn-mpc-danger"><i class="fas fa-times"></i> Reject</button>
                        </div>
                      </div>
                    </form>
                  </div>
                </div>';
            }
            endforeach;
            ?>
          </tbody>
        </table>
        <?php echo $modalHtml; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
function toggleMenu(btn) {
  btn.nextElementSibling.classList.toggle('open');
  btn.classList.toggle('open');
}
function calcForAdvance(id, amount) {
  const instEl = document.getElementById('inst' + id);
  const monEl  = document.getElementById('mon' + id);
  if (!instEl || !monEl) return;
  monEl.textContent = (parseFloat(amount) / parseInt(instEl.value)).toFixed(2);
}
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('button[data-bs-target^="#approve"]').forEach(btn => {
    btn.addEventListener('click', function() {
      const id = btn.getAttribute('data-bs-target').replace('#approve','');
      const amount = btn.getAttribute('data-amount') || '0';
      setTimeout(() => calcForAdvance(id, amount), 120);
    });
  });
  document.querySelectorAll('.inst-select').forEach(sel => {
    sel.addEventListener('change', function() {
      const id = sel.getAttribute('data-advance-id');
      const btn = document.querySelector('button[data-bs-target="#approve'+id+'"][data-amount]');
      calcForAdvance(id, btn ? btn.getAttribute('data-amount') : '0');
    });
  });
});
</script>
</body>
</html>
<?php $conn->close(); ?>