<?php
declare(strict_types=1);

/*
 * Builds the existing Jeeto King Web Clip profile with the referral code in
 * its launch URL. Keep install.mobileconfig beside this file on the server.
 */

const REFERRAL_PREFIX = '777-';
const GAME_URL = 'https://games.jeetoking.com/';

function failRequest(int $statusCode, string $message): void
{
    http_response_code($statusCode);
    header('Content-Type: text/plain; charset=UTF-8');
    header('Cache-Control: no-store');
    echo $message;
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') {
    header('Allow: GET');
    failRequest(405, 'Method not allowed.');
}

$rawReferral = $_GET['ref'] ?? '';
if (is_array($rawReferral)) {
    failRequest(400, 'Invalid referral code.');
}

$rawReferral = trim((string) $rawReferral);
$referralCode = $rawReferral;

if (strncmp($referralCode, REFERRAL_PREFIX, strlen(REFERRAL_PREFIX)) === 0) {
    $referralCode = substr($referralCode, strlen(REFERRAL_PREFIX));
}

if ($referralCode !== '' && preg_match('/\A[A-Za-z0-9_-]{1,64}\z/D', $referralCode) !== 1) {
    failRequest(400, 'Invalid referral code.');
}

$templatePath = __DIR__ . DIRECTORY_SEPARATOR . 'install.mobileconfig';
$profile = @file_get_contents($templatePath);
if ($profile === false) {
    failRequest(500, 'Profile template is unavailable.');
}

$launchUrl = GAME_URL;
if ($referralCode !== '') {
    $launchUrl .= '?ref=' . rawurlencode(REFERRAL_PREFIX . $referralCode);
}

$escapedLaunchUrl = htmlspecialchars($launchUrl, ENT_QUOTES | ENT_XML1, 'UTF-8');
$replacementCount = 0;
$generatedProfile = preg_replace_callback(
    '~(<key>\s*URL\s*</key>\s*<string>)[^<]*(</string>)~i',
    static function (array $matches) use ($escapedLaunchUrl): string {
        return $matches[1] . $escapedLaunchUrl . $matches[2];
    },
    $profile,
    1,
    $replacementCount
);

if ($generatedProfile === null || $replacementCount !== 1) {
    failRequest(500, 'Profile template is invalid.');
}

header('Content-Type: application/x-apple-aspen-config');
header('Content-Disposition: attachment; filename="JeetoKing.mobileconfig"');
header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('X-Content-Type-Options: nosniff');
header('Content-Length: ' . strlen($generatedProfile));

echo $generatedProfile;
