<?php
error_reporting(1);

// Define constants
define('ROOT_DIR', realpath(dirname(__FILE__)) . '/../');

// Include required files
include ROOT_DIR . 'pages/dbFunctions.php';
include ROOT_DIR . 'auth/config.php';
include ROOT_DIR . 'pages/dbInfo.php';

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

// ---------- RESPONSE FUNCTION ----------
function sendResponse($status, $message, $additionalData = []) {
    echo json_encode(array_merge([
        'status' => $status,
        'message' => $message
    ], $additionalData));
    exit;
}

// ---------- INPUT VALIDATION ----------
function validateInputs($order_id, $user_token) {
    if (empty($order_id)) sendResponse('FAILURE', 'Order ID missing');
    if (empty($user_token)) sendResponse('FAILURE', 'User Token missing');
}

// ---------- FETCH ORDER ----------
function getOrderData($conn, $order_id, $user_token) {
    $sql = "SELECT description AS txnId, amount, customer_mobile AS mobile, user_id
            FROM orders WHERE order_id=? AND user_token=? LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $order_id, $user_token);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$data) sendResponse("FAILURE", "Order not found");

    return $data;
}

// ---------- FETCH GOOGLE PAY TOKEN ----------
function getGooglePayData($conn, $user_token, $mobile) {
    $sql = "SELECT phoneNumber, AT, FREQ_RAW, COOKIE 
            FROM googlepay_tokens 
            WHERE user_token=? AND phoneNumber=? LIMIT 1";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $user_token, $mobile);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    return $data;
}

// ---------- COOKIE VALUE ----------
function cookieVal($cookie, $name){
    foreach(explode(";", $cookie) as $p){
        $kv = explode("=", trim($p), 2);
        if(count($kv)==2 && $kv[0]===$name) return $kv[1];
    }
    return null;
}

// ---------- SAPISIDHASH ----------
function sapiHash($cookie){
    $sid = cookieVal($cookie,"SAPISID") ?: cookieVal($cookie,"__Secure-3PAPISID");
    if(!$sid) return null;
    $ts = time();
    return "SAPISIDHASH ".$ts."_".sha1($ts." ".$sid." https://pay.google.com");
}

// ---------- GOOGLE PAY REQUEST ----------
function makeGooglePayRequest($G){
    $url = "https://pay.google.com/g4b/_/SMBConsoleUI/data/batchexecute?".
           "rpcids=RPtkab&source-path=/g4b/transactions/BCR2DN4TU2AP5QCB".
           "&f.sid=8586358160238679812&bl=boq_payments-merchant-console-ui_20250803.08_p0".
           "&hl=en-GB&soc-app=1&soc-platform=1&soc-device=2&_reqid=971843&rt=c";

    $headers = [
        "content-type: application/x-www-form-urlencoded;charset=UTF-8",
        "origin: https://pay.google.com",
        "referer: https://pay.google.com/",
        "user-agent: Mozilla/5.0",
        "cookie: ".$G["COOKIE"]
    ];

    if($auth = sapiHash($G["COOKIE"])){
        $headers[] = "authorization: $auth";
        $headers[] = "x-origin: https://pay.google.com";
    }

    $post = "f.req=".urlencode($G["FREQ_RAW"])."&at=".urlencode($G["AT"]);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL=>$url,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_POST=>true,
        CURLOPT_HTTPHEADER=>$headers,
        CURLOPT_POSTFIELDS=>$post
    ]);

    $raw = curl_exec($ch);
    $err = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if($err || $code!=200) sendResponse("pending","Google Pay API Error");

    return $raw;
}

// ---------- PARSE RESPONSE ----------
function parseGP($raw){
    if(strpos($raw, ")]}'")===0) $raw=substr($raw, 4);
    $lines = explode("\n", trim($raw));
    $json = trim($lines[1] ?? "");
    $arr = json_decode($json, true);
    $payload = $arr[0][2] ?? null;

    for($i=0;$i<3;$i++){
        if(is_string($payload)){
            $tmp = json_decode($payload, true);
            if($tmp!==null) $payload=$tmp;
        }
    }
    return $payload[0] ?? [];
}

// ---------- MATCH REMARK ----------
function findTxn($txns, $remarks){
    foreach($txns as $t){
        if(trim(($t[9] ?? "")) === trim($remarks)) return $t;
    }
    return null;
}

// ----------- MAIN EXECUTION -----------

try {

$order_id   = $_POST["order_id"] ?? "";
$user_token = $_POST["user_token"] ?? "";

validateInputs($order_id, $user_token);

$order = getOrderData($conn, $order_id, $user_token);

$txnId = trim($order["txnId"]);
$amount = $order["amount"];
$mobile = $order["mobile"];
$user_id = $order["user_id"];

$G = getGooglePayData($conn, $user_token, $mobile);

if(!$G) sendResponse("pending", "GooglePay token not found");

if(empty($G["AT"]) || empty($G["FREQ_RAW"]) || empty($G["COOKIE"]))
    sendResponse("pending", "GooglePay token incomplete");

$raw = makeGooglePayRequest($G);

$payload = parseGP($raw);

$txn = findTxn($payload, $txnId);

if(!$txn) sendResponse("pending","No matching transaction");

$txnAmount = $txn[3][1] ?? "0";
$utr = $txn[1] ?? "";
$payer = $txn[8][1] ?? "";
$status = ((int)($txn[10] ?? 0)===5) ? "SUCCESS" : "FAILED";

if($status==="SUCCESS" && $txnAmount==$amount){

    setXbyY("UPDATE orders SET status='SUCCESS', utr='$utr', payerUpi='$payer' WHERE order_id='$order_id'");
    sendResponse("success","Payment Success",[
        "utr"=>$utr,
        "amount"=>$txnAmount
    ]);

}

sendResponse("pending","Pending or Mismatch");

}
catch(Exception $e){
    sendResponse("FAILURE","Error",["reason"=>$e->getMessage()]);
}

?>
