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

if(isset($_GET['amount'])){
    $ramt = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['amount']));
    $payTypeID = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['tyid']));
} else{
    $ramt = 0;
}
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 == 1021) {
    $payName = 'YaYa-APPpay';
} elseif ($payTypeID == 1010) {
    $payName = 'FAST-UPIpay';
} elseif ($payTypeID == 1012) {
    $payName = 'Super-ORpay';
} elseif ($payTypeID == 1013) {
    $payName = 'YaYa-ORpay';
} elseif ($payTypeID == 1014) {
    $payName = 'UPI x QR';
} elseif ($payTypeID == 1015) {
    $payName = 'SunPay';
} elseif ($payTypeID == 2123) {
    $payName = 'UPAY-USDT';
} elseif ($payTypeID == 2190) {
    $payName = 'UU-USDT';
} elseif ($payTypeID == 2191) {
    $payName = '7Day-PayTM';
} elseif ($payTypeID == 2192) {
    $payName = 'UPI-PayTM';
}

$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']));

$createdate = date("Y-m-d H:i:s");
$isDemo = $conn->query("SELECT 1 FROM demo WHERE balakedara = '$uid'")->num_rows > 0;
$sthiti = $isDemo ? '1' : '0';

$insertQuery = "
    INSERT INTO `thevani` (`balakedara`, `motta`, `dharavahi`, `mula`, `ullekha`, `duravani`, `ekikrtapavati`, `dinankavannuracisi`, `madari`, `pavatiaidi`, `sthiti`) 
    VALUES ('$uid', '$ramt', '$serial', '$payName', 'N/A', 'N/A', 'N/A', '$createdate', '1005', '2', '$sthiti')
";
$conn->query($insertQuery);

if ($isDemo) {
    $updateQuery = "
        UPDATE `shonu_kaichila`
        SET `motta` = `motta` + $ramt
        WHERE `balakedara` = '$uid'
    ";
    $conn->query($updateQuery);
    header('Location: https://g10clab.mojid360.online/#/main');
    exit;
}

$res = [
    'code' => 405,
    'message' => 'Illegal access!',
];

if (isset($_GET['tyid'], $_GET['amount'], $_GET['uid'], $_GET['sign'], $_GET['urlInfo'])) {
    $orderid = $serial;
    $amount = $ramt;
    $notify_url = "https://g10clab.mojid360.online/pay/callback.php";
    $redirect_url = "https://g10clab.mojid360.online/#/main";
    $merchantId = "100225396";
    $key = "9KGQE81AGNVJTRSFVNLIQJAKBVNFP7KP";

    $watchpayParams = [
        'version' => '1.0',
        'mch_id' => $merchantId,
        'notify_url' => $notify_url,
        'page_url' => $redirect_url,
        'mch_order_no' => $orderid,
        'pay_type' => '101',
        'trade_amount' => $amount,
        'order_date' => date('Y-m-d H:i:s'),
        'goods_name' => "Recharge",
        'mch_return_msg' => "Recharge",
        'sign_type' => 'MD5',
    ];

    function generateSign($params, $key) {
        ksort($params);
        $signString = '';
        foreach ($params as $k => $v) {
            if ($v !== '' && $k != 'sign' && $k != 'sign_type') {
                $signString .= "$k=$v&";
            }
        }
        $signString .= "key=$key";
        return md5($signString);
    }

    $watchpayParams['sign'] = generateSign($watchpayParams, $key);

    function post($url, $data) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            echo "Error: " . curl_error($curl);
        }
        curl_close($curl);
        return $response;
    }

    $response = post("https://api.watchglb.com/pay/web", $watchpayParams);
    $jsonResponse = json_decode($response, true);

    $status = $jsonResponse['respCode'] ?? '';
    $payUrl = $jsonResponse['payInfo'] ?? '';

    if ($status === 'SUCCESS' && !empty($payUrl)) {
        // Redirect user to the payment page
        header('Location: ' . $payUrl);
        exit;
    } else {
        echo "Payment request failed. Please try again later!";
        var_dump($jsonResponse);
    }
} else {
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(200);
    echo json_encode($res);
}
?>