<?php
define("FXH_PORTAL", true);

require_once __DIR__ . "/../config.php";
require_once __DIR__ . "/../config.nowpayments.php";
require_once __DIR__ . "/../middleware/user_auth.php";

/* =============================
   VALID PLANS
=============================*/

$plans = [
    "BRONZE"  => [ "price"=>20,  "keys"=>1,  "term"=>"30 DAYS" ],
    "SILVER"  => [ "price"=>30,  "keys"=>3,  "term"=>"30 DAYS" ],
    "GOLD"    => [ "price"=>90,  "keys"=>10, "term"=>"365 DAYS" ],
    "DIAMOND" => [ "price"=>999, "keys"=>10, "term"=>"LIFETIME" ],
];

$plan = strtoupper($_GET["plan"] ?? "");

if (!isset($plans[$plan])) {
    fxh_set_flash("Invalid plan selected.");
    header("Location: /portal/plans.php");
    exit;
}

$data  = $plans[$plan];
$price = $data["price"];
$keys  = $data["keys"];
$term  = $data["term"];

$user_id = intval($_SESSION["user_id"]);

/* =============================
   CREATE LOCAL ORDER
=============================*/

$ins = $conn->prepare("
    INSERT INTO fxh_orders
        (user_id, plan, amount, licenses, term, payment_status)
    VALUES
        (?, ?, ?, ?, ?, 'PENDING')
");

$ins->bind_param(
    "isdis",
    $user_id,
    $plan,
    $price,
    $keys,
    $term
);

$ins->execute();

$order_id = $conn->insert_id;

/* =============================
   NOWPAYMENTS REQUEST
=============================*/

$api_url = NOWPAYMENTS_SANDBOX
    ? "https://api-sandbox.nowpayments.io/v1/invoice"
    : "https://api.nowpayments.io/v1/invoice";

$payload = [
    "price_amount"       => $price,
    "price_currency"     => "USD",
    "order_id"           => "FXH-ORDER-" . $order_id,
    "order_description" => "FX-HUNTER {$plan} PLAN",
    "success_url"        => "https://api.fxhunterai.com/portal/payment_success.php?order={$order_id}",
    "cancel_url"         => "https://api.fxhunterai.com/portal/plans.php",
    "ipn_callback_url"  => "https://api.fxhunterai.com/portal/api/nowpayments_ipn.php"
];

$ch = curl_init($api_url);

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "x-api-key: " . NOWPAYMENTS_API_KEY,
        "Content-Type: application/json"
    ],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload)
]);

$response = curl_exec($ch);

if(!$response){
    die("NOWPAYMENTS CURL ERROR: " . curl_error($ch));
}

curl_close($ch);

$res = json_decode($response, true);

if (!isset($res["invoice_url"])) {
    echo "NOWPAYMENTS ERROR:";
    print_r($res);
    exit;
}

/* =============================
   SAVE NOWPAYMENTS INVOICE ID
=============================*/

$upd = $conn->prepare("
    UPDATE fxh_orders
    SET now_invoice_id = ?
    WHERE id = ?
");

$upd->bind_param(
    "si",
    $res["id"],
    $order_id
);

$upd->execute();

/* =============================
   REDIRECT USER TO PAYMENT
=============================*/

header("Location: " . $res["invoice_url"]);
exit;
