<?php
// Wallet "Add Funds" order creation - mirrors auth/lib/pay.php (subscription
// purchase) exactly, since both are the merchant paying the PLATFORM, not
// receiving a payment from their own customer. Uses the same platform
// collection token from config.php ($token).
//
// Plain curl to THIS SAME domain's own /api/create-order - same pattern
// the original script uses everywhere. No hardcoded domain.

session_start();
include __DIR__ . "/../config.php";  // $conn (main app DB config, NOT lib/config.php)
include "config.php";                 // $token (platform collection token)

if (!isset($_SESSION['username'])) {
    header('Location: https://' . $_SERVER["SERVER_NAME"] . '/index');
    exit;
}

$safeMobile = mysqli_real_escape_string($conn, $_SESSION['username']);
$userdata = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE mobile = '$safeMobile' LIMIT 1"));

if (!$userdata) {
    header('Location: https://' . $_SERVER["SERVER_NAME"] . '/index');
    exit;
}

if (isset($_POST['addfund'])) {

    $amount = $_POST['amount'];

    if (!is_numeric($amount) || (float)$amount <= 0) {
        header('Location: https://' . $_SERVER["SERVER_NAME"] . '/auth/wallet?topup_failed=1&reason=invalid_amount');
        exit;
    }
    $amount = (float)$amount;

    // Never trust the client-side min/max check alone - re-check here
    // against whatever Admin has configured right now.
    $limitsResult = $conn->query("SELECT wallet_topup_min, wallet_topup_max FROM site_settings LIMIT 1");
    $limitsRow = $limitsResult ? $limitsResult->fetch_assoc() : null;
    $topupMin = (float)($limitsRow['wallet_topup_min'] ?? 10);
    $topupMax = (float)($limitsRow['wallet_topup_max'] ?? 50000);

    if ($amount < $topupMin || $amount > $topupMax) {
        header('Location: https://' . $_SERVER["SERVER_NAME"] . '/auth/wallet?topup_failed=1&reason=out_of_range');
        exit;
    }

    $order_id = 'WFUND' . time() . rand(11111, 99999);
    setcookie('wallet_topup_order_id_cookie', $order_id, time() + 3600, '/');

    $currentDomain = $_SERVER["SERVER_NAME"];
    $callbackurl = "https://" . $currentDomain . "/auth/lib/wallet_callback";

    $data = array(
        'customer_mobile' => '1234567890',
        'user_token' => $token, // platform's own collection token, same as subscription purchases
        'amount' => $amount,
        'order_id' => $order_id,
        'redirect_url' => $callbackurl,
        // Marker checked in payment/create_order.php, includes/fampay_order_resolver.php
        // and auth/update_order_status.php to skip commission deduction /
        // quota gating on this order (it's the merchant paying the
        // platform, not the other way round).
        'remark1' => 'WALLET_TOPUP',
        'remark2' => (string)($userdata['id'] ?? ''),
        'origin_domain' => $currentDomain,
    );

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://' . $currentDomain . '/api/create-order',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => http_build_query($data),
    ));
    $response = curl_exec($curl);
    $curlErr = curl_error($curl);
    curl_close($curl);

    $jsonResponse = json_decode($response, true);

    if (!empty($jsonResponse['status']) && isset($jsonResponse['result']['payment_url'])) {
        header('Location: ' . $jsonResponse['result']['payment_url']);
        exit;
    } else {
        $apiMsg = $jsonResponse['message'] ?? ($curlErr ?: ('Unexpected response: ' . substr(strip_tags((string)$response), 0, 200)));
        header('Location: https://' . $currentDomain . '/auth/wallet?topup_failed=1&reason=create_order&api_msg=' . urlencode($apiMsg));
        exit;
    }
}
