<?php 
ob_start(); // Start output buffering
    header('Content-type: text/plain; charset=utf-8');
    @include ("../serive/samparka.php");
?>

<?php 

@ini_set('display_errors', 1);
@ini_set('display_startup_errors', 1);
@error_reporting(E_ALL);


if(isset($_GET['amount'])){
    $ramt = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['amount']));
} else{
    $ramt = 0;
}

// Format the amount to ensure two decimal places
$dot_pos = strpos($ramt, '.');
if ($dot_pos === false) {
    $ramt = $ramt . '.00';
} else {
    $after_dot = substr($ramt, $dot_pos + 1);
    $after_dot_length = strlen($after_dot);
    if ($after_dot_length > 2) {
        $after_dot = substr($after_dot, 0, 2);
        $ramt = substr($ramt, 0, $dot_pos + 1) . $after_dot;
    } elseif ($after_dot_length < 2) {
        $zeros_to_add = 2 - $after_dot_length;
        $ramt = $ramt . str_repeat('0', $zeros_to_add);
    }
}

$date = date("Ymd");
$time = time();
$serial = $date . $time . rand(100000, 999900);

$tyid = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['tyid']));
$uid = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['uid']));
$sign = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['sign']));
$urlInfo = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['urlInfo']));

// Check if `uid` exists in the `demo` table
$demoQuery = "SELECT 1 FROM demo WHERE balakedara = '$uid'";
$demoResult = $conn->query($demoQuery);

if ($demoResult->num_rows > 0) {
    // If uid exists in demo table, insert into `thevani` table and update `motta`
    $createdate = date("Y-m-d H:i:s");
    
    // Insert into `thevani`
    $insertQuery = "
        INSERT INTO `thevani` (`balakedara`, `motta`, `dharavahi`, `mula`, `ullekha`, `duravani`, `ekikrtapavati`, `dinankavannuracisi`, `madari`, `pavatiaidi`, `sthiti`) 
        VALUES ('$uid', '$ramt', '$serial', 'IndianPay', 'N/A', 'N/A', 'N/A', '$createdate', '1005', '2', '1')
    ";
    $conn->query($insertQuery);

    // Update `motta` field in `shonu_kaichila`
    $updateQuery = "
        UPDATE `shonu_kaichila`
        SET `motta` = `motta` + $ramt
        WHERE `balakedara` = '$uid'
    ";
    $conn->query($updateQuery);

    // Redirect to recharge history
    header('Location: https://bluewin.sbs/#/main');
    exit;
}

// If not found in `demo` table, proceed with the rest of the existing logic

$res = [
    'code' => 405,
    'message' => 'Illegal access!',
];
if (isset($_GET['tyid']) && isset($_GET['amount']) && isset($_GET['uid']) && isset($_GET['sign']) && isset($_GET['urlInfo'])) {
    $userId = $uid;
    $userPhoto = '1';

    $numquery = "SELECT mobile, codechorkamukala
        FROM shonu_subjects
        WHERE id = ".$userId;
    $numresult = $conn->query($numquery);
    $numarr = mysqli_fetch_array($numresult);

    $userName = '91'.$numarr['mobile'];
    $nickName = $numarr['codechorkamukala'];

    $creaquery = "SELECT createdate
        FROM shonu_subjects
        WHERE id = ".$userId;
    $crearesult = $conn->query($creaquery);
    $creaarr = mysqli_fetch_array($crearesult);

    $knbdstr = '{"userId":'.$userId.',"userPhoto":"'.$userPhoto.'","userName":'.$userName.',"nickName":"'.$nickName.'","createdate":"'.$creaarr['createdate'].'"}';
    $shonusign = strtoupper(hash('sha256', $knbdstr));

    $urlarr = explode (",", $urlInfo);
    $theirurl = $urlarr[0];
    $myurl = 'https://bluewin.sbs';

    if($myurl){

        $orderid = $serial;
        $amount = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['amount']));
        $name = 'TestName';
        $email = 'testemail@gmail.com';
        $mobile = $numarr['mobile'];
        $remark = 'remark';
        $type = 2;
        

        // API configuration
        $config = require 'config.php';
        $apiUrl = $config['api_url'];
        $secretKey = $config['secret_key'];
        $app_id = $config['app_id'];

        // Set up parameters
        $notify_url = "https://bluewin.sbs/pay/lgwebhook.php";

        if (!$ramt || !$serial) {
            die("Error: Amount or order ID not provided.");
        }
        
        
        
    
