<?php
include('config.php');
include('session.php');
$pendingQuery = mysqli_query($tng_conn, "SELECT * FROM nsdl_requests WHERE status='Pending'");

while ($row = mysqli_fetch_assoc($pendingQuery)) {
    $p_order_id = $row['p_order_id'];
    $userPhone = $row['phone'];
    $requestId = $row['id'];
    $request = [
        'order_id' => $p_order_id,
        ];

        $json = nsdl_pan_txn_status_verification_api_run($request);

    if (!empty($json['status']) && $json['status'] === "true" && !empty($json['data']['txn_status'])) {
        $txn_status = $json['data']['txn_status'];   
        $ack_no = $json['data']['ack_no'] ?? '';

        if ($txn_status === "SUCCESS") {
           
            mysqli_query($tng_conn, "UPDATE nsdl_requests 
                SET status='SUCCESS', ack_no='" . mysqli_real_escape_string($tng_conn, $ack_no) . "' 
                WHERE id='$requestId'");

        } elseif ($txn_status === "FAILED") {
          
            $feeRow = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT price FROM pricing WHERE service_name='nsdl_new_pan_fee' LIMIT 1"));
            $refundAmount = $feeRow['price'] ?? 0;

           
            mysqli_query($tng_conn, "UPDATE nsdl_requests 
                SET status='REFUNDED', ack_no=''
                WHERE id='$requestId'");

           
            mysqli_query($tng_conn, "UPDATE users SET balance=balance+$refundAmount WHERE phone='$userPhone'");

          
            $userData = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT balance FROM users WHERE phone='$userPhone'"));
            $newBalance = $userData['balance'];

            mysqli_query($tng_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type) 
                VALUES ('$userPhone', '$refundAmount', '$newBalance', 'NSDL PAN Refund', '1', 'Credit')");
        }
       
    }
}
?>