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

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

$status_filter = $_GET['status'] ?? 'pending';
if (!in_array($status_filter, ['pending','approved','rejected','all'], true)) $status_filter = 'pending';

$employee_filter = trim($_GET['employee_id'] ?? '');

$where = "WHERE u.reporting_manager_id = ?";
$params = [$manager_id];
$types  = "i";
if ($status_filter !== 'all') {
    $where .= " AND e.status = ?";
    $params[] = $status_filter;
    $types .= "s";
}
if ($employee_filter !== '') {
    $where .= " AND e.employee_id = ?";
    $params[] = $employee_filter;
    $types .= "s";
}

$stmt = $conn->prepare("
    SELECT e.*, u.first_name, u.last_name, u.designation
    FROM expenses e
    JOIN users u ON u.id = e.employee_id COLLATE utf8mb4_general_ci
    $where
    ORDER BY FIELD(e.status,'pending','approved','rejected'), e.expense_date DESC
");
$stmt->bind_param($types, ...$params);
$stmt->execute();
$claims = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

/* Direct reports list, to populate the employee filter dropdown */
$stmtE = $conn->prepare("SELECT id, first_name, last_name FROM users WHERE reporting_manager_id = ? ORDER BY first_name, last_name");
$stmtE->bind_param("i", $manager_id);
$stmtE->execute();
$my_team = $stmtE->get_result()->fetch_all(MYSQLI_ASSOC);
$stmtE->close();

/* Group rows sharing a claim_group (multi-category submissions) together for display */
$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'];
}

