<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-type: text/plain; charset=utf-8');

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

date_default_timezone_set('Asia/Kolkata');

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;
}

$payName = 'LG-Pay';

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

// =========================
// 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;
}

// =========================
// VALIDATE REQUIRED PARAMS
// =========================
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);

    if(!$numresult){
        die(mysqli_error($conn));
    }

    $numarr = mysqli_fetch_array($numresult);

    if(!$numarr){
        die("Invalid User");
    }

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

    // FIXED STRING
    $myurl = 'https://smm.yaarwin34.site';

    if($myurl){

        $orderid = $serial;

        $amount = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['amount']));

        $mobile = $numarr['mobile'];

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

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

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

        if (!$ramt || !$serial) {

            die("Error: Amount or order ID not provided.");

        }

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

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

            'remark' => 'web pay',

            'notify_url' => $notify_url,

            'money' => intval($amount * 100),

            'app_id' => $app_id,

            // KEEP INRUPI
            'trade_type' => 'INRUPI',

            'order_sn' => $serial

        ];

        // =========================
        // 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);

        // =========================
        // 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_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
        ]);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {

            die("CURL ERROR: " . curl_error($ch));

        }

        curl_close($ch);

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

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

            $srl = $serial;

            $source = 'LGPay';

            // FIXED
            $ref_num = $serial;

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

            $emailA = mysqli_fetch_array($emailQ);

            $email = $emailA['mobile'];

            $upi = 'LGPayUPI';

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

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

            if(!$deposit1){

                die(mysqli_error($conn));

            }

            // =========================
            // REDIRECT TO PAYMENT
            // =========================
            header('Location: ' . $responseData['data']['pay_url']);

            exit;

        } else {

            echo "Error: Unable to process payment.<br><br>";

            echo "<pre>";
            print_r($responseData);
            exit;

        }
    }

} else {

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

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

}
?>