<?php
require_once __DIR__ . '/../includes/header.php';
require_admin();

if (isset($_GET['recheck'])) {
    @unlink(LICENSE_CACHE_FILE);
    header('Location: ' . BASE_URL . 'index.php?page=admin_license&rechecked=1');
    exit;
}

$lic        = license_check();
$status     = $lic['status']        ?? 'unknown';
$message    = $lic['message']       ?? '';
$customer   = $lic['customer_name'] ?? '';
$expires    = $lic['expires_at']    ?? '';
$cachedAt   = $lic['cached_at']     ?? null;
$rechecked  = isset($_GET['rechecked']);

$statusConfig = [
    'ok'              => ['color' => '#22c55e', 'bg' => 'rgba(34,197,94,.08)',  'border' => 'rgba(34,197,94,.25)',  'label' => 'Ativa',           'icon' => 'check_circle',  'dot' => '#22c55e'],
    'warning'         => ['color' => '#f59e0b', 'bg' => 'rgba(245,158,11,.08)', 'border' => 'rgba(245,158,11,.25)', 'label' => 'Em Carência',     'icon' => 'warning',       'dot' => '#f59e0b'],
    'offline_warning' => ['color' => '#f59e0b', 'bg' => 'rgba(245,158,11,.08)', 'border' => 'rgba(245,158,11,.25)', 'label' => 'Modo Offline',    'icon' => 'wifi_off',      'dot' => '#f59e0b'],
    'blocked'         => ['color' => '#ef4444', 'bg' => 'rgba(239,68,68,.08)',  'border' => 'rgba(239,68,68,.25)',  'label' => 'Bloqueada',       'icon' => 'block',         'dot' => '#ef4444'],
    'no_key'          => ['color' => '#94a3b8', 'bg' => 'rgba(148,163,184,.06)','border' => 'rgba(148,163,184,.2)', 'label' => 'Não configurada', 'icon' => 'key_off',       'dot' => '#94a3b8'],
];
$cfg = $statusConfig[$status] ?? ['color' => '#94a3b8', 'bg' => 'rgba(148,163,184,.06)', 'border' => 'rgba(148,163,184,.2)', 'label' => ucfirst($status), 'icon' => 'help', 'dot' => '#94a3b8'];

$key = LICENSE_KEY;
$keyMasked = $key ? preg_replace('/^([A-Z2-9]{5}-[A-Z2-9]{5}-[A-Z2-9]{5}-)/', '●●●●●-●●●●●-●●●●●-', $key) : '—';

$daysLeft = null;
$totalDays = null;
if ($expires) {
    $expDt  = new DateTime($expires);
    $today  = new DateTime('today');
    $diff   = $today->diff($expDt);
    $daysLeft = $diff->invert ? -$diff->days : $diff->days;
    // Assume licença anual para barra de progresso
    $totalDays = 365;
}

$daysColor = '#22c55e';
if ($daysLeft !== null) {
    if ($daysLeft < 0)  $daysColor = '#ef4444';
    elseif ($daysLeft < 7)  $daysColor = '#ef4444';
    elseif ($daysLeft < 30) $daysColor = '#f59e0b';
}

$progressPct = 0;
if ($daysLeft !== null && $totalDays > 0) {
    $progressPct = max(0, min(100, round(($daysLeft / $totalDays) * 100)));
}
?>

<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Round" rel="stylesheet">

<style>
.lic-page { max-width: 700px; }
.lic-page h2 { font-size: 1.25rem; font-weight: 700; margin-bottom: 1.75rem; display: flex; align-items: center; gap: .6rem; }

