<?php

/**
 * Class WC_Sep_Payment_Gateway
 */
class WC_Sep_Payment_Gateway extends WC_Payment_Gateway
{

    private $merchantcode;
    private $multiIban;
    private $sandbox;

    private $success_massage;

    private $failed_massage;
    public $goverment_details;

    /**
     * WC_Sep_Payment_Gateway constructor.
     */
    public function __construct()
    {
        $this->id = 'WC_Sep_Payment_Gateway';
        $this->method_title = __('Saman Bank Payment Gateway', 'sb24wc');
        $this->method_description = __('Bank Saman payment gateway settings for WooCommerce', 'sb24wc');
        $this->icon = SEP_WOO_IMAGE . '/gateway-saman.png';
        $this->title = __('Saman Bank gateway', 'sb24wc');

        $this->init_gateway_form_fields();
        $this->init_settings();

        $this->description = $this->get_option('description');
        $this->title = $this->get_option('title');

        $this->merchantcode = $this->get_option('merchantcode');
        $this->multiIban = $this->get_option('multi');
        $this->sandbox = $this->get_option('sandbox');

        $this->success_massage = $this->get_option('success_massage');
        $this->failed_massage = $this->get_option('failed_massage');
        $this->has_fields = false;

        $wc_version = get_option('woocommerce_version');

        if (version_compare($wc_version, '2.0.0', '>=')) {
            add_action('woocommerce_update_options_payment_gateways_' . $this->id,
                array($this, 'process_admin_options'));
        } else {
            add_action('woocommerce_update_options_payment_gateways', array($this, 'process_admin_options'));
        }
        add_action('woocommerce_receipt_' . $this->id, array($this, 'RequestPayment'));

        add_action('woocommerce_api_' . strtolower(get_class($this)),
            array($this, 'VerifyPayment'));

        $this->goverment_details = get_option(
            'woocommerce_sep_accounts',
            array(
                array(
                    'iban' => $this->get_option('iban'),
                    'percent' => $this->get_option('percent'),
                    'goverment' => $this->get_option('goverment'),
                ),
            )
        );

        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'save_goverment_details'));
    }

    /**
     * init gateway form fields in woocommerce setting page
     */
    public function init_gateway_form_fields()
    {
        $this->form_fields = [
            'base_config' => array(
                'title' => __('Basic Settings', 'sb24wc'),
                'type' => 'title',
                'description' => '',
            ),
            'enabled' => array(
                'title' => __('Activation/Deactivation', 'sb24wc'),
                'type' => 'checkbox',
                'label' => __('Saman Gateway Activation', 'sb24wc'),
                'description' => __('To activate the Saman payment gateway, you need to check the box.', 'sb24wc'),
                'default' => 'no',
                'desc_tip' => true,
            ),
            'title' => array(
                'title' => __('Gateway Title', 'sb24wc'),
                'type' => 'text',
                'description' => __('The title of the gateway displayed to the customer during the purchase.', 'sb24wc'),
                'default' => __('Saman Bank', 'sb24wc'),
                'desc_tip' => true,
            ),
            'description' => array(
                'title' => __('Gateway Description', 'sb24wc'),
                'type' => 'text',
                'desc_tip' => true,
                'description' => __('Details will be displayed during the payment process for the gateway.', 'sb24wc'),
                'default' => __('Secure payment through all Shetab member cards via Saman Bank gateway.', 'sb24wc'),

            ),
            'sandbox_config' => array(
                'title' => __('تنظیمات Sandbox (شبیه‌سازی)', 'sb24wc'),
                'type' => 'title',
                'description' => __('در حالت Sandbox می‌توانید تراکنش‌ها را بدون نیاز به حساب واقعی بانک تست کنید.', 'sb24wc'),
            ),
            'sandbox' => array(
                'title' => __('فعال‌سازی حالت Sandbox', 'sb24wc'),
                'type' => 'checkbox',
                'label' => __('فعال‌سازی حالت تست و شبیه‌سازی', 'sb24wc'),
                'description' => __('با فعال‌سازی این گزینه، تراکنش‌ها به صورت شبیه‌سازی شده پردازش می‌شوند و نیازی به حساب واقعی بانک نیست. توجه: در حالت Sandbox هیچ تراکنش واقعی انجام نمی‌شود.', 'sb24wc'),
                'default' => 'no',
                'desc_tip' => true,
            ),
            'account_config' => array(
                'title' => __('Saman account settings', 'sb24wc'),
                'type' => 'title',
                'description' => '',
            ),
            'merchantcode' => array(
                'title' => __('Merchant ID', 'sb24wc'),
                'type' => 'text',
                'description' => __('Merchant ID received from Saman Bank. در حالت Sandbox می‌توانید هر کدی وارد کنید.', 'sb24wc'),
                'default' => '',
                'desc_tip' => true,
            ),
            'payment_config' => array(
                'title' => __('Payment Operations Settings', 'sb24wc'),
                'type' => 'title',
                'description' => '',
            ),
            'success_massage' => array(
                'title' => __('Payment Successful', 'sb24wc'),
                'type' => 'textarea',
                'description' => __('Please enter the message you wish to display to the user after a successful payment. You can also use the shortcode {transaction_id} to display the tracking code (token) of Saman Bank.', 'sb24wc'),
                'default' => __('Thank you. Your order has been successfully paid.', 'sb24wc'),
            ),
            'failed_massage' => array(
                'title' => __('Payment Failed Message', 'sb24wc'),
                'type' => 'textarea',
                'description' => __('Please enter the message you would like to display to the user after an unsuccessful payment. You can also use the shortcode {fault} to display the reason for the error. This error reason is sent from the site system.', 'sb24wc'),
                'default' => __('Your payment was unsuccessful. Please try again or contact the website administrator if you encounter any issues.', 'sb24wc'),
            ),
            'multi' => array(
                'title' => __('Government funds (Public funds)', 'sb24wc'),
                'type' => 'checkbox',
                'label' => __('Multiple account payment and government funds activation', 'sb24wc'),
                'description' => __('If you activate this section, you can define several accounts, including government and ordinary accounts', 'sb24wc'),
                'default' => 'no',
                'desc_tip' => true,
            ),
            'goverment' => array(
                'type' => 'goverment_details',
            ),
        ];

    }

    public function generate_goverment_details_html()
    {

        ob_start();

        ?>
        <tr valign="top" class="hideable_field">
            <th scope="row" class="titledesc">
                <label>
                    <?php esc_html_e('Account information', 'sb24wc'); ?>
                    <?php echo wp_kses_post(wc_help_tip(__('For sharing and government payments, enter the information of your desired accounts', 'sb24wc'))); ?>
                </label>
            </th>
            <td class="forminp" id="sep_accounts">
                <div class="wc_input_table_wrapper">
                    <table class="widefat wc_input_table" cellspacing="0">
                        <thead>
                        <tr>
                            <th><?php esc_html_e('IBAN', 'sb24wc'); ?></th>
                            <th><?php esc_html_e('Share percentage', 'sb24wc'); ?></th>
                            <th><?php esc_html_e('Government ID', 'sb24wc'); ?></th>
                        </tr>
                        </thead>
                        <tbody class="accounts">
                        <?php
                        $i = -1;
                        if ($this->goverment_details) {
                            foreach ($this->goverment_details as $account) {
                                $i++;

                                echo '<tr class="account">

										<td><input type="text" class="first_iban" value="' . esc_attr($account['iban']) . '" name="group_iban[' . esc_attr($i) . ']" /></td>
										<td><input type="number" class="first_percent" value="' . esc_attr($account['percent']) . '" name="group_percent[' . esc_attr($i) . ']" /></td>
										<td><input type="text" value="' . esc_attr($account['goverment']) . '" name="group_goverment[' . esc_attr($i) . ']" /></td>

									</tr>';
                            }
                        }
                        ?>
                        </tbody>
                        <tfoot>
                        <tr>
                            <th colspan="7"><a href="#"
                                               class="add button"><?php esc_html_e('+ Add account', 'woocommerce'); ?></a>
                                <a href="#"
                                   class="remove_rows button"><?php esc_html_e('Remove selected account(s)', 'woocommerce'); ?></a>
                            </th>
                        </tr>
                        </tfoot>
                    </table>
                </div>
                <script type="text/javascript">
                    jQuery(document).ready(function ($) {
                        function toggleRepeaterFields() {
                            if ($('#woocommerce_WC_Sep_Payment_Gateway_multi').is(':checked')) {
                                $('.hideable_field').closest('tr').show();
                                $(".first_iban").attr("required", true);
								$(".first_percent").attr("required", true);
                            } else {
                                $('.hideable_field').closest('tr').hide();
                                $(".first_iban").removeAttr('required');
								$(".first_percent").removeAttr('required');
                            }
                        }

                        toggleRepeaterFields();
                        $('#woocommerce_WC_Sep_Payment_Gateway_multi').change(function () {
                            toggleRepeaterFields();
                        });

                    });

                    jQuery(function () {
                        jQuery('#sep_accounts').on('click', 'a.add', function () {
                            var size = jQuery('#sep_accounts').find('tbody .account').length;
                            if (size > 7) return false;
                            jQuery('<tr class="account">\
									<td><input type="text" required name="group_iban[' + size + ']" /></td>\
									<td><input type="text" required name="group_percent[' + size + ']" /></td>\
									<td><input type="text" name="group_goverment[' + size + ']" /></td>\
								</tr>').appendTo('#sep_accounts table tbody');

                            return false;
                        });
                    });
                </script>
            </td>
        </tr>
        <?php
        return ob_get_clean();

    }

    public function save_goverment_details()
    {

        $accounts = array();

        if (isset($_POST['group_iban']) && isset($_POST['group_percent'])) {

            $ibans = wc_clean(wp_unslash($_POST['group_iban']));
            $percent = wc_clean(wp_unslash($_POST['group_percent']));
            $goverment = wc_clean(wp_unslash($_POST['group_goverment']));
            $totalPercent = array_sum($percent);
            if ($totalPercent !== 100) {
                WC_Admin_Settings::add_error(__('The total share percentage should always be 100%', 'sb24wc'));
                return;
            }
            foreach ($ibans as $i => $iban) {
                if (!isset($ibans[$i])) {
                    continue;
                }

                $accounts[] = array(
                    'iban' => $ibans[$i],
                    'percent' => $percent[$i],
                    'goverment' => $goverment[$i],
                );
            }

        }
        // phpcs:enable

        do_action('woocommerce_update_option', array('id' => 'woocommerce_sep_accounts'));
        update_option('woocommerce_sep_accounts', $accounts);
    }

    /**
     * override process_payment method in WC_Payment_Gateway
     * @param int $order_id
     * @return array
     */
    public function process_payment($order_id)
    {
        $order = new WC_Order($order_id);

        return array(
            'result' => 'success',
            'redirect' => $order->get_checkout_payment_url(true),
        );
    }

    /**
     * send request for payment to bank and redirect to bank
     * @param int $order_id
     * @return void
     */
    public function RequestPayment($order_id)
    {
        global $woocommerce;
        $woocommerce->session->sep_order_id = $order_id;
        $order = new WC_Order($order_id);
        $currency = $order->get_currency();

        $total = intval($order->get_total());

        if (
            strtolower($currency) == strtolower('IRT')
            || strtolower($currency) == strtolower('TOMAN')
            || strtolower($currency) == strtolower('Iran TOMAN')
            || strtolower($currency) == strtolower('Iranian TOMAN')
            || strtolower($currency) == strtolower('Iran-TOMAN')
            || strtolower($currency) == strtolower('Iranian-TOMAN')
            || strtolower($currency) == strtolower('Iran_TOMAN')
            || strtolower($currency) == strtolower('Iranian_TOMAN')
            || strtolower($currency) == strtolower('تومان')
            || strtolower($currency) == strtolower('تومان ایران')
        ) {
            $total = $total * 10;
        } else if (strtolower($currency) == strtolower('IRHT')) {
            $total = $total * 10000;
        } else if (strtolower($currency) == strtolower('IRHR')) {
            $total = $total * 1000;
        }

        // Check if Sandbox mode is enabled
        $sandbox_enabled = $this->get_option('sandbox');
        if ($sandbox_enabled === 'yes' || $sandbox_enabled === '1' || $sandbox_enabled === true) {
            $this->handle_sandbox_payment($order_id, $total);
            exit; // Important: exit after rendering sandbox page
        }

        $MerchantCode = $this->merchantcode;
        $ResNumber = $order_id;
        $Payment_URL = self::get_env('PAYMENT_URL');

        $Token = json_decode($this->get_token($MerchantCode, $total, $ResNumber));

        if (!empty($Token->status)) {
            if ($Token->status === 1) {
                echo __('Transferring to the banking portal, please wait...', 'sb24wc');
                ?>
                <form id="pay_form" action="<?= $Payment_URL ?>" method="post" style="display: none;">
                    <input type="hidden" name="Token" value="<?= $Token->token ?>"/>
                    <input name="GetMethod" type="text" value="">
                </form>
                <script type="text/javascript"> document.getElementById("pay_form").submit(); </script>
                <?php
                exit;
            } else {
                $error = $Token->errorDesc ?? "";

                $Note = __('Error connecting to the bank port', 'sb24wc') . " " . $error;
                wc_add_notice($Note, 'error');

                $error_note = sprintf(
                    __('خطای اتصال به درگاه: %s (کد خطا: %s)', 'sb24wc'),
                    $error,
                    !empty($Token->errorCode) ? $Token->errorCode : __('نامشخص', 'sb24wc')
                );
                $order->add_order_note($error_note, 0);

                $url = wc_get_checkout_url();
                wp_safe_redirect($url);
            }
        } else {
            $Note = __('An error has occurred, please contact support.', 'sb24wc');
            wc_add_notice($Note, 'error');

            $error_note = sprintf(
                __('خطای شبکه در اتصال به درگاه پرداخت. خطا: %s', 'sb24wc'),
                !empty($Token->errorCode) ? print_r($Token->errorCode, true) : __('خطای نامشخص', 'sb24wc')
            );
            $order->add_order_note($error_note, 0);

            $url = wc_get_checkout_url();
            wp_safe_redirect($url);
        }

    }

    /**
     * back from gateway saman bank
     */
    public function VerifyPayment()
    {

        global $woocommerce;
        $State = $_POST['State'] ?? '';
        $ResNum = $_POST['ResNum'] ?? '';
        $RefNum = $_POST['RefNum'] ?? '';
        $TermId = $this->merchantcode ?? '';

        if (isset($_GET['wc_order'])) {
            $order_id = $_GET['wc_order'];
        } else if ($ResNum) {
            $order_id = $ResNum;
        } else {
            $order_id = $woocommerce->session->sep_order_id;
            unset($woocommerce->session->sep_order_id);
        }

        if ($order_id) {
            $order = new WC_Order($order_id);

            // Check if Sandbox mode is enabled
            $sandbox_enabled = $this->get_option('sandbox');
            if ($sandbox_enabled === 'yes' || $sandbox_enabled === '1' || $sandbox_enabled === true) {
                $this->handle_sandbox_verify($order_id, $State, $ResNum, $RefNum);
                return;
            }

            if ($order->get_status() != 'completed') {
                if ($State != '' && $ResNum != '' && $RefNum != '') {

                    $result = $this->get_verify_trans($TermId, $RefNum);
                    $Message = "";

                    if (is_null($result['result']->TransactionDetail)) {
                        $Status = 'failed';
                        $Message = __('There is a problem with the payment, please contact support.', 'sb24wc');
                    } elseif ($result['result']->ResultCode == 0) {
                        $Status = 'done';
                    } else {
                        $Status = 'failed';
                        $Message = sprintf(__("The transaction with bank ID %s has failed and the amount paid will be automatically refunded.", 'sb24wc'), $RefNum);
                    }
                } else {
                    $Status = 'failed';
                    $Message = __('One or more parameters were not sent.', 'sb24wc');
                }

                if ($Status === 'done') {
                    update_post_meta($order_id, '_transaction_id', $RefNum);
                    $order->payment_complete($RefNum);
                    $woocommerce->cart->empty_cart();
                    $Note = sprintf('Payment was successful. </br> Tracking code: %s', $RefNum);
                    $order->add_order_note($Note, 1);

                    $Notice = wpautop(wptexturize($this->success_massage));
                    $Notice = str_replace("{transaction_id}", $RefNum, $Notice);
                    if ($Notice) {
                        wc_add_notice($Notice, 'success');
                    }

                    wp_redirect(add_query_arg('wc_status', 'success', $this->get_return_url($order)));
                    exit;

                } else {
                    $tr_id = (isset($result)) ? (sprintf(__("Error number: <br/> %s", 'sb24wc'), $result['result']->ResultCode)) : '';
                    $Note = sprintf('Error while returning from bank: %s %s', $Message, $tr_id);

                    if ($Note) {
                        $order->add_order_note($Note, 1);
                    }

                    $Notice = wpautop(wptexturize($this->failed_massage));
                    $Notice = str_replace("{transaction_id}", $RefNum, $Notice);
                    $Notice = str_replace("{fault}", $Message, $Notice);

                    if ($Notice) {
                        wc_add_notice($Notice, 'error');
                    }

                    wp_redirect(wc_get_checkout_url());
                    exit;
                }
            } else {
                $Transaction_ID = get_post_meta($order_id, '_transaction_id', true);
                $Notice = wpautop(wptexturize($this->success_massage));
                $Notice = str_replace("{transaction_id}", $Transaction_ID, $Notice);

                if ($Notice) {
                    wc_add_notice($Notice, 'success');
                }
                wp_redirect(add_query_arg('wc_status', 'success', $this->get_return_url($order)));
                exit;
            }
        } else {
            $Fault = __('There is no order number.', 'sb24wc');
            $Notice = wpautop(wptexturize($this->failed_massage));
            $Notice = str_replace("{fault}", $Fault, $Notice);

            if ($Notice) {
                wc_add_notice($Notice, 'error');
            }
            wp_redirect(wc_get_checkout_url());
            exit;
        }
    }

    /**
     * get token from bank
     * @param string $TerminalId
     * @param int|float $Amount
     * @param int $ResNum
     * @return bool|string
     */
    public function get_token($TerminalId, $Amount, $ResNum)
    {
        // In Sandbox mode, return a fake token
        $sandbox_enabled = $this->get_option('sandbox');
        if ($sandbox_enabled === 'yes' || $sandbox_enabled === '1' || $sandbox_enabled === true) {
            $sandbox_token = new stdClass();
            $sandbox_token->status = 1;
            $sandbox_token->token = 'SANDBOX_' . time() . '_' . $ResNum;
            return json_encode($sandbox_token);
        }

        $order = new WC_Order($ResNum);
        $CallbackUrl = add_query_arg('wc_order', $ResNum, WC()->api_request_url('WC_Sep_Payment_Gateway'));

        $Token_url = self::get_env('TOKEN_URL');

        $data = [
            "action" => "token",
            "TerminalId" => $TerminalId,
            "Amount" => $Amount,
            "ResNum" => $ResNum,
            "RedirectUrl" => $CallbackUrl,
            "CellNumber" => $order->get_billing_phone(),
        ];
        if ($this->multiIban === 'yes') {
            if ($this->goverment_details) {

                foreach ($this->goverment_details as $accounts) {
                    $share = ($Amount * $accounts['percent']) / 100;
                    $SettlementIBANInfo = new stdClass();
                    $SettlementIBANInfo->IBAN = $accounts['iban'];
                    $SettlementIBANInfo->Amount = $share;
                    if (!empty($accounts['goverment'])) {
                        $data['TranType'] = "Government";
                        $SettlementIBANInfo->PurchaseID = $accounts['goverment'];
                    }

                    $data['SettlementIBANInfo'][] = $SettlementIBANInfo;
                }
            }
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $Token_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //todo: it must change to true, but need an option for set it to false for some host with old ssl package
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        $resp = curl_exec($ch);

        if (curl_errno($ch)) {
            $curl_error = curl_error($ch);
            $curl_errno = curl_errno($ch);
            
            // Log network error to order
            $order = new WC_Order($ResNum);
            $error_note = sprintf(
                __('خطای شبکه در دریافت توکن: %s (کد خطا: %d)', 'sb24wc'),
                $curl_error,
                $curl_errno
            );
            $order->add_order_note($error_note, 0);
            
            curl_close($ch);
            return json_encode(array('status' => 0, 'errorDesc' => $curl_error, 'errorCode' => $curl_errno));
        }

        curl_close($ch);

        return $resp;

    }

    /**
     * verify transaction result with bank
     * @param string $TermId
     * @param string $RefNum
     * @return array
     */
    public function get_verify_trans($TermId, $RefNum)
    {
        $postFields = array(
            "TerminalNumber" => $TermId,
            "RefNum" => $RefNum,
            "CellNumber" => "",
            "NationalCode" => "",
            "IgnoreNationalcode" => true,
        );

        $postFieldsJson = json_encode($postFields);
        $curl = curl_init();

        $payment_verify = self::get_env('PAYMENT_VERIFY');

        curl_setopt_array($curl, array(
            CURLOPT_URL => $payment_verify,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $postFieldsJson,
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/json",
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        $errno = curl_errno($curl);

        curl_close($curl);
        $result = json_decode($response);

        $trans['result'] = $result;

        if ($err) {
            $trans['err'] = $err;
            $trans['errno'] = $errno;
            // Log network error
            $order_id = $this->get_order_id_from_refnum($RefNum);
            if ($order_id) {
                $order = new WC_Order($order_id);
                $error_note = sprintf(
                    __('خطای شبکه در تایید تراکنش: %s (کد خطا: %d)', 'sb24wc'),
                    $err,
                    $errno
                );
                $order->add_order_note($error_note, 0);
            }
        }

        return $trans;
    }

    /**
     * read env file
     * @param $name
     * @return false|string
     */
    private function get_env($name)
    {
        $envFile = SEP_WOO_IRANDARGAH_PATH . '.env';
        if (file_exists($envFile)) {
            $envLines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

            $envVariables = [];
            foreach ($envLines as $line) {
                if (strpos($line, '=') !== false && strpos($line, '#') !== 0) {
                    list($key, $value) = explode('=', $line, 2);
                    if ($key != $name) {
                        continue;
                    }

                    return $value;
                }
            }
        }

        return false;
    }

    /**
     * Get order ID from RefNum
     * @param string $RefNum
     * @return int|false
     */
    private function get_order_id_from_refnum($RefNum)
    {
        global $wpdb;
        
        $order_id = $wpdb->get_var($wpdb->prepare(
            "SELECT post_id FROM {$wpdb->postmeta} 
            WHERE meta_key = '_transaction_id' AND meta_value = %s 
            LIMIT 1",
            $RefNum
        ));
        
        return $order_id ? intval($order_id) : false;
    }

    /**
     * Handle Sandbox payment simulation
     * 
     * @param int $order_id
     * @param int $amount
     * @return void
     */
    private function handle_sandbox_payment($order_id, $amount)
    {
        $order = new WC_Order($order_id);
        $CallbackUrl = add_query_arg('wc_order', $order_id, WC()->api_request_url('WC_Sep_Payment_Gateway'));
        
        // Generate a fake token for sandbox
        $sandbox_token = 'SANDBOX_' . time() . '_' . $order_id;
        
        // Save sandbox token to order meta
        update_post_meta($order_id, '_sep_sandbox_token', $sandbox_token);
        update_post_meta($order_id, '_sep_sandbox_amount', $amount);
        
        // Add note to order
        $order->add_order_note(__('تراکنش در حالت Sandbox (شبیه‌سازی) ایجاد شد.', 'sb24wc'), 0);
        
        // Display sandbox payment page
        $this->render_sandbox_payment_page($order_id, $sandbox_token, $amount, $CallbackUrl);
    }

    /**
     * Render Sandbox payment simulation page
     * 
     * @param int $order_id
     * @param string $token
     * @param int $amount
     * @param string $callback_url
     * @return void
     */
    private function render_sandbox_payment_page($order_id, $token, $amount, $callback_url)
    {
        $order = new WC_Order($order_id);
        $formatted_amount = number_format($amount / 10, 0) . ' تومان';
        
        ?>
        <!DOCTYPE html>
        <html <?php language_attributes(); ?> dir="rtl">
        <head>
            <meta charset="<?php bloginfo('charset'); ?>">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title><?php _e('صفحه پرداخت Sandbox - درگاه سپ', 'sb24wc'); ?></title>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                }
                body {
                    font-family: 'Vazir', 'Tahoma', 'Arial', sans-serif;
                    direction: rtl;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    min-height: 100vh;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 20px;
                }
                .sandbox-container {
                    background: #fff;
                    border-radius: 20px;
                    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                    max-width: 500px;
                    width: 100%;
                    padding: 40px;
                    text-align: center;
                }
                .sandbox-badge {
                    background: #ff9800;
                    color: #fff;
                    padding: 10px 20px;
                    border-radius: 25px;
                    display: inline-block;
                    margin-bottom: 20px;
                    font-weight: bold;
                    font-size: 14px;
                }
                .sandbox-title {
                    font-size: 24px;
                    color: #333;
                    margin-bottom: 30px;
                    font-weight: bold;
                }
                .sandbox-info {
                    background: #f5f5f5;
                    border-radius: 10px;
                    padding: 20px;
                    margin-bottom: 30px;
                }
                .sandbox-info-item {
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 15px;
                    padding-bottom: 15px;
                    border-bottom: 1px solid #ddd;
                }
                .sandbox-info-item:last-child {
                    border-bottom: none;
                    margin-bottom: 0;
                    padding-bottom: 0;
        }
                .sandbox-info-label {
                    color: #666;
                    font-weight: 500;
                }
                .sandbox-info-value {
                    color: #333;
                    font-weight: bold;
                }
                .sandbox-buttons {
                    display: flex;
                    gap: 15px;
                    margin-top: 30px;
                }
                .sandbox-btn {
                    flex: 1;
                    padding: 15px 30px;
                    border: none;
                    border-radius: 10px;
                    font-size: 16px;
                    font-weight: bold;
                    cursor: pointer;
                    transition: all 0.3s;
                    font-family: 'Vazir', 'Tahoma', 'Arial', sans-serif;
                }
                .sandbox-btn-success {
                    background: #4caf50;
                    color: #fff;
                }
                .sandbox-btn-success:hover {
                    background: #45a049;
                    transform: translateY(-2px);
                    box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
                }
                .sandbox-btn-failed {
                    background: #f44336;
                    color: #fff;
                }
                .sandbox-btn-failed:hover {
                    background: #da190b;
                    transform: translateY(-2px);
                    box-shadow: 0 5px 15px rgba(244, 67, 54, 0.4);
                }
                .sandbox-warning {
                    background: #fff3cd;
                    border: 1px solid #ffc107;
                    border-radius: 10px;
                    padding: 15px;
                    margin-top: 20px;
                    color: #856404;
                    font-size: 13px;
                    line-height: 1.6;
                }
            </style>
        </head>
        <body>
            <div class="sandbox-container">
                <div class="sandbox-badge">🔧 حالت Sandbox (شبیه‌سازی)</div>
                <h1 class="sandbox-title"><?php _e('صفحه پرداخت تست', 'sb24wc'); ?></h1>
                
                <div class="sandbox-info">
                    <div class="sandbox-info-item">
                        <span class="sandbox-info-label"><?php _e('شماره سفارش:', 'sb24wc'); ?></span>
                        <span class="sandbox-info-value">#<?php echo esc_html($order_id); ?></span>
                    </div>
                    <div class="sandbox-info-item">
                        <span class="sandbox-info-label"><?php _e('مبلغ:', 'sb24wc'); ?></span>
                        <span class="sandbox-info-value"><?php echo esc_html($formatted_amount); ?></span>
                    </div>
                    <div class="sandbox-info-item">
                        <span class="sandbox-info-label"><?php _e('توکن:', 'sb24wc'); ?></span>
                        <span class="sandbox-info-value" style="font-size: 12px;"><?php echo esc_html($token); ?></span>
                    </div>
                </div>

                <p style="color: #666; margin-bottom: 20px;">
                    <?php _e('برای تست تراکنش، یکی از دکمه‌های زیر را انتخاب کنید:', 'sb24wc'); ?>
                </p>

                <div class="sandbox-buttons">
                    <button class="sandbox-btn sandbox-btn-success" onclick="simulatePayment('success')">
                        <?php _e('✅ پرداخت موفق', 'sb24wc'); ?>
                    </button>
                    <button class="sandbox-btn sandbox-btn-failed" onclick="simulatePayment('failed')">
                        <?php _e('❌ پرداخت ناموفق', 'sb24wc'); ?>
                    </button>
                </div>

                <div class="sandbox-warning">
                    <strong>⚠️ توجه:</strong> <?php _e('این یک صفحه تست است. هیچ تراکنش واقعی انجام نمی‌شود. برای استفاده از درگاه واقعی، حالت Sandbox را غیرفعال کنید.', 'sb24wc'); ?>
                </div>
            </div>

            <script>
                function simulatePayment(status) {
                    const callbackUrl = '<?php echo esc_js($callback_url); ?>';
                    const orderId = <?php echo intval($order_id); ?>;
                    const token = '<?php echo esc_js($token); ?>';
                    
                    // Create form to submit to callback
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = callbackUrl;
                    
                    // Add fields
                    const stateField = document.createElement('input');
                    stateField.type = 'hidden';
                    stateField.name = 'State';
                    stateField.value = status === 'success' ? 'OK' : 'CanceledByUser';
                    form.appendChild(stateField);
                    
                    const resNumField = document.createElement('input');
                    resNumField.type = 'hidden';
                    resNumField.name = 'ResNum';
                    resNumField.value = orderId;
                    form.appendChild(resNumField);
                    
                    const refNumField = document.createElement('input');
                    refNumField.type = 'hidden';
                    refNumField.name = 'RefNum';
                    refNumField.value = status === 'success' ? 'SANDBOX_' + Date.now() : '';
                    form.appendChild(refNumField);
                    
                    document.body.appendChild(form);
                    form.submit();
                }
            </script>
        </body>
        </html>
        <?php
        exit;
    }

    /**
     * Handle Sandbox payment verification
     * 
     * @param int $order_id
     * @param string $State
     * @param string $ResNum
     * @param string $RefNum
     * @return void
     */
    private function handle_sandbox_verify($order_id, $State, $ResNum, $RefNum)
    {
        global $woocommerce;
        $order = new WC_Order($order_id);
        
        // Add note that this is sandbox transaction
        $order->add_order_note(__('تایید تراکنش در حالت Sandbox (شبیه‌سازی)', 'sb24wc'), 0);
        
        if ($order->get_status() != 'completed') {
            if ($State === 'OK' && !empty($RefNum)) {
                // Simulate successful payment
                $sandbox_refnum = !empty($RefNum) ? $RefNum : 'SANDBOX_' . time() . '_' . $order_id;
                
                update_post_meta($order_id, '_transaction_id', $sandbox_refnum);
                $order->payment_complete($sandbox_refnum);
                $woocommerce->cart->empty_cart();
                
                $Note = sprintf(
                    __('پرداخت با موفقیت انجام شد (Sandbox). کد پیگیری: %s', 'sb24wc'),
                    $sandbox_refnum
                );
                $order->add_order_note($Note, 1);
                
                $Notice = wpautop(wptexturize($this->success_massage));
                $Notice = str_replace("{transaction_id}", $sandbox_refnum, $Notice);
                $Notice .= '<br><strong style="color: #ff9800;">[' . __('حالت Sandbox', 'sb24wc') . ']</strong>';
                
                if ($Notice) {
                    wc_add_notice($Notice, 'success');
                }
                
                wp_redirect(add_query_arg('wc_status', 'success', $this->get_return_url($order)));
                exit;
            } else {
                // Simulate failed payment
                $Message = __('پرداخت توسط کاربر لغو شد (Sandbox)', 'sb24wc');
                $Note = sprintf('خطا در بازگشت از درگاه (Sandbox): %s', $Message);
                $order->add_order_note($Note, 1);
                
                $Notice = wpautop(wptexturize($this->failed_massage));
                $Notice = str_replace("{transaction_id}", $RefNum ?: '', $Notice);
                $Notice = str_replace("{fault}", $Message, $Notice);
                $Notice .= '<br><strong style="color: #ff9800;">[' . __('حالت Sandbox', 'sb24wc') . ']</strong>';
                
                if ($Notice) {
                    wc_add_notice($Notice, 'error');
                }
                
                wp_redirect(wc_get_checkout_url());
                exit;
            }
        } else {
            // Order already completed
            $Transaction_ID = get_post_meta($order_id, '_transaction_id', true);
            $Notice = wpautop(wptexturize($this->success_massage));
            $Notice = str_replace("{transaction_id}", $Transaction_ID, $Notice);
            $Notice .= '<br><strong style="color: #ff9800;">[' . __('حالت Sandbox', 'sb24wc') . ']</strong>';
            
            if ($Notice) {
                wc_add_notice($Notice, 'success');
            }
            wp_redirect(add_query_arg('wc_status', 'success', $this->get_return_url($order)));
            exit;
        }
    }

    /**
     * admin_options_woocommerce
     */
    public function admin_options()
    {
        // Show Sandbox warning if enabled
        if ($this->sandbox === 'yes') {
            echo '<div class="notice notice-warning" style="margin: 20px 0; padding: 15px; border-right: 4px solid #ff9800;">';
            echo '<p><strong>' . __('⚠️ حالت Sandbox فعال است', 'sb24wc') . '</strong></p>';
            echo '<p>' . __('در حال حاضر درگاه در حالت تست و شبیه‌سازی قرار دارد. هیچ تراکنش واقعی انجام نمی‌شود. برای استفاده از درگاه واقعی، لطفاً حالت Sandbox را غیرفعال کنید.', 'sb24wc') . '</p>';
            echo '</div>';
        }
        
        parent::admin_options();
    }

}
