<?php
// step6_activation.php

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

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';
require_once ROOT_PATH . '/core/system/License/ViolationsReporter.php';

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

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

$error = '';
$success = '';

$__vr = new ViolationsReporter();

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

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

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

            if (!is_array($res) || empty($res['status'])) {
                $__vr->report('activation_server_unreachable');
                $error = __('install.server_unreachable', 'License server unreachable. Please try again later.');
                goto __activation_done;
            }

            if (($res['status'] ?? '') !== 'active' || ($res['action'] ?? '') === 'block') {
                if (($res['action'] ?? '') === 'block') { $__vr->report('activation_blocked'); }
                $msg = (string)($res['message'] ?? '');
                if ($msg === 'invalid_signature') {
                    $error = __('install.invalid_signature', 'Security validation failed. Please contact support.');
                    $__vr->report('activation_invalid_signature');
                } elseif ($msg !== '') {
                    $error = $msg;
                    $__vr->report('activation_blocked_or_invalid');
                } else {
                    $error = __('install.activation_failed', 'Activation failed.');
                }
            } else {
                // Store license in DB settings table
                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]);
                    }
                    __activation_done:
        } catch (\Throwable $e) {
                    // if DB write fails, still allow activation storage file
                }

                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,
                ]);

                // ✅ Mark activation success in session so we can allow step 7
                $_SESSION['install']['activation_done'] = true;
                $_SESSION['install']['license_key'] = $licenseKey;

                // Redirect to next step
                header("Location: index.php?step=7");
                exit;
            }
        } catch (Throwable $e) {
            $error = __('install.server_unreachable', 'Server unreachable. Please try again.');
        }
    }
}
?>

<div class="card shadow-sm border-0">
    <div class="card-body p-4">
        <h4 class="mb-2"><?= __('install.activate_heading', 'Activate Product') ?></h4>
        <p class="text-muted mb-4"><?= __('install.activate_desc', 'Enter your license key to activate the product. This step is required.') ?></p>

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

        <form method="post" class="needs-validation" novalidate>
            <?= Csrf::field() ?>

            <div class="mb-3">
                <label class="form-label"><?= __('install.license_key', 'License Key') ?></label>
                <input type="text"
                       name="license_key"
                       class="form-control form-control-lg"
                       placeholder="<?= __('install.license_placeholder', 'Enter license key') ?>"
                       required>
                <div class="invalid-feedback">
                    <?= __('install.license_required', 'License key is required.') ?>
                </div>
            </div>

            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary btn-lg">
                    <?= __('install.activate_button', 'Activate & Continue') ?>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
// Bootstrap validation
(() => {
  'use strict';
  const forms = document.querySelectorAll('.needs-validation');
  Array.from(forms).forEach(form => {
    form.addEventListener('submit', event => {
      if (!form.checkValidity()) {
        event.preventDefault();
        event.stopPropagation();
      }
      form.classList.add('was-validated');
    }, false);
  });
})();
</script>
