<?php

declare(strict_types=1);

require __DIR__ . '/app/bootstrap.php';

$error = '';
$returnUrl = trim((string) ($_GET['return'] ?? $_POST['return'] ?? 'index.php'));
if (!preg_match('#^(?:install\.php(?:\?mode=production)?|index\.php)$#', $returnUrl)) $returnUrl = 'index.php';
$productionInstallerReturn = str_starts_with($returnUrl, 'install.php');
if ($productionInstallerReturn) {
    $storedPath = __DIR__ . '/storage/license.key';
    $storedToken = is_file($storedPath) ? trim((string) file_get_contents($storedPath)) : '';
    $status = $storedToken !== ''
        ? dental_license_status($storedToken)
        : ['valid'=>false,'mode'=>'license_required','host'=>dental_current_host(),'message'=>'A signed production license must be activated before installation.'];
} else {
    $status = dental_license_status();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $token = trim((string) ($_POST['license_key'] ?? ''));
        $candidate = dental_license_status($token);
        if (!($candidate['valid'] ?? false)) {
            throw new RuntimeException((string) ($candidate['message'] ?? 'The license is invalid.'));
        }
        $storage = __DIR__ . '/storage';
        if (!is_dir($storage) && !mkdir($storage, 0775, true) && !is_dir($storage)) {
            throw new RuntimeException('The storage directory could not be created.');
        }
        if (file_put_contents($storage . '/license.key', $token, LOCK_EX) === false) {
            throw new RuntimeException('The license file could not be saved. Make storage writable.');
        }
        @chmod($storage . '/license.key', 0640);
        $status = $candidate;
        if (current_user()) {
            audit('license_activated', 'system', null, ['host' => dental_current_host(), 'license_id' => $candidate['payload']['license_id'] ?? null]);
        }
        flash('success', 'The license has been activated for this domain.');
        header('Location: ' . $returnUrl);
        exit;
    } catch (Throwable $exception) {
        $error = $exception->getMessage();
    }
}

$appName = (string) app_config('app.name', 'Dental Appointment and Records System');
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" href="public/favicon.svg" type="image/svg+xml">
<link rel="alternate icon" href="public/favicon.ico">
<title>License Activation · <?= e($appName) ?></title>
    <link rel="stylesheet" href="public/assets/css/install.css">
</head>
<body>
<main class="shell">
    <div class="brand"><div class="mark">DC</div><div><h1><?= e($appName) ?></h1><p>Domain license activation</p></div></div>
    <section class="panel">
        <?php if ($error !== ''): ?><div class="alert error"><?= e($error) ?></div><?php endif; ?>
        <?php if ($status['valid'] ?? false): ?>
            <div class="alert success"><?= e((string) $status['message']) ?></div>
            <h2>License active</h2>
            <div class="summary">
                <div>Domain</div><div><code><?= e((string) ($status['host'] ?? dental_current_host())) ?></code></div>
                <div>Authorization</div><div><?= e(ucwords(str_replace('_', ' ', (string) ($status['mode'] ?? 'licensed')))) ?></div>
                <?php if (!empty($status['payload']['expires_at'])): ?><div>Expires</div><div><?= e((string) $status['payload']['expires_at']) ?></div><?php endif; ?>
            </div>
            <div class="actions"><span></span><a class="button primary" href="<?= e($returnUrl) ?>"><?= str_starts_with($returnUrl,'install.php')?'Continue installation':'Open system' ?></a></div>
        <?php else: ?>
            <h2>A license is required</h2>
            <p class="lead">Every production installation requires a signed DentalCare license issued for the current domain.</p>
            <div class="summary">
                <div>Current domain</div><div><code><?= e(dental_current_host() ?: 'Unknown host') ?></code></div>
                <div>Status</div><div><?= e((string) ($status['message'] ?? 'License required')) ?></div>
            </div>
            <form method="post" style="margin-top:1.5rem">
                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="return" value="<?= e($returnUrl) ?>">
                <label>Signed license key<textarea name="license_key" rows="7" required placeholder="Paste the license key issued for this domain"></textarea></label>
                <div class="actions"><a class="button secondary" href="mailto:licensing@syllabuild.org">Contact licensing</a><button class="primary" type="submit">Activate License</button></div>
            </form>
        <?php endif; ?>
    </section>
</main>
</body>
</html>
