<?php 
    /**
     * wepay.php - Integrated with CodexVertex UPI Gateway
     * Replaced OxaPay with CodexVertex for direct UPI payments.
     */
    header('Content-Type: text/html; charset=utf-8');
    include ("../serive/samparka.php");

    // ---------------------------------------------------------
    // CodexVertex Configuration
    // ---------------------------------------------------------
    $merchant_api_key = "cv_bde0bbe6ba0902eb"; // Your Gateway API Key
    $gateway_url = "https://payment.winto.in/backend/create_order.php";
    $checkout_url = "https://payment.winto.in/index.php";

    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 = 'UPI-Auto';
        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', 'UPI', '$createdate', '1005', '2', '1')");

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

        // 3. Create Order in CodexVertex Gateway
        $data = [
            "amount" => $amount,
            "user_id" => $uid, // Sending UID to gateway for tracking
            "api_key" => $merchant_api_key,
            "return_url" => "https://winto.in/#/main"
        ];

        /* Using cURL for more reliability */
        $ch = curl_init($gateway_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'X-API-KEY: ' . $merchant_api_key
        ]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($response === FALSE) {
            die('Connection error to CodexVertex API');
        }

        $result = json_decode($response, true);

        // 4. Handle Response
        if ($httpCode == 200 && isset($result['status']) && $result['status'] == 'success') {
            $order_id = $result['order_id'];

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

            // Redirect user to Checkout Page
            header('Location: ' . $checkout_url . '?order_id=' . $order_id);
            exit;
        } else {
            echo "Gateway Error: " . ($result['message'] ?? 'Unknown Error');
            echo "<br>Response: " . $response;
        }
    } else {
        echo "Invalid request parameters.";
    }
?>
