<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();

$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$method = isset($_GET['method']) ? trim($_GET['method']) : '';
$q      = isset($_GET['q']) ? trim($_GET['q']) : '';

$where = [];
$params = [];

if ($status !== '') {
    $where[] = 'p.payment_status = ?';
    $params[] = $status;
}
if ($method !== '') {
    $where[] = 'p.payment_method = ?';
    $params[] = $method;
}
if ($q !== '') {
    $where[] = '(u.username LIKE ? OR u.email LIKE ? OR p.transaction_id LIKE ?)';
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
}

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

$payments = $db->getAll(
    "SELECT p.*, u.username, u.email, c.title AS course_title
     FROM payments p
     LEFT JOIN users u ON p.user_id = u.id
     LEFT JOIN courses c ON p.course_id = c.id
     $whereSql
     ORDER BY p.created_at DESC
     LIMIT 200",
    $params
);

$pageTitle = 'Payments';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Payments</h1>
    <p class="text-muted mb-0">View and filter payments</p>
  </div>
</div>

<div class="card mb-4">
  <div class="card-header">
    <form method="get" class="row g-3">
      <div class="col-sm-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="">All</option>
          <?php foreach (['pending','processing','completed','failed','cancelled','refunded'] as $opt): ?>
            <option value="<?php echo $opt; ?>" <?php echo $status===$opt?'selected':''; ?>><?php echo ucfirst($opt); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Method</label>
        <select name="method" class="form-select">
          <option value="">All</option>
          <?php foreach (['stripe','paypal','bank_transfer','mobile_money','free'] as $opt): ?>
            <option value="<?php echo $opt; ?>" <?php echo $method===$opt?'selected':''; ?>><?php echo ucwords(str_replace('_',' ',$opt)); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-4">
        <label class="form-label">Search</label>
        <input type="text" name="q" class="form-control" placeholder="username, email or transaction id" value="<?php echo htmlspecialchars($q); ?>">
      </div>
      <div class="col-sm-2 align-self-end">
        <button class="btn btn-primary w-100" type="submit">Filter</button>
      </div>
    </form>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped table-hover mb-0">
        <thead>
          <tr>
            <th>ID</th>
            <th>User</th>
            <th>Course</th>
            <th>Amount</th>
            <th>Currency</th>
            <th>Method</th>
            <th>Status</th>
            <th>Paid At</th>
            <th>Created</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$payments): ?>
            <tr><td colspan="9" class="text-center text-muted py-4">No payments found.</td></tr>
          <?php else: foreach ($payments as $p): ?>
            <tr>
              <td><?php echo (int)$p['id']; ?></td>
              <td>
                <?php echo htmlspecialchars($p['username'] ?? ''); ?><br>
                <small class="text-muted"><?php echo htmlspecialchars($p['email'] ?? ''); ?></small>
              </td>
              <td><?php echo htmlspecialchars($p['course_title'] ?? '-'); ?></td>
              <td>$<?php echo number_format((float)$p['amount'],2); ?></td>
              <td><?php echo htmlspecialchars($p['currency']); ?></td>
              <td><?php echo htmlspecialchars(ucwords(str_replace('_',' ',$p['payment_method']))); ?></td>
              <td>
                <span class="badge bg-<?php echo $p['payment_status']==='completed'?'success':($p['payment_status']==='failed'?'danger':'secondary'); ?>">
                  <?php echo htmlspecialchars(ucfirst($p['payment_status'])); ?>
                </span>
              </td>
              <td><?php echo $p['paid_at'] ? htmlspecialchars($p['paid_at']) : '-'; ?></td>
              <td><?php echo htmlspecialchars($p['created_at']); ?></td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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