<?php

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

header('Content-Type: text/html; charset=utf-8');

include("../serive/samparka.php");

date_default_timezone_set('Asia/Kolkata');

// =========================
// REQUIRED PARAMS CHECK
// =========================
if (
    !isset($_GET['amount']) ||
    !isset($_GET['tyid']) ||
    !isset($_GET['uid']) ||
    !isset($_GET['sign']) ||
    !isset($_GET['urlInfo'])
) {

    header('Content-Type: application/json; charset=utf-8');

    echo json_encode([
        'code' => 405,
        'message' => 'Illegal access!'
    ]);

    exit;
}

// =========================
// GET VALUES
// =========================
$ramt = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['amount']));
$payTypeID = 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']));

$payName = 'LG-Pay-USDT';

// normalize amount
$ramt = number_format((float)$ramt, 2, '.', '');

$date = date("Ymd");
$time = time();

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

// =========================
// DEMO USER CHECK
// =========================
$demoQuery = "SELECT 1 FROM demo WHERE balakedara = '$uid'";
$demoResult = $conn->query($demoQuery);

if ($demoResult && $demoResult->num_rows > 0) {

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

    $emailQ = mysqli_query($conn, "
        SELECT mobile
        FROM shonu_subjects
        WHERE id = '$uid'
    ");

    $emailA = mysqli_fetch_array($emailQ);

    $userm = $emailA['mobile'];

    mysqli_query($conn, "
        INSERT INTO thevani
        (
            payid,
            balakedara,
            motta,
            dharavahi,
            mula,
            ullekha,
            duravani,
            ekikrtapavati,
            dinankavannuracisi,
            madari,
            pavatiaidi,
            sthiti
        )
        VALUES
        (
            '2',
            '$uid',
            '$ramt',
            '$serial',
            '$payName',
            'N/A',
            '$userm',
            'N/A',
            '$createdate',
            '1005',
            '2',
            '1'
        )
    ");

    mysqli_query($conn, "
        UPDATE shonu_kaichila
        SET motta = motta + $ramt
        WHERE balakedara = '$uid'
    ");

    header('Location: https://smm.yaarwin34.site/#/main');
    exit;
}

// =========================
// USER DATA
// =========================
$userId = $uid;

$numquery = "
    SELECT mobile, codechorkamukala
    FROM shonu_subjects
    WHERE id = '$userId'
";

$numresult = $conn->query($numquery);

if (!$numresult || mysqli_num_rows($numresult) == 0) {

    die("Invalid User");
}

$numarr = mysqli_fetch_array($numresult);

// =========================
// CONFIG
// =========================
$config = require 'lgpayconfig.php';

$apiUrl = $config['api_url'];
$secretKey = $config['secret_key'];
$app_id = $config['app_id'];

$usdtRate = isset($config['usdt_rate'])
    ? floatval($config['usdt_rate'])
    : 92.0;

$gatewayScale = isset($config['gateway_scale'])
    ? intval($config['gateway_scale'])
    : 100;

// =========================
// WEBHOOK
// =========================
$notify_url = "https://smm.yaarwin34.site/larapay/lgpaywebhook.php";

// =========================
// AMOUNT CALCULATION
// =========================
$rawUSDT = floatval($ramt);

// game/history amount
$displayAmount = number_format(
    $rawUSDT * $usdtRate,
    2,
    '.',
    ''
);

// gateway amount
$sendAmountFormatted = intval(
    $displayAmount * $gatewayScale
);

// =========================
// REQUEST PARAMS
// =========================
$params = [

    'ip' => $_SERVER['HTTP_X_FORWARDED_FOR']
        ?? $_SERVER['REMOTE_ADDR']
        ?? '0.0.0.0',

    'remark' => 'USDT pay',

    'notify_url' => $notify_url,

    'money' => $sendAmountFormatted,

    'app_id' => $app_id,

    'trade_type' => 'usdt',

    'currency' => 'INR',

    'order_sn' => $serial,

    'return_url' => 'https://smm.yaarwin34.site'

];

// =========================
// SIGNATURE
// =========================
ksort($params);

$signatureString = '';

foreach ($params as $key => $value) {

    $signatureString .= $key . "=" . $value . "&";
}

$signatureString .= "key=" . $secretKey;

$signature = strtoupper(md5($signatureString));

$params['sign'] = $signature;

$postData = http_build_query($params);

// =========================
// DEBUG LOG
// =========================
$debugLog =
    date('Y-m-d H:i:s')
    . " | order_sn={$serial}"
    . " | rawUSDT={$rawUSDT}"
    . " | displayAmount={$displayAmount}"
    . " | sendAmount={$sendAmountFormatted}"
    . " | post=" . $postData . "\n";

file_put_contents(
    '/tmp/lgpay_debug.log',
    $debugLog,
    FILE_APPEND
);

// =========================
// CURL REQUEST
// =========================
$ch = curl_init($apiUrl);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_TIMEOUT, 30);

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);

curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/x-www-form-urlencoded'
]);

