<?php

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('code' => 405, 'msg' => 'Method Not Allowed'));
    exit;
}

require_once dirname(__DIR__) . '/core/db/db.php';

$raw = json_decode((string) file_get_contents('php://input'), true);
$input = is_array($raw) ? $raw : $_POST;
$key = trim((string) ($input['key'] ?? ''));
$timestamp = intval($input['timestamp'] ?? 0);
$nonce = trim((string) ($input['nonce'] ?? ''));
$signature = strtolower(trim((string) ($input['signature'] ?? '')));

if (!preg_match('/^[A-Za-z0-9._-]{8,128}$/', $key)
    || abs(time() - $timestamp) > 300
    || !preg_match('/^[a-f0-9]{32,64}$/', $nonce)
    || !preg_match('/^[a-f0-9]{64}$/', $signature)) {
    http_response_code(400);
    echo json_encode(array('code' => 400, 'msg' => 'Invalid request'));
    exit;
}

$canonical = $key . "\n" . $timestamp . "\n" . $nonce;
$expected = hash_hmac('sha256', $canonical, $key);
if (!hash_equals($expected, $signature)) {
    http_response_code(403);
    echo json_encode(array('code' => 403, 'msg' => 'Signature validation failed'));
    exit;
}

$nonceDir = dirname(__DIR__) . '/data/cache/license_reset';
if (!is_dir($nonceDir) && !mkdir($nonceDir, 0700, true) && !is_dir($nonceDir)) {
    http_response_code(500);
    echo json_encode(array('code' => 500, 'msg' => 'Replay cache unavailable'));
    exit;
}
$noncePath = $nonceDir . '/' . hash('sha256', $key . '|' . $nonce) . '.nonce';
$nonceHandle = @fopen($noncePath, 'x');
if (!$nonceHandle) {
    http_response_code(409);
    echo json_encode(array('code' => 409, 'msg' => 'Request already processed'));
    exit;
}
fwrite($nonceHandle, (string) time());
fclose($nonceHandle);
foreach (glob($nonceDir . '/*.nonce') ?: array() as $oldNonce) {
    if (@filemtime($oldNonce) < time() - 600) @unlink($oldNonce);
}

try {
    $db = \Core\Db\DB::getInstance();
    $table = $db->table('license');
    $current = $db->fetch("SELECT site_id FROM {$table} WHERE license_code=? LIMIT 1", array($key));
    if (!$current) {
        http_response_code(404);
        echo json_encode(array('code' => 404, 'msg' => 'License not found'));
        exit;
    }
    $db->delete('license', 'license_code = ?', array($key));
    $host = strtolower((string) ($_SERVER['HTTP_HOST'] ?? ''));
    $host = preg_replace('/:\d+$/', '', $host);
    $now = time();
    $db->insert('license', array(
        'license_code' => 'FREE-' . strtoupper(substr(hash('sha256', $host), 0, 8)),
        'license_domain' => $host,
        'license_level' => 1,
        'license_expire' => null,
        'site_id' => (string) $current['site_id'],
        'bind_count' => 1,
        'max_domains' => 1,
        'license_status' => 1,
        'create_time' => $now,
        'update_time' => $now,
    ));
    echo json_encode(array('code' => 200, 'msg' => 'OK'));
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(array('code' => 500, 'msg' => 'License reset failed'));
}
