<?php
require_once __DIR__ . '/includes/expense_common.php';
expense_require_role(['admin','superadmin']);
expense_ensure_schema($conn);

$username = $_SESSION['username'] ?? 'Admin';
$role = $_SESSION['role'];

$totals = ['pending'=>0,'approved'=>0,'rejected'=>0];
$sums   = ['pending'=>0,'approved'=>0,'rejected'=>0];
$res = $conn->query("SELECT status, COUNT(*) c, COALESCE(SUM(amount),0) total FROM expenses GROUP BY status");
while ($r = $res->fetch_assoc()) {
    $st = $r['status'] ?? 'pending';
    if (isset($totals[$st])) { $totals[$st] = (int)$r['c']; $sums[$st] = (float)$r['total']; }
}
$total_claims = array_sum($totals);

$month_start = date('Y-m-01');
$stmtM = $conn->prepare("SELECT COALESCE(SUM(amount),0) t FROM expenses WHERE status='approved' AND expense_date >= ?");
$stmtM->bind_param("s", $month_start);
$stmtM->execute();
$month_approved = (float)$stmtM->get_result()->fetch_assoc()['t'];
$stmtM->close();

/* Breakdown by category (approved only, this month) */
$cat_rows = [];
$stmtC = $conn->prepare("SELECT category, COALESCE(SUM(amount),0) total, COUNT(*) c FROM expenses WHERE status='approved' AND expense_date >= ? GROUP BY category ORDER BY total DESC");
$stmtC->bind_param("s", $month_start);
$stmtC->execute();
$cat_rows = $stmtC->get_result()->fetch_all(MYSQLI_ASSOC);
$stmtC->close();
$cat_max = max(array_column($cat_rows, 'total') ?: [1]);

/* Distinct trip (multi-category) submissions this month, for a quick stat */
$stmtT = $conn->prepare("SELECT COUNT(DISTINCT claim_group) t FROM expenses WHERE claim_group IS NOT NULL AND expense_date >= ?");
$stmtT->bind_param("s", $month_start);
$stmtT->execute();
$month_trips = (int)$stmtT->get_result()->fetch_assoc()['t'];
$stmtT->close();

/* Employee search filter (name) applied to the Recent Claims list below */
$emp_search = trim($_GET['emp'] ?? '');

$recent_where = "";
$recent_params = [];
$recent_types = "";
if ($emp_search !== '') {
    $recent_where = "WHERE (u.first_name LIKE ? OR u.last_name LIKE ? OR e.employee_name LIKE ?)";
    $like = "%$emp_search%";
    $recent_params = [$like, $like, $like];
    $recent_types = "sss";
}
$recent_limit = $emp_search !== '' ? 60 : 20;

/* Recent claims across the company (optionally filtered by employee name search) */
$stmtR = $conn->prepare("
    SELECT e.*, u.first_name, u.last_name, u.division
    FROM expenses e LEFT JOIN users u ON u.id = e.employee_id COLLATE utf8mb4_general_ci
    $recent_where
    ORDER BY e.created_at DESC LIMIT $recent_limit
");
if ($recent_types !== '') $stmtR->bind_param($recent_types, ...$recent_params);
$stmtR->execute();
$recent = $stmtR->get_result()->fetch_all(MYSQLI_ASSOC);
$stmtR->close();

/* Distinct employee names (with expense history) to power the search suggestions */
$emp_options = $conn->query("
    SELECT DISTINCT TRIM(CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,''))) name
    FROM expenses e LEFT JOIN users u ON u.id = e.employee_id COLLATE utf8mb4_general_ci
    WHERE TRIM(CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,''))) <> ''
    ORDER BY name
")->fetch_all(MYSQLI_ASSOC);

/* Group the recent claims by claim_group so multi-category trips show together, same as employee/manager views */
$recent_groups = [];
foreach ($recent as $c) {
    $key = !empty($c['claim_group']) ? $c['claim_group'] : 'single_' . $c['id'];
    if (!isset($recent_groups[$key])) $recent_groups[$key] = ['items' => [], 'total' => 0, 'latest' => $c['created_at']];
    $recent_groups[$key]['items'][] = $c;
    $recent_groups[$key]['total'] += (float)$c['amount'];
}
/* Keep only a reasonable number of groups so the table doesn't grow unbounded */
$recent_groups = array_slice($recent_groups, 0, $emp_search !== '' ? 40 : 12, true);

