<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('include/header.php');
$page_title = WEB_NAME . " | Card Transaction History";

// ── Pagination & Filters ──────────────────────────────────────
$per_page     = 25;
$cur_page     = max(1, (int)(isset($_GET['page'])   ? $_GET['page']   : 1));
$offset       = ($cur_page - 1) * $per_page;
$search       = trim(isset($_GET['q'])      ? $_GET['q']      : '');
$filter_type  = trim(isset($_GET['type'])   ? $_GET['type']   : '');
$filter_status= trim(isset($_GET['status']) ? $_GET['status'] : '');
$filter_from  = trim(isset($_GET['from'])   ? $_GET['from']   : '');
$filter_to    = trim(isset($_GET['to'])     ? $_GET['to']     : '');

$where  = array();
$params = array();

if ($search !== '') {
    $where[]        = "(u.full_name LIKE :q OR u.email LIKE :q2 OR vct.card_id LIKE :q3 OR vct.description LIKE :q4 OR vct.reference LIKE :q5)";
    $params[':q']   = "%{$search}%";
    $params[':q2']  = "%{$search}%";
    $params[':q3']  = "%{$search}%";
    $params[':q4']  = "%{$search}%";
    $params[':q5']  = "%{$search}%";
}
if ($filter_type !== '') {
    $where[]           = "vct.type = :type";
    $params[':type']   = $filter_type;
}
if ($filter_status !== '') {
    $where[]             = "vct.status = :status";
    $params[':status']   = $filter_status;
}
if ($filter_from !== '') {
    $where[]           = "DATE(vct.created_at) >= :dfrom";
    $params[':dfrom']  = $filter_from;
}
if ($filter_to !== '') {
    $where[]         = "DATE(vct.created_at) <= :dto";
    $params[':dto']  = $filter_to;
}

$sql_where = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

// ── Counts & rows ─────────────────────────────────────────────
$tot_stmt = $pdo->prepare(
    "SELECT COUNT(*) FROM virtual_card_transactions vct
     LEFT JOIN users u ON u.id = vct.user_id
     {$sql_where}"
);
$tot_stmt->execute($params);
$total_rows  = (int)$tot_stmt->fetchColumn();
$total_pages = max(1, ceil($total_rows / $per_page));

$txn_stmt = $pdo->prepare(
    "SELECT vct.*, u.full_name AS user_name, u.email AS user_email
     FROM virtual_card_transactions vct
     LEFT JOIN users u ON u.id = vct.user_id
     {$sql_where}
     ORDER BY vct.id DESC
     LIMIT " . (int)$per_page . " OFFSET " . (int)$offset
);
$txn_stmt->execute($params);
$txns = $txn_stmt->fetchAll(PDO::FETCH_ASSOC);

