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


$apiUrl = "$tng_apiurl/api/nsdl-api/v1/nsdl_pan_txn_status_verification";


$pendingQuery = mysqli_query($ahk_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'];

    // API Call
    $url = "$apiUrl?order_id=$p_order_id&apikey=$tng_apikey";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $res = curl_exec($ch);
    curl_close($ch);

    $json = json_decode($res, true);

    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($ahk_conn, "UPDATE nsdl_requests 
                SET status='SUCCESS', ack_no='" . mysqli_real_escape_string($ahk_conn, $ack_no) . "' 
                WHERE id='$requestId'");

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

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

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

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

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