<?php
$active = 'otp';
$pageTitle = 'OTP Logs';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$phone = trim($_GET['phone'] ?? '');
$purpose = $_GET['purpose'] ?? '';

$where = [];
$params = [];
if ($phone !== '') { $where[] = "phone LIKE ?"; $params[] = "%$phone%"; }
if ($purpose && in_array($purpose, ['login','register'])) { $where[] = "purpose=?"; $params[] = $purpose; }

$sql = "SELECT * FROM otp_codes";
if ($where) $sql .= " WHERE " . implode(" AND ", $where);
$sql .= " ORDER BY created_at DESC LIMIT 200";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalCount = (int)$pdo->query("SELECT COUNT(*) FROM otp_codes")->fetchColumn();
?>
<div class="page-header">
  <h1>OTP Logs</h1>
  <p class="subtitle">Vendor login/register OTP history (<?php echo $totalCount; ?> total)</p>
</div>

<form class="row g-2 mb-3">
  <div class="col-md-2"><input class="form-control" name="phone" placeholder="Phone" value="<?php echo htmlspecialchars($phone); ?>"></div>
  <div class="col-md-2"><select class="form-select" name="purpose"><option value="">All</option><option value="login" <?php echo $purpose==='login'?'selected':''; ?>>Login</option><option value="register" <?php echo $purpose==='register'?'selected':''; ?>>Register</option></select></div>
  <div class="col-auto"><button class="btn btn-dark" type="submit">Filter</button></div>
</form>

<div class="card">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>ID</th><th>Phone</th><th>OTP</th><th>Purpose</th><th>Created</th><th>Expires</th><th>Status</th></tr></thead>
        <tbody>
          <?php foreach ($logs as $t): ?>
          <tr>
            <td>#<?php echo $t['id']; ?></td>
            <td><?php echo htmlspecialchars($t['phone']); ?></td>
            <td><code><?php echo htmlspecialchars($t['otp']); ?></code></td>
            <td><span class="badge bg-<?php echo $t['purpose']==='login'?'primary':'secondary'; ?>"><?php echo $t['purpose']; ?></span></td>
            <td class="small"><?php echo date('M d, H:i', strtotime($t['created_at'])); ?></td>
            <td class="small"><?php echo date('M d, H:i', strtotime($t['expires_at'])); ?></td>
            <td><span class="badge bg-<?php echo strtotime($t['expires_at']) > time() ? 'success' : 'secondary'; ?>"><?php echo strtotime($t['expires_at']) > time() ? 'Valid' : 'Expired'; ?></span></td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($logs)): ?><tr><td colspan="7" class="text-muted">No OTP logs</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
