<?php
// request_payment.php
// You will need your API Key from your payment provider's dashboard

// Database connection to fetch dynamic settings
$db = new PDO('sqlite:app_feed.db');
$settings_query = $db->query("SELECT setting_value FROM app_feed_settings WHERE setting_key = 'api_key'");
$api_key = $settings_query->fetchColumn();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = $_POST['amount'];
    $phone = $_POST['phone'];
    $order_id = $phone; // Using phone number as unique identifier

    $data = [
        "price_amount" => $amount,
        "price_currency" => "USD", // Or your preferred currency
        "pay_currency" => "BTC",   // The user pays in Bitcoin
        "order_id" => $order_id,
        "order_description" => "Account Funding for " . $phone
    ];

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

    $response = curl_exec($ch);
    $result = json_decode($response, true);
    curl_close($ch);

    if (isset($result['pay_address'])) {
        // Redirect the user to the payment link provided by the gateway
        header("Location: " . $result['invoice_url']);
        exit();
    } else {
        echo "Error creating payment: " . ($result['message'] ?? 'Unknown error');
    }
}
?>