<?php
/**
 * dashboard.php — Resumen: totales de dispositivos y últimos vistos.
 */

declare(strict_types=1);

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/themes.php';

require_login();

$pdo = db();
$today = gmdate('Y-m-d');

// Conteos. "Activo" = registrado, no bloqueado y (sin fecha o fecha futura).
$total      = (int) $pdo->query('SELECT COUNT(*) FROM devices')->fetchColumn();
$registered = (int) $pdo->query('SELECT COUNT(*) FROM devices WHERE registered = 1')->fetchColumn();

$activeStmt = $pdo->prepare(
    'SELECT COUNT(*) FROM devices
      WHERE registered = 1 AND locked = 0
        AND (sub_expire IS NULL OR sub_expire = "" OR sub_expire >= ?)'
);
$activeStmt->execute([$today]);
$active = (int) $activeStmt->fetchColumn();

$expiredStmt = $pdo->prepare(
    'SELECT COUNT(*) FROM devices
      WHERE sub_expire IS NOT NULL AND sub_expire != "" AND sub_expire < ?'
);
$expiredStmt->execute([$today]);
$expired = (int) $expiredStmt->fetchColumn();

// Últimos dispositivos por last_seen.
$recent = $pdo->query(
    'SELECT mac, device_key, registered, theme, sub_expire, last_seen
       FROM devices
      ORDER BY (last_seen IS NULL), last_seen DESC, id DESC
      LIMIT 10'
)->fetchAll();

$themes = theme_names();
$pageTitle = 'Dashboard';
require __DIR__ . '/lib/header.php';
?>

<div class="row g-3 mb-4">
    <div class="col-6 col-lg-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center justify-content-between">
                <div>
                    <div class="stat-label">Dispositivos</div>
                    <div class="stat-value"><?= $total ?></div>
                </div>
                <i class="la la-tv stat-icon text-primary"></i>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center justify-content-between">
                <div>
                    <div class="stat-label">Registrados</div>
                    <div class="stat-value"><?= $registered ?></div>
                </div>
                <i class="la la-check-circle stat-icon text-info"></i>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center justify-content-between">
                <div>
                    <div class="stat-label">Activos</div>
                    <div class="stat-value"><?= $active ?></div>
                </div>
                <i class="la la-bolt stat-icon text-success"></i>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center justify-content-between">
                <div>
                    <div class="stat-label">Expirados</div>
                    <div class="stat-value"><?= $expired ?></div>
                </div>
                <i class="la la-exclamation-triangle stat-icon text-danger"></i>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex align-items-center justify-content-between">
        <h2 class="h6 mb-0">Dispositivos recientes</h2>
        <a class="btn btn-sm btn-outline-secondary" href="devices.php">Ver todos <i class="la la-arrow-right"></i></a>
    </div>

    <?php if (count($recent) === 0): ?>
        <div class="card-body">
            <p class="text-body-secondary mb-0">Aún no hay dispositivos. Cuando la app contacte con <code>/api/device/config</code> aparecerán aquí.</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>MAC</th>
                        <th>Device key</th>
                        <th>Estado</th>
                        <th>Expira</th>
                        <th>Último acceso</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recent as $d): ?>
                        <tr>
                            <td class="mono"><?= e($d['mac']) ?></td>
                            <td class="mono"><?= e($d['device_key']) ?></td>
                            <td>
                                <?php if ((int) $d['registered'] === 1): ?>
                                    <span class="badge bg-success">Registrado</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Sin registrar</span>
                                <?php endif; ?>
                            </td>
                            <td class="mono"><?= e($d['sub_expire'] ?: '—') ?></td>
                            <td class="mono"><?= e($d['last_seen'] ?: '—') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php require __DIR__ . '/lib/footer.php'; ?>