// ── Summary stats (always across full dataset, ignoring filters) ─
$summary_row = $pdo->query("SELECT
    COUNT(*)                                                        AS total_txns,
    SUM(CASE WHEN type='fund'     THEN amount_usd ELSE 0 END)      AS total_funded_usd,
    SUM(CASE WHEN type='spend'    THEN amount_usd ELSE 0 END)      AS total_spent_usd,
    SUM(CASE WHEN type='withdraw' THEN amount_usd ELSE 0 END)      AS total_withdrawn_usd,
    SUM(CASE WHEN type='fee'      THEN amount_ngn ELSE 0 END)      AS total_fees_ngn,
    SUM(CASE WHEN type='fund'     THEN amount_ngn ELSE 0 END)      AS total_funded_ngn,
    COUNT(CASE WHEN status='failed' THEN 1 END)                    AS failed_txns,
    COUNT(DISTINCT user_id)                                        AS unique_users
    FROM virtual_card_transactions")->fetch(PDO::FETCH_ASSOC);

$summary = $summary_row ? $summary_row : array_fill_keys(
    array('total_txns','total_funded_usd','total_spent_usd','total_withdrawn_usd',
          'total_fees_ngn','total_funded_ngn','failed_txns','unique_users'), 0
);
?>
<title><?php echo htmlspecialchars($page_title); ?></title>

<div class="container-fluid" id="container-wrapper">

  <!-- ── Breadcrumb ──────────────────────────────────────────── -->
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <div>
      <h1 class="h3 mb-0 text-gray-800">
        <i class="fas fa-list mr-2" style="color:#047857"></i>Card Transaction History
      </h1>
      <small class="text-muted">All platform virtual card transactions — fund, spend, withdraw, fee</small>
    </div>
    <ol class="breadcrumb mb-0">
      <li class="breadcrumb-item"><a href="dashboard">Home</a></li>
      <li class="breadcrumb-item"><a href="virtual-cards">Virtual Cards</a></li>
      <li class="breadcrumb-item active">Transactions</li>
    </ol>
  </div>

  <!-- ── Summary Stats ───────────────────────────────────────── -->
  <div class="row mb-4">
    <?php
    $stat_cards = array(
        array('fas fa-receipt',       'primary',   number_format(isset($summary['total_txns'])           ? $summary['total_txns']           : 0),                                     'Total Transactions'),
        array('fas fa-users',         'info',      number_format(isset($summary['unique_users'])         ? $summary['unique_users']         : 0),                                     'Unique Users'),
        array('fas fa-plus-circle',   'success',   '$'.number_format(isset($summary['total_funded_usd']) ? $summary['total_funded_usd']     : 0, 2),                                  'Total Funded (USD)'),
        array('fas fa-naira-sign',    'success',   '&#8358;'.number_format(isset($summary['total_funded_ngn']) ? $summary['total_funded_ngn'] : 0, 2),                               'Total Funded (NGN)'),
        array('fas fa-shopping-cart', 'danger',    '$'.number_format(isset($summary['total_spent_usd'])  ? $summary['total_spent_usd']      : 0, 2),                                  'Total Spent (USD)'),
        array('fas fa-arrow-left',    'warning',   '$'.number_format(isset($summary['total_withdrawn_usd']) ? $summary['total_withdrawn_usd'] : 0, 2),                               'Total Withdrawn'),
        array('fas fa-tag',           'secondary', '&#8358;'.number_format(isset($summary['total_fees_ngn'])  ? $summary['total_fees_ngn']  : 0, 2),                                 'Total Fees (NGN)'),
        array('fas fa-times-circle',  'danger',    number_format(isset($summary['failed_txns'])          ? $summary['failed_txns']          : 0),                                     'Failed'),
    );
    foreach ($stat_cards as $sc):
        $ic  = $sc[0]; $col = $sc[1]; $val = $sc[2]; $lbl = $sc[3];
    ?>
    <div class="col-xl-3 col-md-4 col-sm-6 mb-3">
      <div class="card border-left-<?php echo $col; ?> shadow h-100 py-2">
        <div class="card-body py-2">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-<?php echo $col; ?> text-uppercase mb-1"><?php echo $lbl; ?></div>
              <div class="h6 mb-0 font-weight-bold text-gray-800"><?php echo $val; ?></div>
            </div>
            <div class="col-auto"><i class="<?php echo $ic; ?> fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- ── Main Table Card ─────────────────────────────────────── -->
  <div class="card shadow mb-4">
    <div class="card-header py-3 d-flex align-items-center justify-content-between"
         style="background:linear-gradient(135deg,#064e3b,#065f46);color:#fff;">
      <h6 class="m-0 font-weight-bold">
        <i class="fas fa-list mr-2"></i>All Card Transactions
      </h6>
      <span class="badge badge-light"><?php echo number_format($total_rows); ?> record<?php echo $total_rows !== 1 ? 's' : ''; ?></span>
    </div>
    <div class="card-body">

      <!-- ── Search & Filters ─────────────────────────────────── -->
      <form method="GET" class="mb-4">
        <div class="row">
          <div class="col-md-4 mb-2">
            <input type="text" name="q" class="form-control form-control-sm"
                   placeholder="Search user, email, card ID, description…"
                   value="<?php echo htmlspecialchars($search); ?>">
          </div>
          <div class="col-md-2 mb-2">
            <select name="type" class="form-control form-control-sm">
              <option value="">All Types</option>
              <?php foreach (array('fund'=>'Fund','spend'=>'Spend','withdraw'=>'Withdraw','fee'=>'Fee','refund'=>'Refund','reversal'=>'Reversal') as $v=>$l): ?>
              <option value="<?php echo $v; ?>" <?php echo $filter_type===$v?'selected':''; ?>><?php echo $l; ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-2 mb-2">
            <select name="status" class="form-control form-control-sm">
              <option value="">All Statuses</option>
              <option value="completed" <?php echo $filter_status==='completed'?'selected':''; ?>>Completed</option>
              <option value="pending"   <?php echo $filter_status==='pending'  ?'selected':''; ?>>Pending</option>
              <option value="failed"    <?php echo $filter_status==='failed'   ?'selected':''; ?>>Failed</option>
              <option value="reversed"  <?php echo $filter_status==='reversed' ?'selected':''; ?>>Reversed</option>
            </select>
          </div>
          <div class="col-md-2 mb-2">
            <input type="date" name="from" class="form-control form-control-sm"
                   value="<?php echo htmlspecialchars($filter_from); ?>" title="From date">
          </div>
          <div class="col-md-2 mb-2">
            <input type="date" name="to" class="form-control form-control-sm"
                   value="<?php echo htmlspecialchars($filter_to); ?>" title="To date">
          </div>
        </div>
        <div class="row">
          <div class="col-md-12">
            <button type="submit" class="btn btn-sm btn-success mr-2">
              <i class="fas fa-search mr-1"></i>Search / Filter
            </button>
            <?php if ($search || $filter_type || $filter_status || $filter_from || $filter_to): ?>
            <a href="card-transactions" class="btn btn-sm btn-secondary mr-2">
              <i class="fas fa-times mr-1"></i>Clear Filters
            </a>
            <?php endif; ?>
            <a href="admin-virtual-cards" class="btn btn-sm btn-outline-secondary">
              <i class="fas fa-arrow-left mr-1"></i>Back to Virtual Cards
            </a>
          </div>
        </div>
      </form>

      <!-- ── Table ────────────────────────────────────────────── -->
      <div class="table-responsive">
        <table class="table table-sm table-bordered table-hover" style="font-size:.81rem">
          <thead class="thead-light">
            <tr>
              <th style="width:50px">#</th>
              <th>User</th>
              <th>Card ID</th>
              <th style="width:90px">Type</th>
              <th>USD</th>
              <th>NGN</th>
              <th>Rate</th>
              <th>Description</th>
              <th style="width:90px">Status</th>
              <th style="width:130px">Date</th>
            </tr>
          </thead>
          <tbody>
          <?php if (empty($txns)): ?>
            <tr>
              <td colspan="10" class="text-center text-muted py-4">
                <i class="fas fa-inbox fa-2x mb-2 d-block"></i>No transactions found.
              </td>
            </tr>
          <?php else: ?>
            <?php foreach ($txns as $t):
                $t_type = isset($t['type']) ? $t['type'] : '';
                if ($t_type === 'fund')                                   $type_color = 'success';
                elseif ($t_type === 'spend')                              $type_color = 'danger';
                elseif ($t_type === 'withdraw')                           $type_color = 'warning';
                elseif ($t_type === 'fee')                                $type_color = 'secondary';
                elseif ($t_type === 'refund' || $t_type === 'reversal')   $type_color = 'info';
                else                                                      $type_color = 'secondary';

                if ($t_type === 'fund')                                   $type_icon = 'fa-plus';
                elseif ($t_type === 'spend')                              $type_icon = 'fa-minus';
                elseif ($t_type === 'withdraw')                           $type_icon = 'fa-arrow-left';
                elseif ($t_type === 'fee')                                $type_icon = 'fa-tag';
                elseif ($t_type === 'refund' || $t_type === 'reversal')   $type_icon = 'fa-rotate-left';
                else                                                      $type_icon = 'fa-circle';

                $t_status = isset($t['status']) ? $t['status'] : '';
                if ($t_status === 'completed')      $status_color = 'success';
                elseif ($t_status === 'pending')    $status_color = 'warning';
                elseif ($t_status === 'failed')     $status_color = 'danger';
                elseif ($t_status === 'reversed')   $status_color = 'info';
                else                                $status_color = 'secondary';
            ?>
            <tr>
              <td><?php echo $t['id']; ?></td>
              <td>
                <strong><?php echo htmlspecialchars(isset($t['user_name']) ? $t['user_name'] : 'N/A'); ?></strong><br>
                <small class="text-muted"><?php echo htmlspecialchars(isset($t['user_email']) ? $t['user_email'] : ''); ?></small>
              </td>
              <td>
                <code style="font-size:.7rem" title="<?php echo htmlspecialchars($t['card_id']); ?>">
                  <?php echo htmlspecialchars(substr($t['card_id'], 0, 14)); ?>…
                </code>
              </td>
              <td>
                <span class="badge badge-<?php echo $type_color; ?>">
                  <i class="fas <?php echo $type_icon; ?> mr-1"></i><?php echo ucfirst($t['type']); ?>
                </span>
              </td>
              <td>
                <strong style="color:<?php echo in_array($t['type'],['fund','refund','reversal']) ? '#047857' : '#dc3545'; ?>">
                  <?php echo in_array($t['type'],['fund','refund','reversal']) ? '+' : '-'; ?>$<?php echo number_format($t['amount_usd'], 2); ?>
                </strong>
              </td>
              <td>
                <span style="color:<?php echo in_array($t['type'],['fund','refund','reversal']) ? '#dc3545' : '#047857'; ?>">
                  <?php echo in_array($t['type'],['fund','fee']) ? '-' : '+'; ?>₦<?php echo number_format($t['amount_ngn'], 2); ?>
                </span>
              </td>
              <td><?php echo number_format($t['rate_used'], 2); ?></td>
              <td><?php echo htmlspecialchars(isset($t['description']) ? $t['description'] : '—'); ?></td>
              <td>
                <span class="badge badge-<?php echo $status_color; ?>">
                  <?php echo ucfirst($t['status']); ?>
                </span>
              </td>
              <td style="white-space:nowrap">
                <?php echo date('d M Y', strtotime($t['created_at'])); ?><br>
                <small class="text-muted"><?php echo date('H:i:s', strtotime($t['created_at'])); ?></small>
              </td>
            </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- ── Pagination ───────────────────────────────────────── -->
      <?php if ($total_pages > 1): ?>
      <div class="d-flex align-items-center justify-content-between mt-3 flex-wrap" style="gap:.5rem;">
        <small class="text-muted">
          Showing <?php echo number_format(($cur_page - 1) * $per_page + 1); ?>–<?php echo number_format(min($cur_page * $per_page, $total_rows)); ?>
          of <?php echo number_format($total_rows); ?> records
        </small>
        <nav>
          <ul class="pagination pagination-sm mb-0 flex-wrap">
            <?php if ($cur_page > 1): ?>
            <li class="page-item">
              <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $cur_page - 1))); ?>">
                <i class="fas fa-chevron-left"></i>
              </a>
            </li>
            <?php endif; ?>

            <?php
            // Show smart window of page numbers
            $start = max(1, $cur_page - 3);
            $end   = min($total_pages, $cur_page + 3);
            if ($start > 1): ?>
            <li class="page-item">
              <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => 1))); ?>">1</a>
            </li>
            <?php if ($start > 2): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; ?>
            <?php endif; ?>

            <?php for ($i = $start; $i <= $end; $i++): ?>
            <li class="page-item <?php echo $i === $cur_page ? 'active' : ''; ?>">
              <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $i))); ?>"><?php echo $i; ?></a>
            </li>
            <?php endfor; ?>

            <?php if ($end < $total_pages): ?>
            <?php if ($end < $total_pages - 1): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; ?>
            <li class="page-item">
              <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $total_pages))); ?>"><?php echo $total_pages; ?></a>
            </li>
            <?php endif; ?>

            <?php if ($cur_page < $total_pages): ?>
            <li class="page-item">
              <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $cur_page + 1))); ?>">
                <i class="fas fa-chevron-right"></i>
              </a>
            </li>
            <?php endif; ?>
          </ul>
        </nav>
      </div>
      <?php endif; ?>

    </div>
  </div>

</div>

<?php include('include/footer.php'); ?>