$mch_id = '202018312'; 
$api_key = 'Yzk0M2YwOTIzZWExNGVhMmE0MGEzZDYzMGI2NTBkM2Q='; 
$notify_url = "https://bluewin.sbs/pay/sunpay_notify.php";
$page_url = "https://bluewin.sbs/";
$pay_type = '102'; 


$goods_name = "Test Product";


if (!$amount || !$serial) {
    die("Error: Amount or order ID not provided.");
}


$order_date = date("Y-m-d H:i:s");
$order_date = date("Y-m-d H:i:s");


$data = [
    "version" => "1.0",
    "mch_id" => $mch_id,
    "notify_url" => $notify_url,
    "page_url" => $page_url,
    "mch_order_no" => $serial,
    "pay_type" => $pay_type,
    "trade_amount" => $amount,
    "order_date" => $order_date,
    "goods_name" => $goods_name,
];

// Filter out empty values and 'sign', then sort by keys
$sign_data = array_filter($data, function ($key) {
    return $key !== 'sign';
}, ARRAY_FILTER_USE_KEY);

ksort($sign_data); // Sort array by key

// Build the query string
$sign_str = urldecode(http_build_query($sign_data)); // Use urldecode if required by spec
$sign_str .= "&key=" . base64_decode($api_key);

// Create MD5 signature
$data['sign'] = md5($sign_str);
$data['sign_type'] = "MD5";

// SEND REQUEST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://pay.sunpayonline.xyz/pay/web");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/x-www-form-urlencoded"
]);

$response = curl_exec($ch);
curl_close($ch);

// PARSE RESPONSE
$responseData = json_decode($response, true);

// CHECK RESPONSE
                if ($responseData && $responseData['respCode'] === "SUCCESS" && $responseData['tradeResult'] == "1") {

                $amt = $amount;
                $srl = $serial;
                $source = 'IndianPay';
                $ref_num = $responseData['order_id'] ?? 0;
                $emailQ = mysqli_query($conn , "SELECT mobile FROM `shonu_subjects` WHERE `id` = '".$uid."'");
                $emailA = mysqli_fetch_array($emailQ);
                $email = $emailA['mobile'];
                $upi = 'IndianPayUPI';
                $createdate = date("Y-m-d H:i:s");

                // Insert payment record into `thevani`
                $deposit1 = mysqli_query($conn, "INSERT INTO `thevani`(`balakedara`, `motta`, `dharavahi`, `mula`, `ullekha`, `duravani`, `ekikrtapavati`, `dinankavannuracisi`, `madari`, `pavatiaidi`, `sthiti`) 
                VALUES('$uid', '$amount', '$srl', '$source','$ref_num', '$email', '$upi', '$createdate', '1005', '2', '0')");
                
                header('Location: ' . $responseData['payInfo']);
                exit;
            } else {
                // If there's an error, display an appropriate message
                echo "Error: Unable to process payment.";
                var_dump($response);
            }

        curl_close($ch);

    } else {
        $res['code'] = 10000;
        $res['success'] = 'false';
        $res['message'] = 'Sorry, The system is busy, please try again later!';

        header('Content-Type: text/html; charset=utf-8');
        http_response_code(200);
        echo json_encode($res);
    }
}
	else {
		header('Content-Type: application/json; charset=utf-8');
		http_response_code(200);
		echo json_encode($res);	
	}
ob_end_flush(); // Flush and send the output
	
?>
