<?php
session_start();
$page_title = 'Transactions';
$active_nav = 'transactions';
require_once __DIR__ . '/includes/header.php';

// Filters
$date_from  = $_GET['from']   ?? date('Y-m-01');
$date_to    = $_GET['to']     ?? date('Y-m-d');
$filter_type = $_GET['type']  ?? 'all';     // all | credit | debit
$search      = trim($_GET['q'] ?? '');
$page        = max(1, (int)($_GET['page'] ?? 1));
$per_page    = 50;
$offset      = ($page - 1) * $per_page;

// ─── Build query ────────────────────────────────────────────────────────
$where_parts  = ["u.organization_id = ?", "wt.wallet_type = 'meal_ticket'"];
$count_types  = "i";
$count_vals   = [$org_id];

if ($date_from && $date_to) {
    $where_parts[]  = "DATE(wt.created_at) BETWEEN ? AND ?";
    $count_types   .= "ss";
    $count_vals[]   = $date_from;
    $count_vals[]   = $date_to;
}

if ($filter_type !== 'all') {
    $where_parts[]  = "wt.type = ?";
    $count_types   .= "s";
    $count_vals[]   = $filter_type;
}

if ($search) {
    $where_parts[]  = "(u.name LIKE ? OR wt.description LIKE ? OR wt.reference LIKE ?)";
    $count_types   .= "sss";
    $like           = "%{$search}%";
    $count_vals[]   = $like;
    $count_vals[]   = $like;
    $count_vals[]   = $like;
}

$where = implode(' AND ', $where_parts);

// Total count
$count_sql = "SELECT COUNT(*) FROM wallet_transactions wt
              INNER JOIN users u ON wt.user_id=u.id
              WHERE {$where}";
$cnt_stmt = $conn->prepare($count_sql);
$cnt_stmt->bind_param($count_types, ...$count_vals);
$cnt_stmt->execute();
$total_count = (int)$cnt_stmt->get_result()->fetch_row()[0];
$total_pages = max(1, ceil($total_count / $per_page));

// Period totals
$totals_sql = "SELECT COALESCE(SUM(CASE WHEN wt.type='credit' THEN wt.amount ELSE 0 END),0) AS credits,
                      COALESCE(SUM(CASE WHEN wt.type='debit' THEN wt.amount ELSE 0 END),0) AS debits
               FROM wallet_transactions wt
               INNER JOIN users u ON wt.user_id=u.id
               WHERE {$where}";
$tot_stmt = $conn->prepare($totals_sql);
$tot_stmt->bind_param($count_types, ...$count_vals);
$tot_stmt->execute();
[$period_credits, $period_debits] = $tot_stmt->get_result()->fetch_row();

// Paginated results
$main_sql = "SELECT wt.*, u.name AS staff_name, u.employee_id
             FROM wallet_transactions wt
             INNER JOIN users u ON wt.user_id=u.id
             WHERE {$where}
             ORDER BY wt.created_at DESC
             LIMIT ? OFFSET ?";
$main_types = $count_types . "ii";
$main_vals  = array_merge($count_vals, [$per_page, $offset]);
$main_stmt  = $conn->prepare($main_sql);
$main_stmt->bind_param($main_types, ...$main_vals);
$main_stmt->execute();
$transactions = $main_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>

<div class="anim-up">

<!-- Header -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h2 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em">Meal Ticket Transactions</h2>
    <p style="font-size:.84rem;color:var(--text-muted);margin-top:3px"><?php echo number_format($total_count); ?> transaction<?php echo $total_count!=1?'s':''; ?> · <?php echo fmt_date($date_from); ?> — <?php echo fmt_date($date_to); ?></p>
  </div>
</div>

<!-- Period summary -->
<div class="stat-grid" style="grid-template-columns:repeat(3,1fr);margin-bottom:20px">
  <div class="stat-card" style="border-top:3px solid var(--success)">
    <div class="stat-label">Total Credits</div>
    <div class="stat-value" style="font-size:1.2rem;color:var(--success)"><?php echo fmt_money($period_credits); ?></div>
    <div class="stat-sub">Meal tickets funded</div>
  </div>
  <div class="stat-card" style="border-top:3px solid var(--error)">
    <div class="stat-label">Total Debits</div>
    <div class="stat-value" style="font-size:1.2rem;color:var(--error)"><?php echo fmt_money($period_debits); ?></div>
    <div class="stat-sub">Spent by staff</div>
  </div>
  <div class="stat-card" style="border-top:3px solid var(--primary)">
    <div class="stat-label">Net</div>
    <div class="stat-value" style="font-size:1.2rem;color:var(--primary)"><?php echo fmt_money($period_credits - $period_debits); ?></div>
    <div class="stat-sub">Credits minus debits</div>
  </div>
</div>

