<?php if (!defined('ADMIN_PATH')) { define('ADMIN_PATH', dirname(__DIR__)); } ?>

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

<style>
.ul-card { border-radius: 16px; }
.ul-soft {
    background: rgba(13,110,253,.06);
    border: 1px solid rgba(13,110,253,.18);
    padding: 16px;
    border-radius: 14px;
}
.ul-kv {
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap: 10px;
    padding: 10px 0;
    border-bottom: 1px dashed rgba(0,0,0,.08);
}
.ul-kv:last-child { border-bottom: 0; }
.ul-k { color: #6c757d; font-size: 13px; font-weight: 600; }
.ul-v { font-weight: 700; }
.ul-badge { font-size: 12px; padding: 6px 10px; border-radius: 999px; }

.ul-update-box {
    background: rgba(25,135,84,.06);
    border: 1px solid rgba(25,135,84,.18);
    border-radius: 14px;
    padding: 14px;
}
.ul-update-box-danger {
    background: rgba(220,53,69,.06);
    border: 1px solid rgba(220,53,69,.18);
    border-radius: 14px;
    padding: 14px;
}
</style>

<div class="container-fluid pb-5">

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

        <div class="d-flex gap-2">
            <form method="post" action="/admin/updates-license/verify-now">
                <?= \Core\System\Csrf::field(); ?>
                <button class="btn btn-outline-primary">
                    <i class="bi bi-shield-check me-1"></i>
                    <?= __('updates.verify_now','Verify Now') ?>
                </button>
            </form>

            <form method="post" action="/admin/updates-license/ping-now">
                <?= \Core\System\Csrf::field(); ?>
                <button class="btn btn-outline-secondary">
                    <i class="bi bi-broadcast me-1"></i>
                    <?= __('updates.ping_now','Ping Now') ?>
                </button>
            </form>
<?php
            if (class_exists('\\Core\\System\\PluginManager') && \Core\System\PluginManager::isActive('safe-updater')) {
                $suLang = ROOT_PATH . '/plugins/SafeUpdater/SafeUpdaterLang.php';
                if (is_file($suLang)) { require_once $suLang; }
            ?>
            <a href="/admin/safe-updater" class="btn btn-outline-dark">
                <i class="bi bi-shield-check me-1"></i>
                <?= function_exists('sut') ? sut('safe_updater.entry_button') : 'Safe Updater' ?>
            </a>
            <?php } ?>
        </div>
    </div>

    <?php if (isset($_GET['saved'])): ?>
        <div class="alert alert-success">
            <?= __('ui.success','Saved successfully!') ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['ping']) && $_GET['ping'] === 'ok'): ?>
        <div class="alert alert-info">
            <?= __('updates.ping_ok','Ping OK ✅') ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['err'])): ?>
        <div class="alert alert-danger">
            <?php
            $err = (string)$_GET['err'];
            $map = [
                'missing_key' => __('updates.err_missing_key','License key is missing.'),
                'invalid_key' => __('updates.err_invalid_key','License key is invalid.'),
                'server_unreachable' => __('updates.err_server_unreachable','License server unreachable.'),
                'blocked' => __('updates.err_blocked','License blocked or expired.'),
                'ping_failed' => __('updates.err_ping_failed','Ping failed.'),
            ];
            echo htmlspecialchars($map[$err] ?? $err, ENT_QUOTES, 'UTF-8');
            ?>
        </div>
    <?php endif; ?>

    <div class="row g-4">

        <!-- License Status -->
        <div class="col-lg-6">
            <div class="card shadow-sm ul-card">
                <div class="card-header fw-bold d-flex align-items-center justify-content-between">
                    <div>
                        <i class="bi bi-key-fill me-1"></i>
                        <?= __('updates.license_status','License Status') ?>
                    </div>

                    <?php
                    $st = (string)($cache['status'] ?? 'unknown');
                    $badgeClass = 'bg-secondary';
                    if ($st === 'active') $badgeClass = 'bg-success';
                    if ($st === 'expired') $badgeClass = 'bg-danger';
                    if ($st === 'disabled') $badgeClass = 'bg-danger';
                    ?>
                    <span class="badge <?= $badgeClass ?> ul-badge">
                        <?= htmlspecialchars($st, ENT_QUOTES, 'UTF-8') ?>
                    </span>
                </div>

                <div class="card-body">
                    <div class="ul-soft mb-3">
                        <div class="ul-kv">
                            <div class="ul-k"><?= __('updates.domain','Domain') ?></div>
                            <div class="ul-v"><?= htmlspecialchars((string)$domain, ENT_QUOTES, 'UTF-8') ?></div>
                        </div>

                        <div class="ul-kv">
                            <div class="ul-k"><?= __('updates.license_type','Type') ?></div>
                            <?php
