<?php
// Variables expected from controller:
// $licenseKey, $licenseCache, $currentVersion

$licenseStatus = (string)($licenseCache['status'] ?? 'unknown');
$licenseAction = (string)($licenseCache['action'] ?? '');
$domainBound   = (string)($licenseCache['domain_bound'] ?? '');
$type          = (string)($licenseCache['type'] ?? '');
$expires       = $licenseCache['expires'] ?? null;
$maxDomains    = (int)($licenseCache['max_domains'] ?? 0);
$domainsUsed   = (int)($licenseCache['domains_used'] ?? 0);

$checkedAt     = (int)($licenseCache['checked_at'] ?? 0);
$lastOkAt      = (int)($licenseCache['last_ok_at'] ?? 0);
$pingOkAt      = (int)($licenseCache['ping_last_ok_at'] ?? 0);

function mte_mask_key(string $k): string {
    $k = trim($k);
    if ($k === '') return '—';
    if (strlen($k) <= 8) return $k;
    return substr($k, 0, 3) . str_repeat('*', max(0, strlen($k) - 7)) . substr($k, -4);
}

function mte_badge_class(string $status): string {
    $s = strtolower($status);
    if ($s === 'active') return 'bg-success';
    if ($s === 'expired') return 'bg-warning text-dark';
    if ($s === 'disabled') return 'bg-danger';
    if ($s === 'invalid') return 'bg-danger';
    return 'bg-secondary';
}

$err = $_GET['err'] ?? '';
$saved = $_GET['saved'] ?? '';
?>

<div class="content-wrapper">
<section class="content pt-3">

<style>
.mte-card {
    border-radius: 16px;
}
.mte-kv {
    display:flex;
    justify-content:space-between;
    gap:12px;
    padding:10px 0;
    border-bottom: 1px dashed rgba(0,0,0,.10);
}
.mte-kv:last-child { border-bottom:0; padding-bottom:0; }
.mte-kv .k { color: rgba(0,0,0,.55); }
.mte-kv .v { font-weight: 700; }
.mte-soft {
    background: rgba(13,110,253,.06);
    border: 1px solid rgba(13,110,253,.18);
    padding: 14px;
    border-radius: 14px;
}
.mte-actions-bar {
    position: sticky;
    bottom: 0;
    z-index: 1050;
    background: #fff;
    border-top: 1px solid rgba(0,0,0,.1);
    padding: 14px 24px;
}
</style>

