<?php
define('ROOT_PATH', realpath(__DIR__ . '/../../'));

require_once ROOT_PATH . '/core/system/Env.php';
require_once ROOT_PATH . '/core/system/InstallerGuard.php';
require_once ROOT_PATH . '/core/system/Csrf.php';
require_once ROOT_PATH . '/core/system/Language.php';
require_once ROOT_PATH . '/core/system/License/Fingerprint.php';
require_once ROOT_PATH . '/core/system/License/LicenseClient.php';
require_once ROOT_PATH . '/core/system/License/LicenseStorage.php';

\Core\System\Env::bootstrap(ROOT_PATH);

$helpersPath = ROOT_PATH . '/core/app/Helpers/';
if (is_dir($helpersPath)) {
    foreach (glob($helpersPath . '*.php') ?: [] as $file) {
        require_once $file;
    }
}

use Core\System\Csrf;
use Core\System\Language;
use Core\System\InstallerGuard;
use Core\System\License\Fingerprint;
use Core\System\License\LicenseClient;
use Core\System\License\LicenseStorage;

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!InstallerGuard::isInstalled()) {
    header('Location: /install', true, 302);
    exit;
}

$currentLangCode = Language::code();
$dir = Language::direction();
$reasonKey = trim((string)($_GET['reason'] ?? ''));
$reasonText = $reasonKey !== '' ? __('license.reason.' . $reasonKey, '') : '';
$error = '';
$success = '';

$base = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
if ($base === '' || $base === '.') { $base = ''; }

$home = $base === '' ? '/' : $base . '/';

$licenseKey = '';

if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) === 'POST') {
    Csrf::check();

    $licenseKey = trim((string)($_POST['license_key'] ?? ''));

    if ($licenseKey === '') {
        $error = __('install.license_required', 'License key is required.');
    } else {
        try {
            $client = new LicenseClient();
            $verify = $client->verify($licenseKey);

            if (!is_array($verify) || (($verify['status'] ?? '') === '' && ($verify['action'] ?? '') === '')) {
                $verify = $client->ping($licenseKey, trim((string)($_SERVER['HTTP_HOST'] ?? '')), Fingerprint::generate());
            }

            if (!is_array($verify) || (($verify['status'] ?? '') !== 'active') || (($verify['action'] ?? '') === 'block')) {
                $msg = trim((string)($verify['message'] ?? ''));
                if ($msg === 'invalid_signature') {
                    $error = __('install.invalid_signature', 'Security validation failed. Please contact support.');
                } elseif ($msg !== '') {
                    $error = $msg;
                } else {
                    $error = __('install.activation_failed', 'Activation failed.');
                }
            } else {
                if (function_exists('db')) {
                    try {
                        $stmt = db()->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
                        $stmt->execute(['license_key', $licenseKey]);
                    } catch (\Throwable $e) {
                        // continue: license cache is the critical recovery state
                    }
                }

                LicenseStorage::saveVerifiedState($licenseKey, $verify, [
                    'recovered_at' => time(),
                    'recovery_reason' => $reasonKey,
                ]);

                $success = __('license.recovery.success', 'License recovered successfully.');
                header('Refresh: 1; url=' . $home);
            }
        } catch (\Throwable $e) {
            $error = __('install.server_unreachable', 'Server unreachable. Please try again.');
        }
    }
}
?>
<!doctype html>
<html lang="<?= htmlspecialchars($currentLangCode, ENT_QUOTES, 'UTF-8') ?>" dir="<?= htmlspecialchars($dir, ENT_QUOTES, 'UTF-8') ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= __('license.recovery.heading', 'License Recovery') ?></title>
    <link rel="stylesheet" href="/public/assets/theme/style-generated.css?v=<?= is_file(ROOT_PATH . '/public/assets/theme/style-generated.css') ? filemtime(ROOT_PATH . '/public/assets/theme/style-generated.css') : time() ?>">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <?php if ($dir === 'rtl'): ?>
        <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
        <style>
            body { font-family: "Cairo", sans-serif; }
        </style>
    <?php endif; ?>
    <style>
        body{
            background: var(--light, #f5f6f8);
            color: var(--dark, #16161d);
        }
        .recover-wrap{
            max-width: 760px;
            margin: 30px auto;
            padding: 0 12px;
        }
        .step-pill{
            font-size: 12px;
            padding: 6px 10px;
            border-radius: 999px;
            background: rgba(0,0,0,.06);
        }
        .card{
            border: 0;
            border-radius: 14px;
            box-shadow: 0 10px 25px rgba(0,0,0,.06);
        }
        .btn-lg{
            border-radius: 12px;
            padding: 12px 18px;
        }
        .form-control-lg{
            border-radius: 12px;
        }
        .hint{
            font-size: .95rem;
            color: #6b7280;
        }
    </style>
</head>
<body>
<div class="recover-wrap">
    <div class="d-flex align-items-center justify-content-between mb-3">
        <div>
            <div class="step-pill mb-2"><?= __('license.recovery.badge', 'Recovery') ?></div>
            <h3 class="mb-0"><?= __('license.recovery.heading', 'License Recovery') ?></h3>
            <div class="text-muted"><?= __('license.recovery.subtitle', 'This site is installed, but its local license state needs to be recovered from the license server.') ?></div>
        </div>
    </div>

    <div class="row justify-content-center">
        <div class="col-12">
            <div class="card">
                <div class="card-body p-4 p-md-5">

                    <?php if ($reasonText !== ''): ?>
                        <div class="alert alert-warning"><?= htmlspecialchars($reasonText, ENT_QUOTES, 'UTF-8') ?></div>
                    <?php endif; ?>

                    <?php if ($error !== ''): ?>
                        <div class="alert alert-danger"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
                    <?php endif; ?>

                    <?php if ($success !== ''): ?>
                        <div class="alert alert-success mb-0"><?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?></div>
                    <?php else: ?>
                        <form method="post" novalidate>
                            <?= Csrf::field() ?>
                            <div class="mb-3">
                                <label class="form-label"><?= __('license.recovery.license_key', 'License Key') ?></label>
                                <input type="text" name="license_key" class="form-control form-control-lg" value="<?= htmlspecialchars($licenseKey, ENT_QUOTES, 'UTF-8') ?>" placeholder="<?= __('license.recovery.license_placeholder', 'Enter license key') ?>" required>
                            </div>
                            <div class="hint mb-4"><?= __('license.recovery.description', 'Enter your license key to rebuild the local activation state securely from the license server.') ?></div>
                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-primary btn-lg"><?= __('license.recovery.button', 'Recover License') ?></button>
                                <a href="<?= htmlspecialchars($home, ENT_QUOTES, 'UTF-8') ?>" class="btn btn-outline-secondary btn-lg"><?= __('common.back', 'Back') ?></a>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
