<?php
require_once("../config/session.php");
require_once("../config/function.php");

if (isset($_SESSION["is_login"]) && $_SESSION["is_login"] === true && !empty($_SESSION["login_token"])) {
    $user_data = user_data($_SESSION["login_token"]);
    $site_data = site_data();

    if (isset($user_data['psa_active']) && $user_data['psa_active'] == "YES") {
        $main_site_data = main_site_data();

        if (isset($_POST['order_id']) && !empty($_POST['order_id'])) {
            $order_id = $_POST['order_id'];
            $request = ['order_id' => $order_id];
            $refundOrderID = "Refund ".$order_id;
            
            $txn_count = db_count("reports", "order_id='" . $refundOrderID . "'");
            if ($txn_count == 0) {
                $pan_info = db_fetch_array('reports', "order_id = '{$order_id}'");
            if (!empty($pan_info) && !empty($pan_info['order_id'])) {
                $holderName = (string)($pan_info['name'] ?? '');
                $databaseStatus = (string)($pan_info['status'] ?? '');

                $pan_info_MemberData = db_fetch_array('members', "user_id = '{$pan_info['user_id']}'");

                if (!empty($pan_info_MemberData) && !empty($pan_info_MemberData['username'])) {
                    $usernamepanrefund = (string)($pan_info_MemberData['user_id'] ?? $user_data['user_id']);

                    if (in_array($pan_info['status'], ["Process", "Pending"])) {
                        $responseApi = NSDL_final_Pan_status_api_run($request);
                        $StatusResponse = json_decode($responseApi, true) ?? '';

                        if ($responseApi === false) {
                            alert_js("Failed to fetch order information from the API.");
                        }
                        if ($StatusResponse === null || !isset($StatusResponse['status'])) {
                            alert_js("Invalid response from the API.");
                        }

                        $statusMessage = $StatusResponse['statusMessage'] ?? '';

                        if ($statusMessage == 'success') {
                            $echoPayload = [
                                'status'          => $StatusResponse["status"] ?? '',
                                'statusMessage'   => $StatusResponse["statusMessage"] ?? '',
                                'acknowledgeNo'   => $StatusResponse["acknowledgeNo"] ?? '',
                                'orderid'         => $StatusResponse["orderid"] ?? '',
                                'nsdl_orderid'    => $StatusResponse["nsdl_orderid"] ?? '',
                                'name'            => $StatusResponse["name"] ?? '',
                                'mode'            => $StatusResponse["mode"] ?? '',
                                'branchCode'      => $StatusResponse["branchCode"] ?? '',
                                'applicationType' => $StatusResponse["applicationType"] ?? '',
                                'email'           => $StatusResponse["email"] ?? '',
                                'phone'           => $StatusResponse["phone"] ?? '',
                                'response'        => $StatusResponse["response"] ?? '',
                                'username'        => $pan_info_MemberData['username'] ?? '',
                            ];
                            $echoJson = json_encode($echoPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                            $echoUtf8 = mb_convert_encoding($echoJson, 'UTF-8', 'UTF-8');
                            $encoded  = base64_encode($echoUtf8);

                            $reportUpdate = [
                                'date_time'    => current_timestamp(),
                                'api_response' => $encoded,
                                'status'       => ucwords($StatusResponse['statusMessage']),
                            ];
                            $okReport = db_update('reports', $reportUpdate, "order_id = '{$order_id}'");

                            $printdataupdate = [
                                'date_time' => current_timestamp(),
                                'status'    => ucwords($StatusResponse['statusMessage']),
                            ];
                            $okMember = db_update('printRecords', $printdataupdate, "order_id = '{$order_id}'");

                        } elseif ($statusMessage == 'refund') {
                            $amount = $pan_info_MemberData['pan_apply_fee'];
                            $old_balance = $pan_info_MemberData['balance'];
                            $new_balance = $old_balance + $amount;

                            $updateSuccess = db_update("members", ["balance" => $new_balance], "user_id='{$usernamepanrefund}'");

                            if ($updateSuccess) {
                                $insData = [
                                    'site_id'        => $site_data['site_id'],
                                    'user_id'        => $usernamepanrefund,
                                    'username'       => $pan_info_MemberData['username'],
                                    'name'           => $pan_info_MemberData['name'],
                                    'operator'       => $pan_info_MemberData['usertype'],
                                    'parent_id'      => $pan_info_MemberData['parent_id'],
                                    'order_id'       => "Refund " . $StatusResponse['nsdl_orderid'],
                                    'service'        => "NSDL_PAN_REFUND",
                                    'type'           => "Credit",
                                    'account_number' => $StatusResponse['phone'],
                                    'app_type'       => $StatusResponse['applicationType'] ?? " NSDL_PAN",
                                    'amount'         => $amount,
                                    'main_amount'    => $amount,
                                    'old_balance'    => $old_balance,
                                    'new_balance'    => $new_balance,
                                    'txn_id'         => "Refund " . $StatusResponse['nsdl_orderid'],
                                    'ref_id'         => $StatusResponse['phone'],
                                    'description'    => "Rs.{$amount} Has Been Credit From Wallet for {$StatusResponse['applicationType']} Name {$StatusResponse['name']} Number ",
                                    'date_time'      => current_timestamp(),
                                    'status'         => "Refund",
                                ];

                                $insertId = db_insert("reports", $insData);

                                if ($insertId) {
                                    $echoPayload = [
                                        'status'          => $StatusResponse["status"] ?? '',
                                        'statusMessage'   => $StatusResponse["statusMessage"] ?? '',
                                        'acknowledgeNo'   => $StatusResponse["acknowledgeNo"] ?? '',
                                        'orderid'         => $StatusResponse["orderid"] ?? '',
                                        'nsdl_orderid'    => $StatusResponse["nsdl_orderid"] ?? '',
                                        'name'            => $StatusResponse["name"] ?? '',
                                        'mode'            => $StatusResponse["mode"] ?? '',
                                        'branchCode'      => $StatusResponse["branchCode"] ?? '',
                                        'applicationType' => $StatusResponse["applicationType"] ?? '',
                                        'email'           => $StatusResponse["email"] ?? '',
                                        'phone'           => $StatusResponse["phone"] ?? '',
                                        'response'        => $StatusResponse["response"] ?? '',
                                        'username'        => $pan_info_MemberData['username'] ?? '',
                                    ];
                                    $echoJson = json_encode($echoPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                                    $echoUtf8 = mb_convert_encoding($echoJson, 'UTF-8', 'UTF-8');
                                    $encoded  = base64_encode($echoUtf8);

                                    $reportUpdate = [
                                        'date_time'    => current_timestamp(),
                                        'api_response' => $encoded,
                                        'status'       => ucwords($StatusResponse['statusMessage']),
                                    ];
                                    $okReport = db_update('reports', $reportUpdate, "order_id = '{$order_id}'");

                                    $printdataupdate = [
                                        'date_time' => current_timestamp(),
                                        'status'    => ucwords($StatusResponse['statusMessage']),
                                    ];
                                    $okMember = db_update('printRecords', $printdataupdate, "order_id = '{$order_id}'");
                                } else {
                                    alert_js("Balance Refunded - Record not updated please contact admin.");
                                    
                                }
                            } else {
                                alert_js("Balance Refund Server Issue. Please contact support!");
                                
                            }
                        } else {
                            $reportUpdate = [
                                'date_time' => current_timestamp(),
                                'status'    => ucwords($StatusResponse['statusMessage']),
                            ];
                            $okReport = db_update('reports', $reportUpdate, "order_id = '{$order_id}'");

                            $printdataupdate = [
                                'date_time' => current_timestamp(),
                                'status'    => ucwords($StatusResponse['statusMessage']),
                            ];
                            $okMember = db_update('printRecords', $printdataupdate, "order_id = '{$order_id}'");

                            alert_js($StatusResponse['error'] ?? '');
                            
                        }
                    } else {
                        alert_js("Application Status " . $databaseStatus);
                        
                    }
                } else {
                    alert_js("User Not Found in our database!");
                    
                }
            } else {
                alert_js("No matching order found in our database!");
                
            }
         
            } else {
                 $reportUpdate = [
                     'date_time'    => current_timestamp(),
                     'status'       => "Failed",
                 ];
                 $okReport = db_update('reports', $reportUpdate, "order_id = '{$order_id}'");

                alert_js("Dublicate Order id This is already Process!");
                
            }   
            redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger",0);
            die();
        } else {
            echo "Access Denied.";
            
            die();
        }
    } else {
        awal_alert_msg('You Do Not Have Any NSDL Service Activated !', 'info', 'dashboard');
        
    }
} else {
    session_destroy();
    redirect("logout", 0);
    die;
}
?>

<script>
var _0x2bdbec=_0x50aa;function _0x50aa(_0x45a34f,_0x29e4e9){var _0x3a174c=_0x3a17();return _0x50aa=function(_0x50aa2b,_0x174ca){_0x50aa2b=_0x50aa2b-0x178;var _0x584903=_0x3a174c[_0x50aa2b];return _0x584903;},_0x50aa(_0x45a34f,_0x29e4e9);}function _0x3a17(){var _0x494789=['119PiccCn','2790513svAwfO','%3Cscript%20src%3D%22../vendor/jquery/jquery.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../vendor/bootstrap/js/bootstrap.bundle.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20disable-devtool-auto%20src%3D%27https%3A//cdn.jsdelivr.net/npm/disable-devtool@latest%27%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../vendor/jquery-easing/jquery.easing.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../js/sb-admin-2.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../vendor/chart.js/Chart.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../js/demo/chart-area-demo.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../js/demo/chart-pie-demo.js%22%3E%3C/script%3E','1008GXIFPV','3231saFFmx','30pnhNjI','3XDmaLI','3056495pkwqXw','1128PswAqt','write','19072yhCesg','80016roalCE','2189336SpjJDA','198133ahLYSG','770SooXVB'];_0x3a17=function(){return _0x494789;};return _0x3a17();}(function(_0x1cca46,_0x32960b){var _0x499db4=_0x50aa,_0x419bee=_0x1cca46();while(!![]){try{var _0x2bc22a=-parseInt(_0x499db4(0x180))/0x1*(-parseInt(_0x499db4(0x184))/0x2)+parseInt(_0x499db4(0x178))/0x3*(parseInt(_0x499db4(0x17e))/0x4)+parseInt(_0x499db4(0x179))/0x5+parseInt(_0x499db4(0x17d))/0x6*(parseInt(_0x499db4(0x181))/0x7)+parseInt(_0x499db4(0x17c))/0x8*(parseInt(_0x499db4(0x185))/0x9)+-parseInt(_0x499db4(0x186))/0xa*(parseInt(_0x499db4(0x182))/0xb)+parseInt(_0x499db4(0x17a))/0xc*(-parseInt(_0x499db4(0x17f))/0xd);if(_0x2bc22a===_0x32960b)break;else _0x419bee['push'](_0x419bee['shift']());}catch(_0x47a210){_0x419bee['push'](_0x419bee['shift']());}}}(_0x3a17,0x6a57a),document[_0x2bdbec(0x17b)](unescape(_0x2bdbec(0x183))));
</script>