<?php
include('../includes/session.php');
include('../includes/config.php');

$mobileno = $udata['phone'] ?? '';

if (!$mobileno) {
    echo json_encode(['status'=>'error','message'=>'User session expired']);
    exit;
}

$type = $_POST['type'] ?? 'paytm';
$app  = $_POST['application_no'] ?? '';
$utr  = $_POST['utr'] ?? null;

if (!$app){
    echo json_encode(['status'=>'error','message'=>'Missing application number']);
    exit;
}

$url = "https://".JkL_get('paymentapi','gateway_Url')
     ."/bharatpaygateway_verification?type=".urlencode($type)
     ."&application_no=".urlencode($app)
     .($utr ? "&utr=".urlencode($utr) : "")
     ."&apikey=".urlencode(JkL_get('paymentapi','gateway_apikey'));

/* ===== DIRECT CURL ===== */
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 25,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo json_encode(['status'=>'error','message'=>'Curl Error: '.curl_error($ch)]);
    curl_close($ch);
    exit;
}

curl_close($ch);

$data = json_decode($response, true);

if (!isset($data['Message']) || $data['status'] !== 'SUCCESS'){
    echo json_encode(['status'=>'pending']);
    exit;
}

$utr   = mysqli_real_escape_string($tng_conn, $data['utr']);
$amt   = (float)$data['amount'];
$payer = mysqli_real_escape_string($tng_conn, $data['payerName'] ?? 'QR Payment');
$mode  = mysqli_real_escape_string($tng_conn, $data['payerHandle'] ?? 'QR');
$dt    = date('Y-m-d H:i:s');

/* ===== DUPLICATE CHECK DIRECT ===== */
$check = mysqli_query($tng_conn,"SELECT id FROM wallet WHERE BANKTXNID='$utr' AND phone='$mobileno' LIMIT 1");

if (mysqli_num_rows($check) == 0) {

    mysqli_query($tng_conn,"
        INSERT INTO wallet (phone,BANKTXNID,amount,RESPMSG,PAYMENTMODE,status,txn_date)
        VALUES ('$mobileno','$utr','$amt','$payer','$mode','success','$dt')
    ");

    mysqli_query($tng_conn,"
        UPDATE users SET balance = balance + $amt WHERE phone='$mobileno'
    ");
}

unset($_SESSION['qr_data'],$_SESSION['qr_amount'],$_SESSION['qr_generated_time']);

echo json_encode([
    'status'=>'success',
    'data'=>[
        'amount'=>$amt,
        'payer'=>$payer,
        'date'=>$dt
    ]
]);
exit;
?>
