<?php
declare(strict_types=1);

if (defined('INSTALL_BOOTSTRAP_LOADED')) {
    return;
}
define('INSTALL_BOOTSTRAP_LOADED', true);

$appConfigFile = __DIR__ . '/app_config.php';
if (!is_file($appConfigFile)) {
    return;
}

$appConfig = require $appConfigFile;
if (!is_array($appConfig) || empty($appConfig['installed'])) {
    return;
}

$license = is_array($appConfig['license'] ?? null) ? $appConfig['license'] : [];
$licenseKey = trim((string)($license['license_key'] ?? ''));
$productSlug = trim((string)($license['product_slug'] ?? ''));
$installId = trim((string)($license['install_id'] ?? ''));
$apiUrl = trim((string)($license['api_url'] ?? 'https://sitepro.net.ua/license-center/api/license-hook.php'));

if ($licenseKey === '' || $productSlug === '' || $installId === '') {
    http_response_code(403);
    exit('Ліцензія не налаштована.');
}

$stateFile = dirname(__DIR__) . '/backups/license_state.json';
$state = [];
if (is_file($stateFile)) {
    $rawState = file_get_contents($stateFile);
    $decodedState = json_decode((string)$rawState, true);
    if (is_array($decodedState)) {
        $state = $decodedState;
    }
}

$lastCheckTs = isset($state['checked_at']) ? (int)strtotime((string)$state['checked_at']) : 0;
$lastStatus = (string)($state['license_status'] ?? '');

if ($lastCheckTs > 0 && (time() - $lastCheckTs) < 43200 && in_array($lastStatus, ['active', 'grace'], true)) {
    return;
}

$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (string)($_SERVER['SERVER_PORT'] ?? '') === '443';
$scheme = $https ? 'https' : 'http';
$host = (string)($_SERVER['HTTP_HOST'] ?? 'localhost');
$domain = preg_replace('~:\d+$~', '', $host) ?: $host;
$baseUrl = $scheme . '://' . $host;
$fingerprint = hash('sha256', $domain . '|' . PHP_VERSION . '|' . __DIR__ . '|' . $installId);

$payload = [
    'action' => 'heartbeat',
    'product_slug' => $productSlug,
    'license_key' => $licenseKey,
    'domain' => $domain,
    'base_url' => $baseUrl,
    'fingerprint' => $fingerprint,
    'install_id' => $installId,
    'php' => PHP_VERSION,
    'cms_version' => '5.0',
];

$ch = curl_init($apiUrl);
if ($ch === false) {
    return;
}

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Accept: application/json'],
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 20,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
]);
$response = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

if ($response === false || $response === '' || $httpCode < 200 || $httpCode >= 300) {
    return;
}

$data = json_decode($response, true);
if (!is_array($data)) {
    return;
}

$state = [
    'checked_at' => date('c'),
    'ok' => !empty($data['ok']),
    'license_valid' => !empty($data['license_valid']),
    'license_status' => (string)($data['license_status'] ?? ''),
    'message' => (string)($data['message'] ?? ''),
    'http_code' => $httpCode,
    'curl_error' => $curlError,
];

@file_put_contents($stateFile, json_encode($state, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));

if (empty($data['ok']) || empty($data['license_valid'])) {
    http_response_code(403);
    exit('Ліцензію не підтверджено. ' . (string)($data['message'] ?? ''));
}