require_once __DIR__ . '/includes/expense_theme.php';
expense_render_head('Overview');
expense_render_sidebar_and_topbar($role, $username, 'expense_admin_dashboard.php', 'Overview');
?>
  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">Expense Overview</div>
        <div class="page-subtitle">Company-wide claim activity · <?= date('l, d M Y') ?></div>
      </div>
      <a href="expense_reports.php" class="back-btn"><i class="fas fa-chart-column" style="font-size:10px"></i> Full Reports</a>
    </div>

    <?php expense_render_flash(); ?>

    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon amber"><i class="fas fa-clock"></i></div>
        <div><div class="stat-label">Pending Claims</div><div class="stat-value"><?= $totals['pending'] ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon green"><i class="fas fa-circle-check"></i></div>
        <div><div class="stat-label">Approved (All Time)</div><div class="stat-value">₹<?= number_format($sums['approved'],0) ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-calendar-check"></i></div>
        <div><div class="stat-label">Approved This Month</div><div class="stat-value">₹<?= number_format($month_approved,0) ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon red"><i class="fas fa-circle-xmark"></i></div>
        <div><div class="stat-label">Rejected</div><div class="stat-value"><?= $totals['rejected'] ?></div></div>
      </div>
    </div>

    <div class="dash-card">
      <div class="dash-card-header"><div class="dash-card-title"><i class="fas fa-chart-simple"></i> This Month by Category</div></div>
      <div class="dash-card-body">
        <?php if (empty($cat_rows)): ?>
          <div class="empty-state"><i class="fas fa-chart-simple"></i><p>No approved claims yet this month.</p></div>
        <?php else: foreach ($cat_rows as $cat): $pct = $cat_max > 0 ? round(($cat['total']/$cat_max)*100) : 0; ?>
          <div style="margin-bottom:12px">
            <div style="display:flex;justify-content:space-between;font-size:12.5px;margin-bottom:4px">
              <span style="font-weight:600;color:var(--ink-2)"><?= h($cat['category']) ?> <span style="color:var(--muted);font-weight:400">(<?= $cat['c'] ?>)</span></span>
              <span style="font-weight:700">₹<?= number_format($cat['total'],0) ?></span>
            </div>
            <div style="background:var(--bg);border-radius:20px;height:8px;overflow:hidden">
              <div style="background:linear-gradient(135deg,var(--accent),var(--accent-2));height:100%;width:<?= $pct ?>%;border-radius:20px"></div>
            </div>
          </div>
        <?php endforeach; endif; ?>
      </div>
    </div>

    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-clock-rotate-left"></i> Recent Claims</div>
        <div style="display:flex;gap:6px;flex-wrap:wrap">
          <span style="font-size:10px;font-weight:600;background:#ede9fe;color:#5b21b6;padding:3px 9px;border-radius:20px"><?= $month_trips ?> trips this month</span>
          <span style="font-size:10px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 9px;border-radius:20px"><?= $total_claims ?> total</span>
        </div>
      </div>
      <div class="dash-card-body" style="padding-top:0;padding-bottom:0">
        <form method="GET" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:14px 0">
          <input type="text" name="emp" list="empOptions" value="<?= h($emp_search) ?>" placeholder="Search employee name…" class="form-control" style="max-width:260px;padding:8px 12px">
          <datalist id="empOptions">
            <?php foreach ($emp_options as $eo): ?><option value="<?= h($eo['name']) ?>"><?php endforeach; ?>
          </datalist>
          <button type="submit" class="btn-action btn-finish" style="padding:8px 14px"><i class="fas fa-magnifying-glass" style="font-size:10px"></i> Search</button>
          <?php if ($emp_search !== ''): ?>
            <a href="expense_admin_dashboard.php" class="btn-action btn-remarks" style="padding:8px 14px"><i class="fas fa-xmark" style="font-size:10px"></i> Clear</a>
          <?php endif; ?>
        </form>
      </div>
      <div class="dash-card-body" style="padding-top:0">
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr><th>Employee</th><th>Division</th><th>Date</th><th>Category</th><th>Amount</th><th>Status</th></tr></thead>
            <tbody>
              <?php foreach ($recent_groups as $key => $group): $items = $group['items']; $multi = count($items) > 1; ?>
                <?php if ($multi): $first = $items[0]; ?>
                <tr style="background:#f8fafc">
                  <td colspan="4" style="font-weight:700;color:var(--ink);font-size:12px">
                    <i class="fas fa-suitcase" style="margin-right:5px;color:var(--accent)"></i>
                    <?= h(trim(($first['first_name']??'').' '.($first['last_name']??$first['employee_name']))) ?> — Trip claim
                    <span style="font-weight:400;color:var(--muted)">(<?= count($items) ?> categories)</span>
                  </td>
                  <td colspan="2" style="text-align:right;font-weight:700;color:var(--accent)">Total ₹<?= number_format($group['total'],2) ?></td>
                </tr>
                <?php endif; ?>
                <?php foreach ($items as $c): [$cls,$icon,$label] = expense_status_badge($c['status']); ?>
                <tr>
                  <td style="<?= $multi ? 'padding-left:26px;color:var(--muted);font-size:11.5px' : '' ?>">
                    <?php if (!$multi): ?><strong style="font-size:12.5px"><?= h(trim(($c['first_name']??'').' '.($c['last_name']??$c['employee_name']))) ?></strong><?php else: ?>—<?php endif; ?>
                  </td>
                  <td style="font-size:11px;color:var(--muted)"><?= h($c['division'] ?? '—') ?></td>
                  <td style="white-space:nowrap"><?= h($c['expense_date']) ?><?php if (!empty($c['to_date']) && $c['to_date'] !== $c['expense_date']): ?> → <?= h($c['to_date']) ?><?php endif; ?></td>
                  <td><span class="badge-custom badge-purple"><?= h($c['category']) ?></span></td>
                  <td style="font-weight:700">₹<?= number_format((float)$c['amount'],2) ?></td>
                  <td><span class="badge-custom <?= $cls ?>"><i class="fas fa-<?= $icon ?>" style="font-size:9px"></i><?= $label ?></span></td>
                </tr>
                <?php endforeach; ?>
              <?php endforeach; ?>
              <?php if (empty($recent_groups)): ?>
                <tr><td colspan="6"><div class="empty-state"><i class="fas fa-receipt"></i><p>No claims yet.</p></div></td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
<?php expense_render_footer_scripts(); ?>