<?php
/**
 * MTEngine License Re-activation Page
 *
 * This page handles LICENSE RE-ACTIVATION only (e.g. after domain migration).
 * It is NOT the full installer.
 *
 * For full installation, use: /install/
 *
 * Access:
 *   - Blocked automatically once storage/installed.lock exists (InstallerGuard)
 *   - Only available before installation or when manually triggered for re-activation
 */

define('ROOT_PATH', realpath(__DIR__ . '/../../'));

require_once ROOT_PATH . '/core/system/Env.php';
require_once ROOT_PATH . '/core/system/InstallerGuard.php';

\Core\System\Env::bootstrap(ROOT_PATH);
ini_set('display_errors', \Core\System\Env::isDebug() ? '1' : '0');
error_reporting(E_ALL);

if (!\Core\System\InstallerGuard::canRunInstaller()) {
    http_response_code(404);
    exit('Installer is disabled.');
}

$helpersPath = ROOT_PATH . '/core/app/Helpers/';
foreach (glob($helpersPath . '*.php') as $file) {
    require_once $file;
}

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';

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

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

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

$currentLangCode = Language::code();
$dir             = Language::direction();

$error = '';

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

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

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

            if (($res['status'] ?? '') !== 'active' || ($res['action'] ?? '') === 'block') {
                $msg = (string)($res['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 {
                try {
                    $pdo = db();
                    $stmt = $pdo->prepare("SELECT id FROM settings WHERE setting_key = ? LIMIT 1");
                    $stmt->execute(['license_key']);
                    $exists = $stmt->fetchColumn();

                    if ($exists) {
                        $upd = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ? LIMIT 1");
                        $upd->execute([$licenseKey, 'license_key']);
                    } else {
                        $ins = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)");
                        $ins->execute(['license_key', $licenseKey]);
                    }
                } catch (\Throwable $e) {
                    // silent — settings table may not exist on fresh install path
                }

                LicenseStorage::save([
                    'license_key'   => $licenseKey,
                    'status'        => 'active',
                    'type'          => $res['type'] ?? null,
                    'expires'       => $res['expires'] ?? null,
                    'domain_bound'  => $res['domain_bound'] ?? null,
                    'max_domains'   => (int)($res['max_domains'] ?? 0),
                    'domains_used'  => (int)($res['domains_used'] ?? 0),
                    'checked_at'    => time(),
                    'last_ok_at'    => time(),
                    'ttl'           => 3600,
                    'failures'      => 0,
                ]);

                \Core\System\InstallerGuard::ensureLockFile();
                header('Location: ' . ($home === '' ? '/' : $home . '/'));
                exit;
            }
        } 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">
    <title><?= __('install.title', 'MTEngine Activation') ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex, nofollow">
    <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() ?>">
    <style>
        body{background:var(--light,#f5f6f8);display:flex;align-items:center;justify-content:center;height:100vh;margin:0;color:var(--dark,#16161d);}
        .box{background:#fff;padding:30px;width:100%;max-width:420px;border-radius:12px;box-shadow:0 10px 30px rgba(0,0,0,.08);border:1px solid rgba(0,0,0,.06);}
        h2{margin:0 0 10px;}
        p{color:rgba(0,0,0,.55);margin-bottom:20px;line-height:1.6;}
        input{width:100%;padding:12px;margin-bottom:15px;border:1px solid rgba(0,0,0,.15);border-radius:10px;font-size:14px;box-sizing:border-box;outline:none;font-family:inherit;font-weight:400;}
        input:focus{border-color:var(--primary,#598aee);box-shadow:0 0 0 4px rgba(89,138,238,.18);}
        button{width:100%;padding:12px;background:var(--primary,#598aee);color:#fff;border:0;border-radius:10px;cursor:pointer;font-size:16px;font-family:inherit;font-weight:700;}
        button:hover{opacity:.92;}
        .error{background:rgba(247,24,46,.10);color:var(--secondary,#f7182e);padding:12px;border-radius:10px;margin-bottom:15px;font-size:14px;border:1px solid rgba(247,24,46,.20);font-family:inherit;}
        .footer{margin-top:15px;font-size:12px;color:rgba(0,0,0,.45);text-align:center;}
        .note{margin-bottom:16px;font-size:12px;color:rgba(0,0,0,.45);padding:10px 12px;background:rgba(89,138,238,.06);border-radius:8px;border:1px solid rgba(89,138,238,.15);}
    </style>
</head>
<body>
<div class="box">
    <h2><?= __('install.heading', 'Activate MTEngine') ?></h2>
    <p><?= __('install.description', 'Please enter your license key to activate the product.') ?></p>

    <div class="note">
        <?= __('install.reactivation_note', 'This page is for license re-activation only. For a fresh installation, use /install/') ?>
    </div>

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

    <form method="post">
        <?= Csrf::field() ?>
        <input type="text"
               name="license_key"
               placeholder="<?= __('install.license_placeholder', 'License Key') ?>"
               required>
        <button type="submit"><?= __('install.activate_button', 'Activate') ?></button>
    </form>

    <div class="footer">
        &copy; <?= date('Y') ?> MTEngine
    </div>
</div>
</body>
</html>
