<?php
require_once __DIR__ . '/header.php';
global $pdo;

// Totales
$totalGiftcards = $pdo->query("SELECT COUNT(*) AS c FROM giftcards")->fetch()['c'] ?? 0;
$totalAmountRow = $pdo->query("SELECT SUM(amount) AS s FROM giftcards")->fetch();
$totalAmount    = $totalAmountRow['s'] ?? 0;
$totalCustomers = $pdo->query("SELECT COUNT(*) AS c FROM customers")->fetch()['c'] ?? 0;

// Ultimas giftcards
$stmt = $pdo->query("SELECT * FROM giftcards ORDER BY created_at DESC LIMIT 10");
$latest = $stmt->fetchAll();
?>
<h1 class="h4 mb-4">Dashboard</h1>

<div class="row mb-4">
  <div class="col-md-4">
    <div class="card text-bg-primary mb-3">
      <div class="card-body">
        <div class="card-title">Giftcards vendidas</div>
        <div class="display-6"><?php echo (int)$totalGiftcards; ?></div>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card text-bg-success mb-3">
      <div class="card-body">
        <div class="card-title">Monto total vendido</div>
        <div class="display-6">$<?php echo number_format($totalAmount,2); ?></div>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card text-bg-secondary mb-3">
      <div class="card-body">
        <div class="card-title">Clientes con puntos</div>
        <div class="display-6"><?php echo (int)$totalCustomers; ?></div>
      </div>
    </div>
  </div>
</div>

<h2 class="h5 mb-3">Últimas tarjetas vendidas</h2>
<div class="table-responsive">
  <table class="table table-sm">
    <thead>
      <tr>
        <th>Fecha</th>
        <th>Para</th>
        <th>De</th>
        <th>Monto</th>
        <th>Código</th>
        <th>Estado</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($latest as $g): ?>
        <tr>
          <td><?php echo htmlspecialchars($g['created_at']); ?></td>
          <td><?php echo htmlspecialchars($g['recipient_name']); ?></td>
          <td><?php echo htmlspecialchars($g['sender_name']); ?></td>
          <td>$<?php echo number_format($g['amount'],2); ?></td>
          <td><?php echo htmlspecialchars($g['code']); ?></td>
          <td><?php echo ((int)$g['is_valid']===1) ? 'Válida' : 'No válida'; ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

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