<?php
require_once __DIR__.'/../config.database.php';
require_once __DIR__.'/../config.nowpayments.php';

$raw = file_get_contents("php://input");

$hmac = hash_hmac("sha512", $raw, NOWPAYMENTS_IPN_SECRET);

if($hmac !== ($_SERVER["HTTP_X_NOWPAYMENTS_SIG"] ?? "")){
    http_response_code(403);
    exit("INVALID SIGNATURE");
}

$data = json_decode($raw,true);

if($data['payment_status'] !== "finished") exit("IGNORED");

$email = $data['buyer_email'] ?? null;
$desc  = $data['order_description'];   // FXH-BRONZE PLAN

if(!$email) exit("NO EMAIL");

if(!preg_match("/FX-HUNTER\s+(.*)\s+PLAN/i",$desc,$m)) exit("BAD DESC");

$plan = strtoupper($m[1]);

$keyLimits = [
    "BRONZE"=>1,
    "SILVER"=>3,
    "GOLD"=>10,
    "DIAMOND"=>10
];

$exp = match($plan){
    "BRONZE","SILVER" => date("Y-m-d", strtotime("+1 month")),
    "GOLD" => date("Y-m-d", strtotime("+1 year")),
    default => null
};

$conn = new mysqli(FXH_DB_HOST, FXH_DB_USER, FXH_DB_PASS, FXH_DB_NAME);

for($i=0;$i<$keyLimits[$plan];$i++){

    $lic = random_int(100000000000,999999999999);

    $st = $conn->prepare("
        INSERT INTO fxh_licenses
        (license_key,plan,user_email,expires_at,active,created_at)
        VALUES (?,?,?,?,0,NOW())
    ");

    $st->bind_param("ssss",$lic,$plan,$email,$exp);
    $st->execute();
}