<!-- Filters -->
<div class="card card-body" style="padding:14px 18px;margin-bottom:16px">
  <form method="GET" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
    <div style="flex:1;min-width:200px;position:relative">
      <svg style="position:absolute;left:12px;top:50%;transform:translateY(-50%);width:15px;height:15px;stroke:var(--text-light);fill:none" viewBox="0 0 24 24" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
      <input type="text" name="q" value="<?php echo h($search); ?>" placeholder="Search staff, description, reference…" class="form-control" style="padding-left:38px">
    </div>
    <input type="date" name="from" value="<?php echo h($date_from); ?>" class="form-control" style="width:148px">
    <input type="date" name="to" value="<?php echo h($date_to); ?>" class="form-control" style="width:148px">
    <select name="type" class="form-control" style="width:auto;min-width:120px">
      <option value="all"    <?php echo $filter_type==='all'?'selected':''; ?>>All Types</option>
      <option value="credit" <?php echo $filter_type==='credit'?'selected':''; ?>>Credits Only</option>
      <option value="debit"  <?php echo $filter_type==='debit'?'selected':''; ?>>Debits Only</option>
    </select>
    <button type="submit" class="btn btn-secondary btn-md">Filter</button>
    <?php if ($search || $filter_type!=='all' || $date_from!==date('Y-m-01') || $date_to!==date('Y-m-d')): ?>
    <a href="transactions.php" class="btn btn-secondary btn-md">Clear</a>
    <?php endif; ?>
    <!-- Preset ranges -->
    <div style="display:flex;gap:6px;margin-left:auto">
      <a href="?from=<?php echo date('Y-m-01'); ?>&to=<?php echo date('Y-m-d'); ?>" class="btn btn-secondary btn-sm">This Month</a>
      <a href="?from=<?php echo date('Y-m-01',strtotime('-1 month')); ?>&to=<?php echo date('Y-m-t',strtotime('-1 month')); ?>" class="btn btn-secondary btn-sm">Last Month</a>
    </div>
  </form>
</div>

<!-- Transaction table -->
<div class="card">
  <?php if (empty($transactions)): ?>
  <div style="text-align:center;padding:56px 24px">
    <p style="font-weight:700;margin-bottom:6px">No transactions found</p>
    <p style="font-size:.82rem;color:var(--text-muted)">Try adjusting the date range or filters</p>
  </div>
  <?php else: ?>
  <div style="overflow-x:auto">
    <table class="data-table">
      <thead>
        <tr>
          <th>Date & Time</th>
          <th>Staff</th>
          <th>Description</th>
          <th>Type</th>
          <th>Amount</th>
          <th>Status</th>
          <th>Reference</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($transactions as $t): ?>
        <tr>
          <td style="font-size:.78rem;color:var(--text-muted);white-space:nowrap"><?php echo fmt_datetime($t['created_at']); ?></td>
          <td>
            <div style="font-weight:600;font-size:.84rem"><?php echo h($t['staff_name']); ?></div>
            <?php if ($t['employee_id']): ?>
            <div style="font-size:.7rem;color:var(--text-muted);font-family:monospace"><?php echo h($t['employee_id']); ?></div>
            <?php endif; ?>
          </td>
          <td style="font-size:.82rem;max-width:240px"><?php echo h($t['description']); ?></td>
          <td><span class="badge <?php echo $t['type']==='credit'?'badge-success':'badge-error'; ?>"><?php echo ucfirst($t['type']); ?></span></td>
          <td style="font-weight:700;color:<?php echo $t['type']==='credit'?'var(--success)':'var(--error)'; ?>;white-space:nowrap">
            <?php echo ($t['type']==='credit'?'+':'−') . fmt_money($t['amount']); ?>
          </td>
          <td><span class="badge badge-muted"><?php echo ucfirst($t['status']); ?></span></td>
          <td style="font-size:.68rem;color:var(--text-muted);font-family:monospace;max-width:140px;word-break:break-all"><?php echo h($t['reference']); ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  <?php if ($total_pages > 1): ?>
  <div style="padding:16px 20px;border-top:1px solid var(--border);display:flex;align-items:center;justify-content:space-between">
    <span style="font-size:.8rem;color:var(--text-muted)">
      Showing <?php echo number_format(($page-1)*$per_page+1); ?>–<?php echo number_format(min($page*$per_page,$total_count)); ?> of <?php echo number_format($total_count); ?>
    </span>
    <div style="display:flex;gap:6px">
      <?php
      $qs = http_build_query(array_filter(['q'=>$search,'from'=>$date_from,'to'=>$date_to,'type'=>$filter_type!=='all'?$filter_type:null]));
      if ($page > 1): ?>
      <a href="?<?php echo $qs; ?>&page=<?php echo $page-1; ?>" class="btn btn-secondary btn-sm">← Prev</a>
      <?php endif;
      // Show window of pages
      for ($p = max(1,$page-2); $p <= min($total_pages,$page+2); $p++): ?>
      <a href="?<?php echo $qs; ?>&page=<?php echo $p; ?>" class="btn btn-sm <?php echo $p===$page?'btn-org':'btn-secondary'; ?>"><?php echo $p; ?></a>
      <?php endfor;
      if ($page < $total_pages): ?>
      <a href="?<?php echo $qs; ?>&page=<?php echo $page+1; ?>" class="btn btn-secondary btn-sm">Next →</a>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

  <?php endif; ?>
</div>

</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
