<?php 
    /**
     * wepay.php - Integrated with OxaPay Merchant API (Invoice Creation)
     * Updated based on actual API response structure.
     */
    header('Content-Type: text/html; charset=utf-8');
    include ("../serive/samparka.php");

    // ---------------------------------------------------------
    // OxaPay Configuration (Merchant API)
    // ---------------------------------------------------------
    $merchant_api_key = "IPYKKV-I1LEGR-KYWSBT-TPL4OL"; 
    $apiUrl = "https://api.oxapay.com/v1/payment/invoice";

    if (isset($_GET['amount']) && isset($_GET['uid']) && isset($_GET['tyid'])) {
        $amount = floatval(mysqli_real_escape_string($conn, $_GET['amount']));
        $uid = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['uid']));
        $payTypeID = intval($_GET['tyid']);
        
        // 1. Map Payment Name
        $payName = 'OxaPay';
        if ($payTypeID == 1023) { $payName = 'SG-pay'; }
        elseif ($payTypeID == 1124) { $payName = 'TB-pay'; }
        elseif ($payTypeID == 1030) { $payName = 'LG-pay'; }
        elseif ($payTypeID == 1029) { $payName = 'FAST-UPIPay'; }
        elseif ($payTypeID == 2123) { $payName = 'UPAY-USDT'; }

        $serial = date("YmdHis") . rand(1000, 9999);
        $createdate = date("Y-m-d H:i:s");

        // 2. Handle Demo Users
        $demoQuery = "SELECT 1 FROM demo WHERE balakedara = '$uid'";
        $demoResult = $conn->query($demoQuery);

        if ($demoResult && $demoResult->num_rows > 0) {
            $conn->query("INSERT INTO `thevani` (`balakedara`, `motta`, `dharavahi`, `mula`, `ullekha`, `duravani`, `ekikrtapavati`, `dinankavannuracisi`, `madari`, `pavatiaidi`, `sthiti`) 
                          VALUES ('$uid', '$amount', '$serial', '$payName', 'DEMO_CREDIT', 'N/A', 'OxaPay', '$createdate', '1005', '2', '1')");

            $conn->query("UPDATE `shonu_kaichila` SET `motta` = `motta` + $amount WHERE `balakedara` = '$uid'");
            header('Location: https://moonclubs.in/#/main');
            exit;
        }

        // 3. Prepare Data for OxaPay Invoice
        $data = [
            "amount"               => $amount,
            "currency"             => "INR", 
            "lifetime"             => 30,
            "fee_paid_by_payer"    => 0,
            "under_paid_coverage"  => 2.5,
            "to_currency"          => "USDT",
            "auto_withdrawal"      => false,
            "mixed_payment"        => true,
            "return_url"           => "https://moonclubs.in/#/main",
            "callback_url"         => "https://moonclubs.in/pay/oxa_webhook.php",
            "order_id"             => $serial,
            "description"          => "Platform Deposit - UID: $uid",
            "sandbox"              => false
        ];

        $headers = [
            'Content-Type: application/json',
            'merchant_api_key: ' . $merchant_api_key
        ];

        $options = array(
            'http' => array(
                'header'  => implode("\r\n", $headers),
                'method'  => 'POST',
                'content' => json_encode($data),
                'ignore_errors' => true
            ),
        );

        $context  = stream_context_create($options);
        $response = file_get_contents($apiUrl, false, $context);
        
        if ($response === FALSE) {
            die('Connection error to OxaPay API');
        }

        $result = json_decode($response, true);

        // 4. Handle Response (Updated based on actual API response structure)
        if (isset($result['status']) && $result['status'] == 200 && isset($result['data']['payment_url'])) {
            $pay_url = $result['data']['payment_url'];
            $track_id = $result['data']['track_id'];

            // Save to DB (Status 0 = Pending)
            $conn->query("INSERT INTO `thevani` (`payid`, `balakedara`, `motta`, `dharavahi`, `mula`, `ullekha`, `duravani`, `ekikrtapavati`, `dinankavannuracisi`, `madari`, `pavatiaidi`, `sthiti`) 
                          VALUES ('2', '$uid', '$amount', '$serial', '$payName', '$track_id', 'N/A', 'OxaPay', '$createdate', '1005', '2', '0')");

            // Redirect user
            header('Location: ' . $pay_url);
            exit;
        } else {
            // Detailed error reporting
            header('Content-Type: application/json');
            echo $response;
        }
    } else {
        echo "Invalid request parameters.";
    }
?>
