<?php
declare(strict_types=1);
require __DIR__ . '/lib/Auth.php';
require __DIR__ . '/lib/Layout.php';
require __DIR__ . '/../api/lib/Db.php';

use PSLauncher\Admin\Auth;
use PSLauncher\Admin\Layout;
use PSLauncher\Db;

Auth::requireLogin();
$config = require __DIR__ . '/../api/config.php';
$db = Db::get($config);

$stats = [
    'licenses_total'   => (int)$db->query('SELECT COUNT(*) FROM licenses')->fetchColumn(),
    'licenses_active'  => (int)$db->query('SELECT COUNT(*) FROM licenses WHERE revoked_at IS NULL AND download_entitlement_until >= NOW()')->fetchColumn(),
    'licenses_expired' => (int)$db->query('SELECT COUNT(*) FROM licenses WHERE revoked_at IS NULL AND download_entitlement_until < NOW()')->fetchColumn(),
    'licenses_revoked' => (int)$db->query('SELECT COUNT(*) FROM licenses WHERE revoked_at IS NOT NULL')->fetchColumn(),
    'machines_30d'     => (int)$db->query('SELECT COUNT(*) FROM license_machines WHERE last_seen >= DATE_SUB(NOW(), INTERVAL 30 DAY)')->fetchColumn(),
    'audit_24h'        => (int)$db->query('SELECT COUNT(*) FROM audit_log WHERE ts >= DATE_SUB(NOW(), INTERVAL 24 HOUR)')->fetchColumn(),
];

$manifestPath = dirname(__DIR__) . '/manifest/versions.json';
$manifest = is_file($manifestPath) ? json_decode(file_get_contents($manifestPath), true) : null;
$buildsDir = dirname(__DIR__) . '/builds';
$zips = is_dir($buildsDir) ? glob("$buildsDir/*.zip") : [];

$lastAudit = $db->query('SELECT * FROM audit_log ORDER BY id DESC LIMIT 10')->fetchAll();

Layout::header('Dashboard', 'dashboard');
?>
<h1>Dashboard</h1>

<div class="row">
    <div class="card col">
        <div class="kpi-label">Licenses actives</div>
        <div class="kpi" style="color: var(--installed)"><?= $stats['licenses_active'] ?></div>
    </div>
    <div class="card col">
        <div class="kpi-label">Expirées</div>
        <div class="kpi" style="color: var(--busy)"><?= $stats['licenses_expired'] ?></div>
    </div>
    <div class="card col">
        <div class="kpi-label">Révoquées</div>
        <div class="kpi" style="color: var(--danger)"><?= $stats['licenses_revoked'] ?></div>
    </div>
    <div class="card col">
        <div class="kpi-label">Machines vues (30j)</div>
        <div class="kpi"><?= $stats['machines_30d'] ?></div>
    </div>
    <div class="card col">
        <div class="kpi-label">Validations (24h)</div>
        <div class="kpi"><?= $stats['audit_24h'] ?></div>
    </div>
</div>

<h2>État du dépôt de versions</h2>
<div class="card">
    <p>
        <strong><?= count($manifest['versions'] ?? []) ?></strong> entrée(s) dans le manifest •
        <strong><?= count($zips) ?></strong> ZIP(s) dans <code>builds/</code> •
        signature manifest :
        <?= empty($manifest['signature'])
            ? "<span class='badge badge-warning'>NON SIGNÉ</span>"
            : "<span class='badge badge-success'>SIGNÉ Ed25519</span>" ?>
    </p>
    <?php if (!empty($manifest['versions'])): ?>
        <p class="muted">Dernière version annoncée : <code>v<?= htmlspecialchars($manifest['latest'] ?? '?') ?></code>
            (publiée le <?= htmlspecialchars(substr($manifest['publishedAt'] ?? '', 0, 10)) ?>)</p>
    <?php endif; ?>
    <a href="versions.php" class="btn btn-primary">Gérer les versions →</a>
</div>

<h2>Activité récente</h2>
<div class="card">
    <?php if (empty($lastAudit)): ?>
        <p class="muted">Aucune activité enregistrée.</p>
    <?php else: ?>
    <table>
        <thead><tr><th>Date</th><th>Événement</th><th>License</th><th>IP</th></tr></thead>
        <tbody>
        <?php foreach ($lastAudit as $row):
            $cls = match($row['event']) {
                'validate_ok'         => 'badge-success',
                'validate_invalid', 'validate_revoked', 'machine_limit' => 'badge-danger',
                'validate_expired'    => 'badge-warning',
                default                => 'badge-secondary',
            };
        ?>
            <tr>
                <td class="muted"><?= htmlspecialchars($row['ts']) ?></td>
                <td><span class="badge <?= $cls ?>"><?= htmlspecialchars($row['event']) ?></span></td>
                <td><?= $row['license_id'] ? '#' . htmlspecialchars((string)$row['license_id']) : '<span class="muted">—</span>' ?></td>
                <td class="muted"><?= htmlspecialchars($row['ip'] ?? '—') ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <a href="audit.php" class="btn btn-secondary" style="margin-top:16px">Voir tout →</a>
    <?php endif; ?>
</div>
<?php Layout::footer();