$response = curl_exec($ch);

// =========================
// CURL ERROR
// =========================
if (curl_errno($ch)) {

    $curlError = curl_error($ch);

    curl_close($ch);

    die("CURL ERROR: " . $curlError);
}

curl_close($ch);

// raw backup
$responseRaw = $response;

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

// invalid response
if (!$responseData) {

    die("Invalid gateway response");
}

// =========================
// SUCCESS
// =========================
if (
    isset($responseData['status']) &&
    $responseData['status'] == 1 &&
    isset($responseData['data']['pay_url'])
) {

    $ref_num = $responseData['data']['order_id']
        ?? 'N/A';

    $mobile = $numarr['mobile'];

    $upi = 'LGPayUSDT';

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

    // =========================
    // INSERT PENDING
    // =========================
    mysqli_query($conn, "
        INSERT INTO thevani
        (
            payid,
            balakedara,
            motta,
            dharavahi,
            mula,
            ullekha,
            duravani,
            ekikrtapavati,
            dinankavannuracisi,
            madari,
            pavatiaidi,
            sthiti
        )
        VALUES
        (
            '2',
            '$uid',
            '$displayAmount',
            '$serial',
            '$payName',
            '$ref_num',
            '$mobile',
            '$upi',
            '$createdate',
            '1005',
            '2',
            '0'
        )
    ");

    // redirect payment
    header('Location: ' . $responseData['data']['pay_url']);

    exit;
}

// =========================
// NO CHANNEL UI
// =========================
if (
    isset($responseData['msg']) &&
    strpos(
        strtolower($responseData['msg']),
        'no available payment channel account'
    ) !== false
) {

    $returnUrl = "https://smm.yaarwin34.site/#/wallet/Recharge";

?>
<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Deposit Unavailable</title>

<style>

body{
    margin:0;
    padding:0;
    background:#111;
    font-family:Arial,sans-serif;
    display:flex;
    justify-content:center;
    align-items:center;
    height:100vh;
}

.box{
    width:90%;
    max-width:380px;
    background:#1c1c1c;
    border-radius:18px;
    padding:30px 20px;
    text-align:center;
    border:1px solid rgba(255,0,0,0.3);
    box-shadow:0 0 25px rgba(255,0,0,0.25);
}

.icon{
    width:85px;
    height:85px;
    background:#ff2d2d;
    border-radius:50%;
    margin:auto;
    display:flex;
    align-items:center;
    justify-content:center;
    color:#fff;
    font-size:42px;
    font-weight:bold;
}

.title{
    margin-top:20px;
    color:#fff;
    font-size:24px;
    font-weight:bold;
}

.desc{
    margin-top:12px;
    color:#cfcfcf;
    line-height:24px;
    font-size:15px;
}

.count{
    margin-top:22px;
    font-size:34px;
    color:#ff3d3d;
    font-weight:bold;
}

.small{
    margin-top:10px;
    color:#9e9e9e;
    font-size:13px;
}

.loader{
    width:100%;
    height:6px;
    background:#2c2c2c;
    border-radius:20px;
    margin-top:25px;
    overflow:hidden;
}

.loader-bar{
    height:100%;
    width:100%;
    background:#ff2d2d;
    animation:load 5s linear forwards;
}

@keyframes load{
    from{
        width:100%;
    }
    to{
        width:0%;
    }
}

</style>

</head>

<body>

<div class="box">

    <div class="icon">!</div>

    <div class="title">
        Deposit Method Unavailable
    </div>

    <div class="desc">
        Deposit gateway is currently unavailable.<br>
        Please try again after some time.
    </div>

    <div class="count" id="count">
        5
    </div>

    <div class="small">
        Redirecting automatically...
    </div>

    <div class="loader">
        <div class="loader-bar"></div>
    </div>

</div>

<script>

let sec = 5;

let timer = setInterval(function(){

    sec--;

    document.getElementById("count").innerText = sec;

    if(sec <= 0){

        clearInterval(timer);

        window.location.href =
            "<?php echo $returnUrl; ?>";

    }

},1000);

</script>

</body>
</html>
<?php

exit;

}

// =========================
// OTHER ERROR
// =========================
echo "Error: Unable to process USDT payment.<br><br>";

echo "<pre>";

print_r($responseData);

echo "</pre>";

?>