<?php
declare(strict_types=1);

require_once __DIR__ . '/../api/session-guard.php';
session_guard_start_session();

function h(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function activation_access_file(): string
{
    return dirname(__DIR__) . '/privatedata/access-tokens.json';
}

function activation_read_tokens(): array
{
    $file = activation_access_file();
    if (!is_file($file)) {
        return [];
    }

    $data = json_decode((string) file_get_contents($file), true);
    return is_array($data) ? $data : [];
}

function activation_write_tokens(array $tokens): void
{
    file_put_contents(
        activation_access_file(),
        json_encode($tokens, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT),
        LOCK_EX
    );
}

function clean_access_code(string $value): string
{
    $value = strtoupper(trim($value));
    return preg_replace('/[^A-Z0-9_-]/', '', $value) ?? '';
}

function clean_access_type(string $value): string
{
    $value = strtolower(trim($value));
    $allowed = ['premium', 'gift', 'asso', 'test'];

    return in_array($value, $allowed, true) ? $value : 'premium';
}

function activation_page(
    string $title,
    string $message,
    string $emoji = '🔒',
    int $status = 200,
    string $buttonLabel = 'Retour Chrono Party',
    string $buttonUrl = 'https://chrono-party.e-u.fr/'
): void {
    http_response_code($status);
    echo '<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>' . h($title) . '</title>
<style>
*{box-sizing:border-box}
body{margin:0;min-height:100vh;display:grid;place-items:center;background:linear-gradient(135deg,#160d3f,#31106a);color:#fff;font-family:Arial,Helvetica,sans-serif;padding:18px}
.box{width:min(600px,100%);padding:28px;border-radius:26px;background:rgba(255,255,255,.09);box-shadow:0 20px 80px rgba(0,0,0,.35);text-align:center}
.emoji{font-size:46px;margin-bottom:10px}
h1{font-size:26px;margin:0 0 12px}
p{line-height:1.55;color:rgba(255,255,255,.84);font-size:16px}
.btn{display:inline-block;margin-top:14px;padding:13px 20px;border-radius:999px;background:#7c5cff;color:white;text-decoration:none;font-weight:800}
</style>
</head>
<body>
<div class="box">
  <div class="emoji">' . h($emoji) . '</div>
  <h1>' . h($title) . '</h1>
  <p>' . h($message) . '</p>
  <a class="btn" href="' . h($buttonUrl) . '">' . h($buttonLabel) . '</a>
</div>
</body>
</html>';
    exit;
}

$gift = clean_access_code((string) ($_GET['gift'] ?? ''));

if ($gift === '') {
    activation_page(
        'Licence Chrono Party requise',
        'Pour jouer à Chrono Party, activez votre licence ou achetez un accès.',
        '🎁',
        400,
        '🎁 Acheter une licence',
        'https://buy.stripe.com/cNi28r1XPcjn9IM5YtgQE01'
    );
}

$tokens = activation_read_tokens();
$foundIndex = null;

foreach ($tokens as $i => $entry) {
    if (is_array($entry) && clean_access_code((string) ($entry['gift'] ?? '')) === $gift) {
        $foundIndex = $i;
        break;
    }
}

if ($foundIndex === null) {
    activation_page(
        'Licence non trouvée',
        'Ce lien n’est plus valide. Vous pouvez acheter une licence Chrono Party.',
        '🎁',
        404,
        '🎁 Acheter une licence',
        'https://buy.stripe.com/cNi28r1XPcjn9IM5YtgQE01'
    );
}

$entry = $tokens[$foundIndex];
$accessType = clean_access_type((string) ($entry['access_type'] ?? 'premium'));

$isActive = array_key_exists('active', $entry) ? (bool) $entry['active'] : true;
if (!$isActive) {
    activation_page(
        'Accès désactivé',
        'Ce code d’accès a été désactivé. Vous pouvez acheter une nouvelle licence Chrono Party.',
        '🔒',
        403,
        '🎁 Acheter une licence',
        'https://buy.stripe.com/cNi28r1XPcjn9IM5YtgQE01'
    );
}

$accessEnd = trim((string) ($entry['access_end'] ?? '2027-12-31'));
if ($accessEnd !== '' && date('Y-m-d') > $accessEnd) {
    activation_page('Accès expiré', 'Ce code d’accès n’est plus valable.', '⏳', 403);
}

$devicesRevision = (int) ($entry['devices_revision'] ?? 0);
$maxDevices = (int) ($entry['max_devices'] ?? 2);
if ($maxDevices <= 0) {
    $maxDevices = 2;
}

$clientName = trim((string) ($entry['label'] ?? ''));
if ($clientName === '') {
    $clientName = 'Code d’accès ' . $gift;
}

if (empty($entry['token'])) {
    $entry['token'] = bin2hex(random_bytes(20));
}

$entry['activated'] = true;
$entry['activated_at'] = $entry['activated_at'] ?? date('c');
$entry['last_used_at'] = date('c');
$tokens[$foundIndex] = $entry;
activation_write_tokens($tokens);

$clientId = 'gift-' . $gift;

$_SESSION['logged_in'] = true;
$_SESSION['client_id'] = $clientId;
$_SESSION['client_name'] = $clientName;
$_SESSION['access_end'] = $accessEnd;
$_SESSION['gift_code'] = $gift;
$_SESSION['access_type'] = $accessType;
$_SESSION['devices_revision'] = $devicesRevision;

$result = session_guard_authorize_current_device('gift:' . $gift, $clientName, $maxDevices);

if (empty($result['ok'])) {


    session_guard_revoke_remember_cookie_if_present();
    $_SESSION = [];

activation_page(
    'Limite d’appareils atteinte',
    'Ce code d’accès est déjà activé sur ' . $maxDevices . ' navigateurs/appareils. Pour continuer à jouer sur ce nouvel appareil, vous pouvez acheter une nouvelle licence Chrono Party.',
    '🔒',
    403,
    '🎁 Acheter une licence',
    'https://buy.stripe.com/cNi28r1XPcjn9IM5YtgQE01'
);
}

$_SESSION['device_status'] = $result['status'] ?? 'added';
$_SESSION['device_used'] = $result['used'] ?? 1;
$_SESSION['device_max'] = $result['max'] ?? 2;

session_guard_issue_remember_me_token($clientId, $clientName, $accessEnd, $gift, $devicesRevision);

header('Location: ../?activation=ok');
exit;