/* Hero card */
.lic-hero {
    background: <?= $cfg['bg'] ?>;
    border: 1px solid <?= $cfg['border'] ?>;
    border-radius: 16px;
    padding: 1.75rem;
    margin-bottom: 1.25rem;
    position: relative;
    overflow: hidden;
}
.lic-hero::before {
    content: '';
    position: absolute;
    top: -60px; right: -60px;
    width: 180px; height: 180px;
    border-radius: 50%;
    background: <?= $cfg['color'] ?>;
    opacity: .04;
}
.lic-status-row {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.5rem;
}
.lic-status-icon {
    width: 52px; height: 52px;
    border-radius: 14px;
    background: <?= $cfg['color'] ?>22;
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
}
.lic-status-icon .material-icons-round { font-size: 26px; color: <?= $cfg['color'] ?>; }
.lic-status-label { font-size: 1.3rem; font-weight: 700; color: <?= $cfg['color'] ?>; line-height: 1.2; }
.lic-status-sub { font-size: .82rem; color: var(--text-secondary); margin-top: .2rem; line-height: 1.4; }

/* Info grid */
.lic-grid { display: grid; grid-template-columns: 1fr 1fr; gap: .875rem; }
.lic-cell {
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: .875rem 1rem;
}
.lic-cell-label {
    font-size: .7rem;
    font-weight: 600;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: .06em;
    margin-bottom: .35rem;
    display: flex; align-items: center; gap: .3rem;
}
.lic-cell-label .material-icons-round { font-size: 13px; }
.lic-cell-value { font-size: .95rem; font-weight: 600; color: var(--text); }
.lic-cell-value.mono { font-family: monospace; color: #fbbf24; font-size: .88rem; letter-spacing: .03em; }

/* Progress bar */
.lic-progress-wrap { margin-top: 1.25rem; }
.lic-progress-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: .4rem; font-size: .78rem; color: var(--text-secondary); }
.lic-progress-bar { height: 6px; background: var(--border); border-radius: 99px; overflow: hidden; }
.lic-progress-fill {
    height: 100%;
    width: <?= $progressPct ?>%;
    background: <?= $daysColor ?>;
    border-radius: 99px;
    transition: width .4s ease;
}