$typeRaw = (string)($cache['type_original'] ?? '');
$typeKeyMap = [
    'single'   => 'license.type.single',
    'multi'    => 'license.type.multi',
    'trial'    => 'license.type.trial',
    'yearly'   => 'license.type.yearly',
    'lifetime' => 'license.type.lifetime',
];

$translatedType = $typeRaw !== '' && isset($typeKeyMap[$typeRaw])
    ? __($typeKeyMap[$typeRaw], ucfirst($typeRaw))
    : htmlspecialchars((string)($cache['type'] ?? '-'), ENT_QUOTES, 'UTF-8');
?>

<div class="ul-v"><?= $translatedType ?></div>

                        </div>

                        <div class="ul-kv">
                            <div class="ul-k"><?= __('updates.domain_bound','Bound Domain') ?></div>
                            <div class="ul-v"><?= htmlspecialchars((string)($cache['domain_bound'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></div>
                        </div>

                        <div class="ul-kv">
                            <div class="ul-k"><?= __('updates.expires','Expires') ?></div>
                            <div class="ul-v"><?= htmlspecialchars((string)($cache['expires'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></div>
                        </div>

                        <div class="ul-kv">
                            <div class="ul-k"><?= __('updates.domains_used','Domains Used') ?></div>
                            <div class="ul-v">
                                <?= (int)($cache['domains_used'] ?? 0) ?> / <?= (int)($cache['max_domains'] ?? 0) ?>
                            </div>
                        </div>
                    </div>

                    <div class="small text-muted">
                        <?= __('updates.last_check','Last Check') ?>:
                        <?= !empty($cache['checked_at']) ? date('Y-m-d H:i:s', (int)$cache['checked_at']) : '-' ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Change License Key -->
        <div class="col-lg-6">
            <div class="card shadow-sm ul-card">
                <div class="card-header fw-bold">
                    <i class="bi bi-arrow-left-right me-1"></i>
                    <?= __('updates.change_license','Change License Key') ?>
                </div>

                <div class="card-body">
                    <p class="text-muted mb-3">
                        <?= __('updates.change_license_desc','You can change your license key and re-activate safely without reinstalling.') ?>
                    </p>

                    <form method="post" action="/admin/updates-license/change-key">
                        <?= \Core\System\Csrf::field(); ?>

                        <label class="form-label">
                            <?= __('updates.license_key','License Key') ?>
                        </label>

                        <div class="input-group mb-3">
                            <span class="input-group-text"><i class="bi bi-key"></i></span>
                            <input type="text"
                                   name="license_key"
                                   class="form-control"
                                   value="<?= htmlspecialchars((string)$licenseKey, ENT_QUOTES, 'UTF-8') ?>"
                                   placeholder="<?= __('updates.license_key_placeholder','Enter your license key') ?>"
                                   required>
                        </div>

                        <button class="btn btn-primary w-100">
                            <i class="bi bi-check2-circle me-1"></i>
                            <?= __('updates.save_activate','Save & Activate') ?>
                        </button>
                    </form>

                    <hr class="my-4">

                    <div class="ul-soft">
                        <div class="ul-kv">
                            <div class="ul-k"><?= __('updates.fingerprint','Fingerprint') ?></div>
                            <div class="ul-v" style="font-size:12px;word-break:break-all">
                                <?= htmlspecialchars((string)$fingerprint, ENT_QUOTES, 'UTF-8') ?>
                            </div>
                        </div>
                    </div>

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

        <!-- Updates -->
        <div class="col-12">
            <div class="card shadow-sm ul-card">
                <div class="card-header fw-bold">
                    <i class="bi bi-cloud-download me-1"></i>
                    <?= __('updates.updates','Updates') ?>
                </div>

                <div class="card-body">

                    <div class="row g-3">

                        <div class="col-md-4">
                            <div class="ul-soft h-100">
                                <div class="ul-k"><?= __('updates.product','Product') ?></div>
                                <div class="ul-v fs-5 mt-1">
                                    <?= htmlspecialchars((string)$product, ENT_QUOTES, 'UTF-8') ?>
                                </div>
                                <div class="text-muted small mt-2">
                                    <?= __('updates.product_desc','Product identifier used for update checks.') ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="ul-soft h-100">
                                <div class="ul-k"><?= __('updates.current_version','Current Version') ?></div>
                                <div class="ul-v fs-4 mt-1">
                                    <?= htmlspecialchars((string)$currentVersion, ENT_QUOTES, 'UTF-8') ?>
                                </div>
                                <div class="text-muted small mt-2">
                                    <?= __('updates.current_version_desc','Installed version on this server.') ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="ul-soft h-100">
                                <div class="ul-k"><?= __('updates.latest_version','Latest Version') ?></div>
                                <div class="ul-v fs-4 mt-1">
                                    <?= htmlspecialchars((string)($latestVersion ?? '-'), ENT_QUOTES, 'UTF-8') ?>
                                </div>
                                <div class="text-muted small mt-2">
                                    <?= __('updates.latest_version_desc','Latest version available on update server.') ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="ul-soft h-100">
                                <div class="ul-k"><?= __('updates.update_status','Update Status') ?></div>

                                <?php
                                // ✅ تحديد الحالة حسب المتغيرات القادمة من الكونترولر
                                $isOnline = ($updatesStatus !== 'not_configured');
                                ?>

                                <div class="mt-2">
                                    <?php if (!$isOnline): ?>
                                        <span class="badge bg-secondary ul-badge">
                                            <?= __('updates.not_configured','Not configured yet') ?>
                                        </span>
                                    <?php else: ?>
                                        <?php if ($updateAvailable): ?>
                                            <span class="badge bg-success ul-badge">
                                                <?= __('updates.update_available','Update Available') ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-primary ul-badge">
                                                <?= __('updates.up_to_date','Up to date') ?>
                                            </span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>

                                <div class="text-muted small mt-2">
                                    <?php if (!$isOnline): ?>
                                        <?= __('updates.update_status_desc','We will enable update checking in the next step.') ?>
                                    <?php else: ?>
                                        <?= htmlspecialchars((string)($updateMessage ?? ''), ENT_QUOTES, 'UTF-8') ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                    </div>

                    <?php if ($isOnline && $updateAvailable): ?>
                        <div class="ul-update-box mt-4">
                            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                                <div>
                                    <div class="fw-bold mb-1">
                                        <i class="bi bi-stars me-1"></i>
                                        <?= __('updates.new_update','New Update') ?>
                                        <?= htmlspecialchars((string)$latestVersion, ENT_QUOTES, 'UTF-8') ?>
                                    </div>

                                    <?php if (!empty($updateTitle)): ?>
                                        <div class="text-muted small">
                                            <?= htmlspecialchars((string)$updateTitle, ENT_QUOTES, 'UTF-8') ?>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <?php if (!empty($updateDownloadUrl)): ?>
                                    <a class="btn btn-success"
                                       href="<?= htmlspecialchars((string)$updateDownloadUrl, ENT_QUOTES, 'UTF-8') ?>"
                                       target="_blank">
                                        <i class="bi bi-download me-1"></i>
                                        <?= __('updates.download','Download') ?>
                                    </a>
                                <?php endif; ?>
                            </div>

                            <?php if (!empty($updateNotes)): ?>
                                <hr>
                                <div style="white-space: pre-line">
                                    <?= htmlspecialchars((string)$updateNotes, ENT_QUOTES, 'UTF-8') ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php elseif ($isOnline && !$updateAvailable): ?>
                        <div class="ul-update-box mt-4">
                            <div class="fw-bold">
                                <i class="bi bi-check-circle me-1"></i>
                                <?= __('updates.no_update','No updates available. You are on the latest version.') ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if (!$isOnline): ?>
                        <div class="alert alert-warning mt-4 mb-0">
                            <i class="bi bi-info-circle me-1"></i>
                            <?= __('updates.note','Update server integration will be added next. This page is ready.') ?>
                        </div>
                    <?php endif; ?>

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

    </div>

</div>

</section>
</div>