<div class="container-fluid py-4">

    <div class="d-flex align-items-center justify-content-between mb-3">
        <h3 class="mb-0">
            <i class="bi bi-arrow-repeat me-2"></i>
            <?= __('sidebar.updates_license','Updates & License') ?>
        </h3>

        <span class="badge <?= mte_badge_class($licenseStatus) ?> px-3 py-2">
            <?= __('license.status','Status') ?>: <?= htmlspecialchars($licenseStatus) ?>
        </span>
    </div>

    <?php if ($saved): ?>
        <div class="alert alert-success">
            <i class="bi bi-check-circle me-1"></i>
            <?php
            if ($saved === 'verify_ok') echo __('license.verify_ok','License verified successfully.');
            elseif ($saved === 'ping_ok') echo __('license.ping_ok','Ping successful.');
            elseif ($saved === 'license_changed') echo __('license.changed_ok','License key updated successfully.');
            else echo __('ui.success','Success');
            ?>
        </div>
    <?php endif; ?>

    <?php if ($err): ?>
        <div class="alert alert-danger">
            <i class="bi bi-exclamation-triangle me-1"></i>
            <?php
            if ($err === 'missing_license') echo __('license.missing','License key is missing.');
            elseif ($err === 'server_unreachable') echo __('license.server_unreachable','License server unreachable. Please try again.');
            elseif ($err === 'license_blocked') echo __('license.blocked','License blocked. Please contact support.');
            elseif ($err === 'kill_switch_block') echo __('license.kill_switch','Access blocked by kill-switch.');
            elseif ($err === 'ping_failed') echo __('license.ping_failed','Ping failed. Please try again.');
            elseif ($err === 'license_required') echo __('install.license_required','License key is required.');
            elseif ($err === 'invalid_license') echo __('license.invalid','Invalid license key.');
            else echo __('ui.error','Error');
            ?>
        </div>
    <?php endif; ?>

    <ul class="nav nav-tabs mb-4">
        <li class="nav-item">
            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-license">
                <i class="bi bi-shield-check me-1"></i>
                <?= __('license.tab_license','License') ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-updates">
                <i class="bi bi-cloud-arrow-down me-1"></i>
                <?= __('license.tab_updates','Updates') ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-actions">
                <i class="bi bi-lightning-charge me-1"></i>
                <?= __('license.tab_actions','Actions') ?>
            </button>
        </li>
    </ul>

    <div class="tab-content">

        <!-- LICENSE -->
        <div class="tab-pane fade show active" id="tab-license">
            <div class="row g-4">

                <div class="col-lg-6">
                    <div class="card shadow-sm mte-card">
                        <div class="card-header fw-bold">
                            <i class="bi bi-key me-1"></i>
                            <?= __('license.overview','License Overview') ?>
                        </div>
                        <div class="card-body">

                            <div class="mte-kv">
                                <div class="k"><?= __('license.key','License Key') ?></div>
                                <div class="v"><?= htmlspecialchars(mte_mask_key((string)$licenseKey)) ?></div>
                            </div>

                            <div class="mte-kv">
                                <div class="k"><?= __('license.domain_bound','Domain Bound') ?></div>
                                <div class="v"><?= $domainBound !== '' ? htmlspecialchars($domainBound) : '—' ?></div>
                            </div>

                            <div class="mte-kv">
                                <div class="k"><?= __('license.type','Type') ?></div>
                                <div class="v"><?= $type !== '' ? htmlspecialchars($type) : '—' ?></div>
                            </div>

                            <div class="mte-kv">
                                <div class="k"><?= __('license.expires','Expires') ?></div>
                                <div class="v"><?= $expires ? htmlspecialchars((string)$expires) : __('license.never','Never') ?></div>
                            </div>

                            <div class="mte-kv">
                                <div class="k"><?= __('license.domains_used','Domains Used') ?></div>
                                <div class="v"><?= (int)$domainsUsed ?> / <?= (int)$maxDomains ?></div>
                            </div>

                        </div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="card shadow-sm mte-card">
                        <div class="card-header fw-bold">
                            <i class="bi bi-activity me-1"></i>
                            <?= __('license.health','License Health') ?>
                        </div>
                        <div class="card-body">

                            <div class="mte-soft mb-3">
                                <div class="fw-bold mb-1">
                                    <i class="bi bi-info-circle me-1"></i>
                                    <?= __('license.cache_info','Local license cache') ?>
                                </div>
                                <div class="text-muted">
                                    <?= __('license.cache_hint','This section shows your current cached state even if the server is offline.') ?>
                                </div>
                            </div>

                            <div class="mte-kv">
                                <div class="k"><?= __('license.last_verify','Last Verify') ?></div>
                                <div class="v"><?= $checkedAt ? date('Y-m-d H:i:s', $checkedAt) : '—' ?></div>
                            </div>

                            <div class="mte-kv">
                                <div class="k"><?= __('license.last_ok','Last OK') ?></div>
                                <div class="v"><?= $lastOkAt ? date('Y-m-d H:i:s', $lastOkAt) : '—' ?></div>
                            </div>

                            <div class="mte-kv">
                                <div class="k"><?= __('license.last_ping_ok','Last Ping OK') ?></div>
                                <div class="v"><?= $pingOkAt ? date('Y-m-d H:i:s', $pingOkAt) : '—' ?></div>
                            </div>

                            <div class="mte-kv">
                                <div class="k"><?= __('license.action','Action') ?></div>
                                <div class="v"><?= $licenseAction !== '' ? htmlspecialchars($licenseAction) : '—' ?></div>
                            </div>

                        </div>
                    </div>
                </div>

            </div>
        </div>

        <!-- UPDATES -->
        <div class="tab-pane fade" id="tab-updates">
            <div class="card shadow-sm mte-card">
                <div class="card-header fw-bold">
                    <i class="bi bi-cloud-arrow-down me-1"></i>
                    <?= __('license.updates','Updates') ?>
                </div>
                <div class="card-body">
                    <div class="row g-4">

                        <div class="col-md-4">
                            <div class="mte-soft">
                                <div class="text-muted"><?= __('license.current_version','Current Version') ?></div>
                                <div class="fs-4 fw-bold"><?= htmlspecialchars((string)$currentVersion) ?></div>
                            </div>
                        </div>

                        <div class="col-md-8">
                            <div class="alert alert-info mb-0">
                                <i class="bi bi-lightbulb me-1"></i>
                                <?= __('license.update_hint','Online update check will be enabled once the update endpoint is added on the license server.') ?>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>

        <!-- ACTIONS -->
        <div class="tab-pane fade" id="tab-actions">
            <div class="row g-4">

                <div class="col-lg-6">
                    <div class="card shadow-sm mte-card">
                        <div class="card-header fw-bold">
                            <i class="bi bi-arrow-repeat me-1"></i>
                            <?= __('license.actions','Actions') ?>
                        </div>
                        <div class="card-body">

                            <form method="POST" action="/admin/updates-license/verify-now" class="mb-3">
                                <?= \Core\System\Csrf::field(); ?>
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="bi bi-shield-check me-1"></i>
                                    <?= __('license.verify_now','Verify Now') ?>
                                </button>
                            </form>

                            <form method="POST" action="/admin/updates-license/ping-now" class="mb-3">
                                <?= \Core\System\Csrf::field(); ?>
                                <button type="submit" class="btn btn-outline-primary w-100">
                                    <i class="bi bi-lightning-charge me-1"></i>
                                    <?= __('license.ping_now','Ping Now') ?>
                                </button>
                            </form>

                            <div class="text-muted small">
                                <?= __('license.actions_hint','These actions refresh your license state instantly.') ?>
                            </div>

                        </div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="card shadow-sm mte-card">
                        <div class="card-header fw-bold">
                            <i class="bi bi-key me-1"></i>
                            <?= __('license.change_key','Change License Key') ?>
                        </div>
                        <div class="card-body">
                            <form method="POST" action="/admin/updates-license/change-key">
                                <?= \Core\System\Csrf::field(); ?>

                                <label class="form-label">
                                    <?= __('license.new_key','New License Key') ?>
                                </label>
                                <input type="text"
                                       name="license_key"
                                       class="form-control"
                                       placeholder="MT-XXXX-XXXX-XXXX"
                                       required>

                                <button type="submit" class="btn btn-success w-100 mt-3">
                                    <i class="bi bi-check2-circle me-1"></i>
                                    <?= __('license.change_apply','Verify & Apply') ?>
                                </button>

                                <div class="text-muted small mt-2">
                                    <?= __('license.change_key_hint','The key will not be saved unless verification succeeds.') ?>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

            </div>
        </div>

    </div>

</div>

</section>
</div>