/* Actions */
.lic-actions { display: flex; gap: .75rem; flex-wrap: wrap; margin-bottom: 1.25rem; }
.lic-btn {
    display: inline-flex; align-items: center; gap: .4rem;
    padding: .6rem 1.15rem;
    border-radius: 8px;
    font-size: .875rem; font-weight: 500;
    text-decoration: none; border: none; cursor: pointer;
    transition: opacity .15s, transform .1s;
}
.lic-btn:hover { opacity: .88; transform: translateY(-1px); }
.lic-btn.primary { background: #0ea5e9; color: #fff; }
.lic-btn.purple  { background: #7c3aed; color: #fff; }
.lic-btn.ghost   { background: var(--card); color: var(--text); border: 1px solid var(--border); }
.lic-btn .material-icons-round { font-size: 16px; }

/* Alert banner */
.lic-alert {
    border-radius: 10px;
    padding: .875rem 1rem;
    font-size: .85rem;
    display: flex; align-items: flex-start; gap: .65rem;
    border: 1px solid;
}
.lic-alert .material-icons-round { font-size: 18px; margin-top: 1px; flex-shrink: 0; }
.lic-alert.warn  { background: rgba(245,158,11,.08); border-color: rgba(245,158,11,.3); color: #fcd34d; }
.lic-alert.ok    { background: rgba(34,197,94,.08);  border-color: rgba(34,197,94,.3);  color: #86efac; }

@media (max-width: 480px) {
    .lic-grid { grid-template-columns: 1fr; }
    .lic-actions { flex-direction: column; }
    .lic-btn { justify-content: center; }
}
</style>

<div class="lic-page">

    <h2>
        <span class="material-icons-round" style="color:<?= $cfg['color'] ?>">verified_user</span>
        Licença do Sistema
    </h2>

    <?php if ($rechecked): ?>
    <div class="lic-alert ok" style="margin-bottom:1.25rem">
        <span class="material-icons-round">check_circle</span>
        <span>Licença reverificada com o servidor agora.</span>
    </div>
    <?php endif; ?>

    <!-- Hero -->
    <div class="lic-hero">
        <div class="lic-status-row">
            <div class="lic-status-icon">
                <span class="material-icons-round"><?= $cfg['icon'] ?></span>
            </div>
            <div>
                <div class="lic-status-label"><?= $cfg['label'] ?></div>
                <div class="lic-status-sub">
                    <?php if ($message): ?>
                        <?= h($message) ?>
                    <?php else: ?>
                        Licença válida e verificada com o servidor
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="lic-grid">
            <div class="lic-cell">
                <div class="lic-cell-label">
                    <span class="material-icons-round">person</span> Cliente
                </div>
                <div class="lic-cell-value"><?= $customer ? h($customer) : '—' ?></div>
            </div>
            <div class="lic-cell">
                <div class="lic-cell-label">
                    <span class="material-icons-round">event</span> Validade
                </div>
                <div class="lic-cell-value">
                    <?php if ($expires): ?>
                        <?= date('d/m/Y', strtotime($expires)) ?>
                        <?php if ($daysLeft !== null): ?>
                            <span style="font-size:.78rem;color:<?= $daysColor ?>;margin-left:.35rem;font-weight:500">
                                (<?= $daysLeft >= 0 ? $daysLeft . ' dias' : abs($daysLeft) . ' dias atrás' ?>)
                            </span>
                        <?php endif; ?>
                    <?php else: ?>—<?php endif; ?>
                </div>
            </div>
            <div class="lic-cell">
                <div class="lic-cell-label">
                    <span class="material-icons-round">key</span> Chave
                </div>
                <div class="lic-cell-value mono"><?= h($keyMasked) ?></div>
            </div>
            <div class="lic-cell">
                <div class="lic-cell-label">
                    <span class="material-icons-round">schedule</span> Última verificação
                </div>
                <div class="lic-cell-value" style="font-size:.88rem">
                    <?= $cachedAt ? date('d/m/Y H:i', $cachedAt) : 'Nunca' ?>
                </div>
            </div>
        </div>

        <?php if ($daysLeft !== null && $daysLeft >= 0): ?>
        <div class="lic-progress-wrap">
            <div class="lic-progress-header">
                <span>Tempo de licença restante</span>
                <span style="color:<?= $daysColor ?>;font-weight:600"><?= $progressPct ?>%</span>
            </div>
            <div class="lic-progress-bar">
                <div class="lic-progress-fill"></div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Ações -->
    <div class="lic-actions">
        <a href="<?= BASE_URL ?>index.php?page=admin_license&recheck=1" class="lic-btn primary">
            <span class="material-icons-round">sync</span>
            Verificar agora
        </a>
        <?php if (in_array($status, ['blocked', 'no_key', 'warning'])): ?>
        <a href="<?= BASE_URL ?>index.php?page=license_activate" class="lic-btn purple">
            <span class="material-icons-round">key</span>
            Inserir nova chave
        </a>
        <?php endif; ?>
        <a href="https://monitorping.com.br" target="_blank" class="lic-btn ghost">
            <span class="material-icons-round">open_in_new</span>
            Renovar licença
        </a>
    </div>

    <?php if ($status === 'warning'): ?>
    <div class="lic-alert warn">
        <span class="material-icons-round">warning</span>
        <span>Sua licença venceu. O sistema continua funcionando durante o período de carência.
            <a href="https://monitorping.com.br" target="_blank" style="color:#fbbf24;margin-left:.35rem">Renovar agora →</a>
        </span>
    </div>
    <?php elseif ($status === 'offline_warning'): ?>
    <div class="lic-alert warn">
        <span class="material-icons-round">wifi_off</span>
        <span>Servidor de licenças inacessível há mais de 48h. Verifique a conexão do servidor com a internet.</span>
    </div>
    <?php endif; ?>

</div>

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