<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../../../config/config.php';

if (!isset($_SESSION['invoice_data']) || !isset($_SESSION['user_id'])) {
    header("Location: ../user/billing.php");
    exit();
}

$invoice = $_SESSION['invoice_data'];
$user_id = $_SESSION['user_id'];

// Fetch NOWPayments API Key from Database
$stmt = $pdo->query("SELECT key_value FROM payment_settings WHERE key_name = 'nowpayments_api_key'");
$np_api_key = $stmt->fetchColumn();

// Setup Order Payload to communicate securely to the NOWPayments API
$payment_url = "#";
$error = "";

$postData = [
    'price_amount' => $invoice['amount'],
    'price_currency' => 'usd', // Set default currency supported by NOWPayments
    'pay_currency' => 'usdttrc20', // Pre-selected coin (e.g., usdttrc20, btc, eth)
    'ipn_callback_url' => 'https://yourdomain.com/public/user/gateways/ipn-nowpayments.php',
    'order_id' => 'INV_' . $user_id . '_' . time(),
    'order_description' => 'Subscription: ' . $invoice['plan_name'],
    'success_url' => 'https://yourdomain.com/public/user/billing.php?status=success',
    'cancel_url' => 'https://yourdomain.com/public/user/billing.php?status=cancelled'
];

$ch = curl_init('https://api.nowpayments.io/v1/payment');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'x-api-key: ' . $np_api_key,
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    $responseData = json_decode($response, true);
    if (isset($responseData['pay_amount'])) {
        // Redirect the user to the crypto deposit page hosted by NOWPayments
        header("Location: " . $responseData['invoice_url']);
        exit();
    }
} else {
    $error = "Payment Node Transport Error. Please use alternate node.";
}
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <title>NowPayments Checkout Node</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-[#020617] text-white flex flex-col items-center justify-center min-h-screen">
    <div class="bg-slate-900 border border-slate-800 rounded-3xl p-8 max-w-md w-full text-center shadow-2xl">
        <h3 class="text-lg font-black tracking-wider uppercase text-amber-500 mb-2">🌐 Crypto Gateway Node</h3>
        <p class="text-xs text-slate-400 mb-6">Processing transaction. Please wait...</p>

        <?php if (!empty($error)): ?>
            <div class="bg-rose-500/10 border border-rose-500/30 text-rose-400 p-4 rounded-xl text-xs font-bold mb-4">
                <?= $error; ?>
            </div>
        <?php endif; ?>

        <a href="../user/billing.php" class="text-[9px] font-black tracking-widest uppercase text-slate-500 hover:text-white transition">🔙 Return to Billing Ledger</a>
    </div>
</body>
</html>