<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

function respond(int $code, array $payload): void
{
    http_response_code($code);
    echo json_encode($payload, JSON_UNESCAPED_SLASHES);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    respond(405, ['status' => 'error', 'message' => 'Method not allowed']);
}

$key = trim((string) ($_GET['key'] ?? ''));
if ($key === '' || !preg_match('/^[a-zA-Z0-9._-]{1,64}$/', $key)) {
    respond(400, ['status' => 'error', 'message' => 'Missing or invalid key parameter']);
}

$clientIp = $_SERVER['REMOTE_ADDR'] ?? '';
if (!filter_var($clientIp, FILTER_VALIDATE_IP)) {
    respond(400, ['status' => 'error', 'message' => 'Unable to determine client IP']);
}

$dataFile = __DIR__ . '/allowed_ips.txt';
if (!is_readable($dataFile)) {
    respond(503, ['status' => 'error', 'message' => 'License data not available']);
}

$today = new DateTimeImmutable('today');
$lines = file($dataFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($lines ?: [] as $line) {
    $line = trim($line);
    if ($line === '' || substr($line, 0, 1) === '#') {
        continue;
    }

    $parts = array_map('trim', explode('|', $line));
    if (count($parts) < 5) {
        continue;
    }

    [$licenseKey, $ip, $brand, $domain, $expiry] = array_slice($parts, 0, 5);
    if ($licenseKey !== $key || $ip !== $clientIp) {
        continue;
    }

    $expiryDate = DateTimeImmutable::createFromFormat('!Y-m-d', $expiry);
    if (!$expiryDate) {
        respond(500, ['status' => 'error', 'message' => 'Invalid license data']);
    }

    if ($expiryDate < $today) {
        respond(403, [
            'status' => 'expired',
            'brand_name' => $brand,
            'domain_name' => $domain,
            'expire_date' => $expiry,
        ]);
    }

    respond(200, [
        'status' => 'success',
        'brand_name' => $brand,
        'domain_name' => $domain,
        'expire_date' => $expiry,
    ]);
}

respond(403, ['status' => 'error', 'message' => 'License not found for this IP']);
