<?php
error_reporting(0);
include "../pages/dbFunctions.php";
include "../pages/dbInfo.php";

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

$servername = DB_HOST;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $byteTransactionId = $_POST['byte_order_status'];
    // continue processing the POST request
} else {
    
   
    // Send a 403 Forbidden HTTP status code
    header('HTTP/1.1 403 Forbidden');
    exit('Forbidden');
    
}





$sqlSelectOrderscxr = "SELECT * FROM orders WHERE byteTransactionId=?";
$stmtSelectOrderscxr = $conn->prepare($sqlSelectOrderscxr);
$stmtSelectOrderscxr->bind_param("s", $byteTransactionId);
$stmtSelectOrderscxr->execute();
$resultSelectOrders = $stmtSelectOrderscxr->get_result();
$cxrrrowOrders = $resultSelectOrders->fetch_assoc();
$stmtSelectOrderscxr->close();

if (!$cxrrrowOrders) {
    die("Byter error");
}


$order_id = $cxrrrowOrders['order_id'];
$bytehackamount=$cxrrrowOrders['amount'];





// Check if the order has already been processed
$sqlCheckStatus = "SELECT status FROM orders WHERE order_id=?";
$stmtCheckStatus = $conn->prepare($sqlCheckStatus);
$stmtCheckStatus->bind_param("s", $order_id);
$stmtCheckStatus->execute();
$resultCheckStatus = $stmtCheckStatus->get_result();
if ($resultCheckStatus->num_rows > 0) {
    $rowCheckStatus = $resultCheckStatus->fetch_assoc();
    if ($rowCheckStatus['status'] === 'SUCCESS') {
        echo 'success';
        $stmtCheckStatus->close();
        $conn->close();
        exit;
    }
}
$stmtCheckStatus->close();

$sqlDelete = "DELETE FROM reports WHERE status='' AND order_id=?";
$stmtDelete = $conn->prepare($sqlDelete);
$stmtDelete->bind_param("s", $order_id);
$stmtDelete->execute();
$stmtDelete->close();

$sqlSelectOrders = "SELECT * FROM orders WHERE order_id=?";
$stmtSelectOrders = $conn->prepare($sqlSelectOrders);
$stmtSelectOrders->bind_param("s", $order_id);
$stmtSelectOrders->execute();
$resultSelectOrders = $stmtSelectOrders->get_result();
$rowOrders = $resultSelectOrders->fetch_assoc();
$stmtSelectOrders->close();

if (!$rowOrders) {
    die("Order not found");
}

$user_token = $rowOrders['user_token'];
$orderamount = $rowOrders['amount'];
$gateway_txn = $rowOrders['gateway_txn'];
$cxrremark1 = $rowOrders['remark1'];

$slq_pmode = "SELECT * FROM users where user_token='$user_token'";
        $res_pmode = getXbyY($slq_pmode);
        
        if($res_pmode[0]["pg_mode"] == 2){
            $slq_admingetdata = "SELECT * FROM users where id=157 AND role = 'Admin'";
$adminarraydata =  getXbyY($slq_admingetdata);
$usermodetoken = $adminarraydata[0]["user_token"];
$rmode = 2;
        }else{
            $rmode = 1;
            $usermodetoken = $user_token;
        }

$sqlSelectUser = "SELECT * FROM users WHERE user_token=?";
$stmtSelectUser = $conn->prepare($sqlSelectUser);
$stmtSelectUser->bind_param("s", $user_token);
$stmtSelectUser->execute();
$resultSelectUser = $stmtSelectUser->get_result();
$rowUser = $resultSelectUser->fetch_assoc();
$stmtSelectUser->close();

$callback_url = $rowUser['callback_url'];
$megabyteuserid=$rowUser['id'];

$txn_data = file_get_contents('https://pay.codexhost.in/phnpe/user_txn.php?no=' . $usermodetoken . ''); 
$txn_data = substr($txn_data, 4);
// echo $txn_data;
// exit;
$obj = json_decode($txn_data);
$data = $obj->data;
$jsonData = json_decode($txn_data, true);
$data = $jsonData["data"];
$results = $data["results"];

