<?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['voter_Mobile_Link_Service']) && $user_data['voter_Mobile_Link_Service'] == "YES") {
    $main_site_data = main_site_data();
        if ( isset($_POST['order_id']) && !empty($_POST['order_id']) && !empty($_POST['voterNumber']) && !empty($_POST['mobileNumber'])) {

            $order_id     = $_POST['order_id'] ?? '';
            $voterNumber  = $_POST['voterNumber'] ?? '';
            $mobileNumber = $_POST['mobileNumber'] ?? '';

            $request = [
                'order_id'     => $order_id,
                'voterNumber'  => $voterNumber,
                'mobileNumber' => $mobileNumber
            ];

            $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'])) {

                    $databaseStatus = (string)($pan_info['status'] ?? '');
                    $memberData = db_fetch_array('members', "user_id = '{$pan_info['user_id']}'");

                    if (!empty($memberData) && !empty($memberData['username'])) {

                        $usernamepanrefund = (string)($memberData['user_id'] ?? $user_data['user_id']);

                        if (in_array($databaseStatus, ["Process", "Pending"])) {

                            $responseApi = VoterMobileLink_DataCheckstatus_run($request);
                            $StatusResponse = json_decode($responseApi, true) ?? '';

                            if ($responseApi === false) {
                                alert_js("Failed to fetch order information from the API." .$StatusResponse);
                            }

                            if ($StatusResponse === null || !isset($StatusResponse['status'])) {
                                alert_js("Invalid response from the API.");
                            }

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

                            /* SUCCESS */
                            if ($statusMessage == 'success') {

                                $echoPayload = [
                                    'status'        => $StatusResponse["status"] ?? '',
                                    'statusMessage' => $StatusResponse["statusMessage"] ?? '',
                                    'voterNumber'   => $StatusResponse["epicNumber"] ?? '',
                                    'name'          => $StatusResponse["name"] ?? '',
                                    'mobileNumber'  => $StatusResponse["MobileNumber"] ?? '',
                                    'username'      => $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);

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

                                db_update('printRecords', [
                                    'date_time' => current_timestamp(),
                                    'name'      => $StatusResponse['name'],
                                    'status'    => ucwords($StatusResponse['statusMessage'])
                                ], "order_id = '{$order_id}'");
                                
                               alert_js($StatusResponse['message'] ?? 'Application Success But Api Response error.');
                            }elseif ($statusMessage == 'refunded') {

                                $amount      = $memberData['voter_mobile_link_fee'];
                                $old_balance = $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'       => $memberData['username'],
                                        'name'           => $memberData['name'],
                                        'operator'       => $memberData['usertype'],
                                        'parent_id'      => $memberData['parent_id'],
                                        'order_id'       => $refundOrderID,
                                        'service'        => "VCM_REFUND",
                                        'type'           => "Credit",
                                        'account_number' => $StatusResponse['epicNumber'],
                                        'app_type'       => "VCM_REFUND",
                                        'amount'         => $amount,
                                        'main_amount'    => $amount,
                                        'old_balance'    => $old_balance,
                                        'new_balance'    => $new_balance,
                                        'txn_id'         => $refundOrderID,
                                        'ref_id'         => $StatusResponse['epicNumber'],
                                        'description'    => "Rs.{$amount} Has Been Credit From Wallet for {$StatusResponse['epicNumber']}",
                                        'date_time'      => current_timestamp(),
                                        'status'         => "Refund",
                                    ];

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

                                    if ($insertId) {

                                        $echoPayload = [
                                            'status'        => $StatusResponse["status"] ?? '',
                                            'statusMessage' => $StatusResponse["statusMessage"] ?? '',
                                            'voterNumber'   => $StatusResponse["epicNumber"] ?? '',
                                            'MobileNumber'  => $StatusResponse["MobileNumber"] ?? '',
                                            'username'      => $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); 

                                        db_update('reports', [
                                            'date_time'    => current_timestamp(),
                                            'api_response' => $encoded,
                                            'status'       => 'Refund',
                                        ], "order_id = '{$order_id}'");

                                        db_update('printRecords', [
                                            'date_time' => current_timestamp(),
                                            'status'       => 'Refund',
                                        ], "order_id = '{$order_id}'");
                                        
                                      alert_js($StatusResponse['message'] ?? 'Application Refunded But Api Response error.');
                                    } else {
                                        alert_js("Balance Refunded - Record not updated please contact admin.");
                                    }

                                } else {
                                    alert_js("Balance Refund Server Issue. Please contact support!");
                                }
                            }else {
                                alert_js($StatusResponse['message'] ?? $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 {

                db_update('reports', [
                    'date_time' => current_timestamp(),
                    'status'    => "Failed"
                ], "order_id = '{$order_id}'");

                alert_js("Duplicate Order ID. This is already Process!");
            }

            redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/vcmRequest", 0);
            die();

        } else {
            echo "Access Denied.";
            die();
        }

    } else {
        awal_alert_msg('You Do Not Have Any Voter Service Activated !', 'info', 'dashboard');
    }

} else {
    session_destroy();
    redirect("logout", 0);
    die;
}
?>