/* Stats across the whole team, regardless of the current filter */
$stmt2 = $conn->prepare("
    SELECT e.status, COUNT(*) c, COALESCE(SUM(e.amount),0) total
    FROM expenses e JOIN users u ON u.id = e.employee_id COLLATE utf8mb4_general_ci
    WHERE u.reporting_manager_id = ?
    GROUP BY e.status
");
$stmt2->bind_param("i", $manager_id);
$stmt2->execute();
$counts = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
$sums   = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
$res2 = $stmt2->get_result();
while ($r = $res2->fetch_assoc()) {
    $st = $r['status'] ?? 'pending';
    if (isset($counts[$st])) { $counts[$st] = (int)$r['c']; $sums[$st] = (float)$r['total']; }
}
$stmt2->close();

require_once __DIR__ . '/includes/expense_theme.php';
expense_render_head('Approvals');
expense_render_sidebar_and_topbar('manager', $username, 'expense_manager_dashboard.php', 'Approvals', ['pending' => $counts['pending']]);
?>
  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">Team Expense Approvals</div>
        <div class="page-subtitle">Review and act on claims submitted by your reports</div>
      </div>
    </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</div><div class="stat-value"><?= $counts['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($sums['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"><?= $counts['rejected'] ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-layer-group"></i></div>
        <div><div class="stat-label">Total Team Claims</div><div class="stat-value"><?= array_sum($counts) ?></div></div>
      </div>
    </div>

    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-list-check"></i> Claims</div>
        <form method="GET" class="filter-bar" style="margin:0">
          <select name="employee_id" onchange="this.form.submit()">
            <option value="">All employees</option>
            <?php foreach ($my_team as $emp): ?>
              <option value="<?= h($emp['id']) ?>" <?= $employee_filter === (string)$emp['id'] ? 'selected' : '' ?>>
                <?= h($emp['first_name'].' '.$emp['last_name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <select name="status" onchange="this.form.submit()">
            <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>
            <option value="all" <?= $status_filter==='all'?'selected':'' ?>>All</option>
          </select>
          <?php if ($employee_filter !== ''): ?>
            <a href="expense_manager_dashboard.php?status=<?= h($status_filter) ?>" class="btn-action btn-remarks" style="padding:7px 12px"><i class="fas fa-xmark" style="font-size:10px"></i> Clear employee</a>
          <?php endif; ?>
        </form>
      </div>
      <div class="dash-card-body">
        <?php if (empty($claims)): ?>
          <div class="empty-state">
            <i class="fas fa-inbox"></i>
            <p>No claims found for this filter.</p>
          </div>
        <?php else: ?>
          <?php foreach ($groups as $key => $group): $items = $group['items']; $multi = count($items) > 1; ?>
            <?php if ($multi): $first = $items[0]; ?>
              <div style="display:flex;justify-content:space-between;align-items:center;background:#eef2ff;border-radius:10px;padding:9px 14px;margin-bottom:8px">
                <span style="font-size:12px;font-weight:700;color:var(--ink)">
                  <i class="fas fa-suitcase" style="margin-right:5px;color:var(--accent)"></i>
                  <?= h($first['first_name'].' '.$first['last_name']) ?> — Trip claim (<?= count($items) ?> categories)
                </span>
                <span style="font-size:13px;font-weight:700;color:var(--accent)">Total ₹<?= number_format($group['total'],2) ?></span>
              </div>
            <?php endif; ?>
            <?php foreach ($items as $c):
              [$cls, $icon, $label] = expense_status_badge($c['status']);
              $item_cls = $c['status'] === 'approved' ? 'approved' : ($c['status'] === 'pending' ? 'in-progress' : '');
            ?>
          <div class="task-item <?= $item_cls ?>">
            <div class="task-header">
              <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
                <span class="badge-custom <?= $cls ?>"><i class="fas fa-<?= $icon ?>" style="font-size:9px"></i><?= $label ?></span>
                <span class="badge-custom badge-purple"><i class="fas fa-tag" style="font-size:9px"></i><?= h($c['category']) ?></span>
              </div>
              <div style="font-size:11px;color:var(--muted);white-space:nowrap">Date: <strong><?= h($c['expense_date']) ?><?php if (!empty($c['to_date']) && $c['to_date'] !== $c['expense_date']): ?> → <?= h($c['to_date']) ?><?php endif; ?></strong></div>
            </div>
            <div class="task-body">
              <div class="task-title-text">₹<?= number_format((float)$c['amount'],2) ?> — <?= h($c['category']) ?></div>
              <div class="task-desc-text"><?= h($c['description']) ?></div>
              <div class="task-meta">
                <span><i class="fas fa-user" style="margin-right:3px"></i><?= h($c['first_name'].' '.$c['last_name']) ?>
                  <span class="badge-role"><?= h($c['designation'] ?? '') ?></span>
                </span>
                <?php if (!empty($c['bill_image'])): ?>
                  <a href="<?= h($c['bill_image']) ?>" target="_blank" style="color:var(--accent);text-decoration:none">
                    <i class="fas fa-paperclip" style="margin-right:3px"></i>View Bill
                  </a>
                <?php endif; ?>
              </div>
              <?php if ($c['status'] !== 'pending'): ?>
                <div class="remarks-area">
                  <?= $c['status']==='approved' ? 'Approved' : 'Rejected' ?> by <?= h($c['reviewed_by_name'] ?? 'you') ?>
                  <?php if (!empty($c['reviewed_at'])): ?> on <?= h(date('d M Y, H:i', strtotime($c['reviewed_at']))) ?><?php endif; ?>
                  <?php if (!empty($c['rejection_reason'])): ?><br>Reason: <?= h($c['rejection_reason']) ?><?php endif; ?>
                  <?php if (!empty($c['manager_remarks'])): ?><br>Remarks: <?= h($c['manager_remarks']) ?><?php endif; ?>
                </div>
              <?php endif; ?>
            </div>
            <?php if ($c['status'] === 'pending'): ?>
            <div class="task-footer">
              <form method="POST" action="expense_approve.php" style="margin:0;display:flex;gap:8px;align-items:center;flex-wrap:wrap">
                <input type="hidden" name="csrf" value="<?= h($csrf_token) ?>">
                <input type="hidden" name="claim_id" value="<?= (int)$c['id'] ?>">
                <input type="text" name="remarks" class="form-control" placeholder="Optional remarks…" style="max-width:220px;padding:6px 10px;font-size:12px">
                <button type="submit" class="btn-action btn-start" onclick="return confirm('Approve this claim?')"><i class="fas fa-check" style="font-size:10px"></i>Approve</button>
              </form>
              <form method="POST" action="expense_reject.php" style="margin:0;display:flex;gap:8px;align-items:center;flex-wrap:wrap" onsubmit="return validateReject(this)">
                <input type="hidden" name="csrf" value="<?= h($csrf_token) ?>">
                <input type="hidden" name="claim_id" value="<?= (int)$c['id'] ?>">
                <input type="text" name="reason" class="form-control" placeholder="Reason for rejection…" style="max-width:220px;padding:6px 10px;font-size:12px" required>
                <button type="submit" class="btn-action btn-danger"><i class="fas fa-xmark" style="font-size:10px"></i>Reject</button>
              </form>
            </div>
            <?php endif; ?>
          </div>
          <?php endforeach; // items in this group ?>
          <?php endforeach; // groups ?>
        <?php endif; ?>
      </div>
    </div>
  </div>
  <script>
    function validateReject(form) {
      const reason = form.querySelector('[name="reason"]').value.trim();
      if (!reason) { alert('Please provide a reason for rejection.'); return false; }
      return confirm('Reject this claim?');
    }
  </script>
<?php expense_render_footer_scripts(); ?>