<?php
define('SKIP_LICENSE_CHECK', true);
session_start();

require_once 'config/license.php';
require_once 'includes/license.php';

$domain  = _normalizeDomain($_SERVER['HTTP_HOST'] ?? 'localhost');
$success = false;
$error   = '';
$info    = '';

// Read current key from config file (for display)
$config_file    = __DIR__ . '/config/license.php';
$current_key    = defined('LICENSE_KEY') ? LICENSE_KEY : '';
$is_placeholder = ($current_key === '' || $current_key === '8RVQG-RF3B7-UKY24-GDMN7');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input_key = trim($_POST['license_key'] ?? '');

    if ($input_key === '') {
        $error = 'Please enter a license key.';
    } else {
        // Try to verify with server
        $result = _queryServer($domain, $input_key);

        if ($result === null) {
            $error = 'Could not reach the license server. Check your internet connection and try again.';
        } elseif ($result['status'] === 'valid') {
            // Write key into config file
            $new_config = file_get_contents($config_file);
            $new_config = preg_replace(
                "/define\('LICENSE_KEY',\s*'[^']*'\);/",
                "define('LICENSE_KEY', '" . addslashes($input_key) . "');",
                $new_config
            );
            if (file_put_contents($config_file, $new_config) !== false) {
                // Write valid cache so we don't immediately re-check
                _writeCache($domain, 'valid', 'Activated successfully.');
                $success = true;
            } else {
                // Can't write file — show manual instructions
                $info = $input_key;
                $error = 'Verification succeeded but the config file is not writable. '
                       . 'Please manually set LICENSE_KEY in config/license.php (see below).';
            }
        } else {
            $msgs = [
                'not_found'  => 'License key not found or not registered for domain: <strong>' . htmlspecialchars($domain) . '</strong>',
                'suspended'  => 'This license has been suspended. Contact tmitstore.com support.',
                'expired'    => 'This license has expired. Contact tmitstore.com to renew.',
                'tampered'   => 'License server response is invalid. Contact support.',
            ];
            $code  = $result['status'] ?? 'invalid';
            $error = $msgs[$code] ?? htmlspecialchars($result['message'] ?? 'License verification failed.');
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Activate License — ISP Stock Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body { background: linear-gradient(135deg, #0d6efd 0%, #0056b3 100%);
               min-height: 100vh; display: flex; align-items: center; justify-content: center; }
        .act-card { max-width: 520px; width: 100%; border-radius: 1rem; padding: 2rem; }
    </style>
</head>
<body>
<div class="act-card card shadow-lg mx-3">

    <div class="text-center mb-4">
        <i class="bi bi-key text-primary" style="font-size:3rem;"></i>
        <h3 class="fw-bold mt-2">Activate ISP Stock Manager</h3>
        <p class="text-muted small mb-0">Enter the license key you received from tmitstore.com</p>
    </div>

    <!-- Domain info -->
    <div class="alert alert-info d-flex gap-2 align-items-center py-2 mb-3">
        <i class="bi bi-globe2"></i>
        <span>
            License will be registered for domain:
            <strong><?= htmlspecialchars($domain) ?></strong>
        </span>
    </div>

    <?php if ($success): ?>
    <!-- ===== Success ===== -->
    <div class="alert alert-success text-center">
        <i class="bi bi-check-circle-fill fs-2 d-block mb-2"></i>
        <strong>License Activated Successfully!</strong><br>
        Your software is now licensed for <strong><?= htmlspecialchars($domain) ?></strong>.
    </div>
    <div class="d-grid mt-3">
        <a href="login.php" class="btn btn-primary fw-semibold py-2">
            <i class="bi bi-box-arrow-in-right me-1"></i> Go to Login
        </a>
    </div>

    <?php else: ?>
    <!-- ===== Activation Form ===== -->
    <?php if ($error !== ''): ?>
    <div class="alert alert-danger">
        <i class="bi bi-exclamation-triangle-fill me-2"></i>
        <?= $error ?>
    </div>
    <?php endif; ?>

    <?php if ($info !== ''): ?>
    <!-- Manual update instructions (when file is not writable) -->
    <div class="alert alert-warning small">
        <strong>Manual activation:</strong> Open <code>config/license.php</code> and change:
        <pre class="mt-2 mb-0 p-2 bg-light rounded">define('LICENSE_KEY', '<?= htmlspecialchars($info) ?>');</pre>
    </div>
    <?php endif; ?>

    <form method="POST" action="" novalidate>
        <div class="mb-3">
            <label for="license_key" class="form-label fw-semibold">License Key</label>
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-key"></i></span>
                <input type="text"
                       class="form-control font-monospace"
                       id="license_key"
                       name="license_key"
                       placeholder="XXXXX-XXXXX-XXXXX-XXXXX"
                       value="<?= htmlspecialchars(
                           !$is_placeholder ? $current_key : ($_POST['license_key'] ?? '')
                       ) ?>"
                       autocomplete="off"
                       required>
            </div>
            <div class="form-text">
                Purchase a license at <a href="https://tmitstore.com" target="_blank">tmitstore.com</a>
            </div>
        </div>

        <div class="d-grid">
            <button type="submit" class="btn btn-primary fw-semibold py-2">
                <i class="bi bi-shield-check me-1"></i> Verify &amp; Activate
            </button>
        </div>
    </form>

    <?php if (!$is_placeholder): ?>
    <div class="text-center mt-3">
        <a href="login.php" class="small text-muted">Already activated? Go to login →</a>
    </div>
    <?php endif; ?>

    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