foreach ($results as $result) {
    
    if ($result['merchantTransactionId']==$byteTransactionId){
    
    $cxrmerchantTransactionId=$result["merchantTransactionId"];
    $customerDetails = $result["customerDetails"];
    $user_name = $customerDetails["userName"];
    $paymentApp = $result["paymentApp"];
    $paymentApp = $paymentApp["paymentApp"];
    $logo = $paymentApp["logo"];

    $amount = $result["amount"];
    $amount = $amount / 100;
    $transactionId = $result["transactionId"]; //== utr number
    $paymentState = $result["payResponseCode"]; //success or fail
    $transactionDate = $result["transactionDate"];
    $transactionNote = $result["transactionNote"];
    $transactionDate = date('m/d/Y', $transactionDate);
    $Status = $result["Status"];
    $UTR = $result["utr"];
    $vpa = $result["vpa"] ?? 'test@paytm'; // Set default value for $vpa
    

   // Updated SQL Insert Statement to include UTR column
   $sqlInsertReport = "INSERT INTO reports (transactionId, status, order_id, vpa, user_name, paymentApp, amount, user_token, transactionNote, merchantTransactionId, user_id, user_mode, UTR) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
   $stmtInsertReport = $conn->prepare($sqlInsertReport);

   // Bind the $UTR variable along with other parameters
   // Assuming all variables are strings except $amount which is a float.
   $stmtInsertReport->bind_param("ssssssdssssss", $transactionId, $paymentState, $order_id, $vpa, $user_name, $paymentApp, $amount, $user_token, $transactionNote, $cxrmerchantTransactionId, $megabyteuserid,$rmode, $UTR);

if ($stmtInsertReport->execute() === TRUE) {
$stmtInsertReport->close();
}


}
}

$sqlSelectReports = "SELECT * FROM reports WHERE order_id=?";
$stmtSelectReports = $conn->prepare($sqlSelectReports);
$stmtSelectReports->bind_param("s", $order_id);
$stmtSelectReports->execute();
$resultSelectReports = $stmtSelectReports->get_result();
$rowReports = $resultSelectReports->fetch_assoc();
$stmtSelectReports->close();

$db_status = $rowReports['status'];
$db_user_token = $rowReports['user_token'];
$db_transactionId = $rowReports['transactionId'];  //utr


if ($db_status == 'SUCCESS') {
    

// Data to be sent
$postData = array(
    'status' => 'SUCCESS',
    'order_id' => $order_id,
    'message' => 'Transaction Successfully',
    'result' => array(
            "txnStatus" => "COMPLETED",
            "resultInfo" => "Transaction Success",
            "orderId" => $order_id,
            'amount' => $amount,
            'date' => $rowOrders['create_date'],
            'utr' => $UTR,
            'customer_mobile' => $rowOrders['customer_mobile'],
            'remark1' => $cxrremark1,
            'remark2' => $rowOrders["remark2"]
        )
);

// URL to which the request is sent
$url = $callback_url;

// Initialize cURL
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));

// Execute the POST request
curl_exec($ch);

// Close cURL session
curl_close($ch);


    $sql = "UPDATE orders SET status='SUCCESS' WHERE order_id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $order_id);
    $stmt->execute();
    $stmt->close();

    $sql = "UPDATE reports SET status='SUCCESS' WHERE order_id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $order_id);
    $stmt->execute();
    $stmt->close();
    
    if($res_pmode[0]["pg_mode"] == 2){
    if($db_status =='SUCCESS' && $amount == $orderamount){
    $getuserdata = $conn->query("SELECT wallet FROM `users` WHERE `id` = '$megabyteuserid'")->fetch_assoc();
    $getchargedata = $conn->query("SELECT * FROM `charge` WHERE `status` = '1' ORDER BY id DESC LIMIT 1")->fetch_assoc();
    $getplatformcharge = ($getchargedata["platform_fee"] / 100) * $amount;
    $getgstcharge = ($getchargedata["gst_charge"] / 100) * $amount;
    $getadditionalcharge = ($getchargedata["additional_fees"] / 100) * $amount;
    $updatewalletbal = $getuserdata["wallet"]+$amount-$getplatformcharge-$getgstcharge-$getadditionalcharge;
    $conn->query("UPDATE `users` SET `wallet`='$updatewalletbal' WHERE `id` = '$megabyteuserid'");
    }
}

    $sql = "UPDATE orders SET utr=? WHERE order_id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $UTR, $order_id);
    $stmt->execute();
    $stmt->close();
    echo 'success';
} else if ($db_status == 'FAILURE' || $db_status == 'FAILED' || $db_status == 'UPI_BACKBONE_ERROR') {
     $sql = "UPDATE orders SET status='FAILURE' WHERE order_id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $order_id);
    $stmt->execute();
    $stmt->close();

    $sql = "UPDATE reports SET status='FAILURE' WHERE order_id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $order_id);
    $stmt->execute();
    $stmt->close();
    echo 'FAILURE';
}else{
    echo 'PENDING';
}





$conn->close();
?>
