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

$user_id  = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'User';
$csrf_token = expense_csrf_token();

/* Optional filter */
$status_filter = $_GET['status'] ?? '';
$where = "WHERE employee_id = ?";
$params = [$user_id];
$types  = "s";
if (in_array($status_filter, ['pending','approved','rejected'], true)) {
    $where .= " AND status = ?";
    $params[] = $status_filter;
    $types .= "s";
}

$stmt = $conn->prepare("SELECT * FROM expenses $where ORDER BY expense_date DESC, id DESC");
$stmt->bind_param($types, ...$params);
$stmt->execute();
$claims = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

/* Group rows sharing a claim_group (multi-category submissions) together; legacy/ungrouped rows stand alone. */
$groups = [];
foreach ($claims as $c) {
    $key = !empty($c['claim_group']) ? $c['claim_group'] : 'single_' . $c['id'];
    if (!isset($groups[$key])) $groups[$key] = ['items' => [], 'total' => 0];
    $groups[$key]['items'][] = $c;
    $groups[$key]['total'] += (float)$c['amount'];
}

$stmt2 = $conn->prepare("SELECT status, COUNT(*) c, COALESCE(SUM(amount),0) total FROM expenses WHERE employee_id = ? GROUP BY status");
$stmt2->bind_param("s", $user_id);
$stmt2->execute();
$stats = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
$totals = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
$res2 = $stmt2->get_result();
while ($r = $res2->fetch_assoc()) {
    $st = $r['status'] ?? 'pending';
    if (isset($stats[$st])) { $stats[$st] = (int)$r['c']; $totals[$st] = (float)$r['total']; }
}
$stmt2->close();
$total_claims = array_sum($stats);

expense_render_head('My Claims');
expense_render_sidebar_and_topbar('employee', $username, 'expense_claim_list.php', 'My Claims');
?>
  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">My Expense Claims</div>
        <div class="page-subtitle">Track and manage your reimbursement requests</div>
      </div>
      <a href="expense_claim_add.php" class="back-btn"><i class="fas fa-circle-plus" style="font-size:11px"></i> New Claim</a>
    </div>

    <?php expense_render_flash(); ?>

    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-layer-group"></i></div>
        <div><div class="stat-label">Total Claims</div><div class="stat-value"><?= $total_claims ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon amber"><i class="fas fa-clock"></i></div>
        <div><div class="stat-label">Pending</div><div class="stat-value"><?= $stats['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</div><div class="stat-value">₹<?= number_format($totals['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"><?= $stats['rejected'] ?></div></div>
      </div>
    </div>

    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-receipt"></i> Claims</div>
        <div class="filter-bar" style="margin:0">
          <select onchange="location.href='expense_claim_list.php'+(this.value?('?status='+this.value):'')">
            <option value="">All statuses</option>
            <option value="pending" <?= $status_filter==='pending'?'selected':'' ?>>Pending</option>
            <option value="approved" <?= $status_filter==='approved'?'selected':'' ?>>Approved</option>
            <option value="rejected" <?= $status_filter==='rejected'?'selected':'' ?>>Rejected</option>
          </select>
        </div>
      </div>
      <div class="dash-card-body" style="padding:0">
        <?php if (empty($claims)): ?>
          <div class="empty-state">
            <i class="fas fa-receipt"></i>
            <p>No expense claims found. <a href="expense_claim_add.php">Submit your first claim</a>.</p>
          </div>
        <?php else: ?>
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead>
              <tr>
                <th>Date</th><th>Category</th><th>Description</th><th>Amount</th><th>Bill</th><th>Status</th><th></th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($groups as $key => $group): $items = $group['items']; $multi = count($items) > 1; ?>
                <?php if ($multi): $first = $items[0]; ?>
                <tr style="background:#f8fafc">
                  <td colspan="3" style="font-weight:700;color:var(--ink);font-size:12px">
                    <i class="fas fa-suitcase" style="margin-right:5px;color:var(--accent)"></i>
                    Trip claim — <?= h($first['expense_date']) ?><?php if (!empty($first['to_date']) && $first['to_date'] !== $first['expense_date']): ?> → <?= h($first['to_date']) ?><?php endif; ?>
                    <span style="font-weight:400;color:var(--muted)">(<?= count($items) ?> categories)</span>
                  </td>
                  <td colspan="4" 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="white-space:nowrap;<?= $multi ? 'padding-left:26px;color:var(--muted);font-size:11.5px' : '' ?>">
                    <?php if (!$multi): ?><?= h($c['expense_date']) ?><?php if (!empty($c['to_date']) && $c['to_date'] !== $c['expense_date']): ?> → <?= h($c['to_date']) ?><?php endif; endif; ?>
                  </td>
                  <td><span class="badge-custom badge-purple"><?= h($c['category']) ?></span></td>
                  <td style="max-width:260px"><?= h(mb_strimwidth($c['description'] ?? '', 0, 70, '…')) ?></td>
                  <td style="font-weight:700;white-space:nowrap">₹<?= number_format((float)$c['amount'], 2) ?></td>
                  <td>
                    <?php if (!empty($c['bill_image'])): ?>
                      <img src="<?= h($c['bill_image']) ?>" class="bill-thumb" onclick="window.open(this.src)">
                    <?php else: ?><span style="color:var(--muted);font-size:11px">—</span><?php endif; ?>
                  </td>
                  <td><span class="badge-custom <?= $cls ?>"><i class="fas fa-<?= $icon ?>" style="font-size:9px"></i><?= $label ?></span></td>
                  <td style="white-space:nowrap">
                    <a href="expense_claim_view.php?id=<?= (int)$c['id'] ?>" class="btn-action btn-remarks" style="padding:5px 10px"><i class="fas fa-eye" style="font-size:10px"></i></a>
                    <?php if ($c['status'] === 'pending'): ?>
                    <a href="expense_claim_edit.php?id=<?= (int)$c['id'] ?>" class="btn-action btn-remarks" style="padding:5px 10px"><i class="fas fa-pen" style="font-size:10px"></i></a>
                    <?php endif; ?>
                  </td>
                </tr>
                <?php endforeach; ?>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
<?php expense_render_footer_scripts(); ?>