<?php
if (!defined('ABSPATH')) {
    exit; 
}
use gateways\SMSIRGateway;
use gateways\IPPANELGateway;
use gateways\MELLIPAYAMAKGateway;
use gateways\KAVEHNEGARGateway;


class KavehInvoice {

    private $order;
    private $invoice_number;

    public $options;

    public function __construct($order_id = null) {
        $this->options = kaveh_get_options();
        if ($this->options['kaveh_factor_enable'] !== '1'){ 
            return;
            }else{
            $this->init();
            }
        if ($order_id) {
            $this->order = wc_get_order($order_id);
            $this->generate_invoice_number();
        }

    }

    

    public function init() {
        add_action('init', [$this, 'dequeue_assets_on_invoice_page'], 10);

        add_action('woocommerce_thankyou', [$this, 'add_download_invoice_link']);


        add_filter('woocommerce_my_account_my_orders_actions', [$this, 'add_invoice_download_button'], 10, 2);
        add_action('woocommerce_view_order', [$this, 'add_download_invoice_link_dash']);

        add_action('kaveh_delete_invoice_pdf', [$this, 'delete_invoice_pdf']);

        add_action('admin_init', [$this, 'handle_manual_delete_all_factors']);

        add_action('woocommerce_thankyou', [$this, 'redirect_to_invoice_on_complete']);
        add_action('woocommerce_order_status_completed', [$this, 'check_and_generate_invoice']);

        add_action('wp_ajax_kaveh_check_invoice_pdf', [$this, 'check_invoice_pdf']);
        add_action('wp_ajax_nopriv_kaveh_check_invoice_pdf', [$this, 'check_invoice_pdf']);

        add_action('wp_ajax_kaveh_save_invoice_pdf', [$this, 'save_invoice_pdf']);
        add_action('wp_ajax_nopriv_kaveh_save_invoice_pdf', [$this, 'save_invoice_pdf']);

        add_action('wp_ajax_kaveh_generate_invoice_html', [$this, 'generate_invoice_html']);
        add_action('wp_ajax_nopriv_kaveh_generate_invoice_html', [$this, 'generate_invoice_html']);


        add_action('wp_ajax_kaveh_send_invoice_email', [$this, 'send_invoice_email']);
        add_action('wp_ajax_nopriv_kaveh_send_invoice_email', [$this, 'send_invoice_email']);

        add_action('wp_ajax_kaveh_send_invoice_sms', [$this, 'send_invoice_sms']);
        add_action('wp_ajax_nopriv_kaveh_send_invoice_sms', [$this, 'send_invoice_sms']);

        if ($this->options['kaveh_sms_pre_invoice'] === '1'){ 
        add_action('wp_ajax_kaveh_create_guest_order', [$this, 'create_guest_order']);
        add_action('wp_ajax_nopriv_kaveh_create_guest_order', [$this, 'create_guest_order']);
        add_action('woocommerce_after_checkout_form', [$this, 'add_preview_invoice_link']);

        }

        if ($this->options['kaveh_sms_pre_invoice_link'] === '1'){ 
        add_action('wp_ajax_kaveh_send_payment_link', [$this, 'send_payment_link']);
        }

        add_action('init', [$this, 'handle_invoice_download']);
        add_action('init', [$this, 'handle_preview_invoice']);
        add_action('add_meta_boxes', [$this, 'add_invoice_metabox']);

        add_action('kaveh_delete_pending_guest_order', [$this, 'maybe_delete_pending_guest_order']);


        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);


    }

    private function generate_invoice_number() {
        $prefix = get_option('invoice_prefix', 'INV-');
        $this->invoice_number = $prefix . uniqid();
    }

    public function get_invoice_number() {
        return $this->invoice_number;
    }

    public function get_order() {
        return $this->order;
    }

    public function generate_html() {
        ob_start();
        include KAVEH_TEMPLATE_PATH . '/template-part/orders/factor/factor-one.php';
        return ob_get_clean();
    }
    
    
    public function redirect_to_invoice_on_complete($order_id) {
        $nonce = wp_create_nonce('kaveh_download_invoice');
        $sms_nonce = wp_create_nonce('kaveh_send_invoice_sms'); 
        $sms_nonce = htmlspecialchars_decode($sms_nonce);
    
        $email_nonce = wp_create_nonce('kaveh_send_invoice_email'); 
        $email_nonce = htmlspecialchars_decode($email_nonce);  
        
        $invoice_url = add_query_arg([
            'kaveh_download_invoice' => $order_id,
            '_wpnonce' => $nonce
        ], home_url());
    
        $invoice_url = htmlspecialchars_decode($invoice_url); 



        $pdf_url = get_post_meta($order_id, '_invoice_pdf_url', true);


        if ($pdf_url) {
            delete_post_meta($order_id, '_invoice_pdf_url');
        }
        ?>

        <script>
            document.addEventListener("DOMContentLoaded", function () {
                let invoiceUrl = <?php echo json_encode($invoice_url); ?>; 
                let invoiceWindow = window.open(invoiceUrl, "_blank");
                if (!invoiceWindow) {
                    alert("⚠️ <?php esc_html_e('Please enable pop-ups!', 'kavehTheme'); ?>");
                }
            });

        </script>
        <?php if ($this->options['kaveh_sms_thankyou_auto'] === '1'){ ?>
            <script>
            document.addEventListener("DOMContentLoaded", function () {

                setTimeout(function() {
                    if (typeof sendInvoiceSMS === "function") {
                        sendInvoiceSMS('<?php echo esc_js($order_id ?? ''); ?>', '<?php echo esc_js(wp_create_nonce('kaveh_send_invoice_sms')); ?>', null);
                    } else {
                        console.error("🚨 " + <?php echo json_encode(esc_html__('sendInvoiceSMS not defined yet!', 'kavehTheme')); ?>);
                    }
                }, 20000);
                

            });
        </script>
        <?php } ?>
        <?php if ($this->options['kaveh_email_thankyou_auto'] === '1'){ ?>

        <script>
            document.addEventListener("DOMContentLoaded", function () {
                setTimeout(function() {

                    if (typeof sendInvoiceEmail === "function") {
                        sendInvoiceEmail('<?php echo esc_js($order_id ?? ''); ?>', '<?php echo esc_js(wp_create_nonce('kaveh_send_invoice_email')); ?>', null);
                    } else {
                        console.error("🚨 " + <?php echo json_encode(esc_html__('sendInvoiceEmail not defined yet!', 'kavehTheme')); ?>);
                    }
                }, 20000);
            });
        </script>
        <?php } ?>

        <?php
    }

    public function add_invoice_download_button($actions, $order) {
        $order_id = $order->get_id();
    
        $download_url = wp_nonce_url(
            add_query_arg('kaveh_download_invoice', $order_id, home_url()), 
            'kaveh_download_invoice'
        );
    
        $actions['kaveh_invoice'] = [
            'url'  => $download_url,
            'name' => __('📄 ' . esc_html__('Download Invoice', 'kavehTheme'), 'kaveh-frame'),
            'class' => 'view kaveh-invoice-download'
        ];
    
        return $actions;
    }
public function add_download_invoice_link_dash($order_id) {
    if (!is_account_page()) return;

    $download_url = wp_nonce_url(
        add_query_arg('kaveh_download_invoice', $order_id, home_url()), 
        'kaveh_download_invoice'
    );

    echo '<p><a href="' . esc_url($download_url) . '" class="button alt">📄 ' . esc_html__('Download Invoice', 'kavehTheme') . '</a></p>';
}
    


    public function check_and_generate_invoice($order_id) {
        $upload_dir = wp_upload_dir();
        $pdf_path = $upload_dir['basedir'] . "/factor/invoice_{$order_id}.pdf";
    
        if (!file_exists($pdf_path)) {
            add_action('wp_footer', function () use ($order_id) {
                $nonce = wp_create_nonce('kaveh_download_invoice');
    
                $invoice_url = add_query_arg([
                    'kaveh_download_invoice' => $order_id,
                    '_wpnonce' => $nonce
                ], home_url());
                $invoice_url = htmlspecialchars_decode($invoice_url); 
    
                ?>
                <script>
                    document.addEventListener("DOMContentLoaded", function () {
                        let invoiceUrl = <?php echo json_encode($invoice_url); ?>; 
                        let invoiceWindow = window.open(invoiceUrl, "_blank");
                        if (!invoiceWindow) {
                            alert("⚠️ <?php esc_html_e('Please enable pop-ups!', 'kavehTheme'); ?>");
                        }

                    });
                </script>
                <?php
            });
        }
    }
    

    public function generate_invoice_html() {
        if (!isset($_POST['order_id']) || !isset($_POST['_wpnonce'])) {
            wp_send_json_error(['message' => '❌ ' . esc_html__('Invalid request.', 'kavehTheme')]);
        }
    
        if (!wp_verify_nonce($_POST['_wpnonce'], 'kaveh_download_invoice')) {
            wp_send_json_error(['message' => '🚫 ' . esc_html__('Security error: Invalid nonce.', 'kavehTheme')]);
        }
    
        ob_start();
        do_action('kaveh_download_invoice');
        $html = ob_get_clean();
    
        if (empty($html)) {
            wp_send_json_error(['message' => '⚠️ ' . esc_html__('Error: Invoice HTML is empty!', 'kavehTheme')]);
        }
    
        wp_send_json_success(['html' => $html]);
    }
    
    

    public function save_invoice_pdf() {
        if (!isset($_POST['order_id']) || !isset($_POST['_wpnonce']) || !isset($_POST['pdf_data'])) {
            wp_send_json_error(['message' => '❌ ' . esc_html__('Invalid request.', 'kavehTheme')]);
        }
    
        $order_id = intval($_POST['order_id']);
    
        if (!wp_verify_nonce($_POST['_wpnonce'], 'kaveh_download_invoice')) {
            wp_send_json_error(['message' => '🚫 ' . esc_html__('Security error: Invalid nonce.', 'kavehTheme')]);
        }
    
        $upload_dir = wp_upload_dir();
        $factor_dir = $upload_dir['basedir'] . "/factor";
        if (!file_exists($factor_dir)) {
            mkdir($factor_dir, 0755, true);
        }
    
        $pdf_path = $factor_dir . "/invoice_{$order_id}.pdf";
        $pdf_url = $upload_dir['baseurl'] . "/factor/invoice_{$order_id}.pdf";
    
        $decoded_pdf = base64_decode($_POST['pdf_data']);
    
        if (!$decoded_pdf || empty($decoded_pdf)) {
            wp_send_json_error(['message' => '🚨 ' . esc_html__('Error: Invalid PDF data!', 'kavehTheme')]);
        }
    
        if (!file_put_contents($pdf_path, $decoded_pdf)) {
            wp_send_json_error(['message' => '🚨 ' . esc_html__('Error saving PDF on server!', 'kavehTheme')]);
        }
    
        update_post_meta($order_id, '_invoice_pdf_url', $pdf_url);
    
        $deletefactortime = intval($this->options['kaveh_delete_invoice_payment'] ?? 240);
        if (function_exists('as_schedule_single_action')) {
            $timestamp = time() + ($deletefactortime * HOUR_IN_SECONDS);
            as_schedule_single_action($timestamp, 'kaveh_delete_invoice_pdf', [$order_id]);
        }
    
        wp_send_json_success(['pdf_url' => $pdf_url]);
    }
    public function delete_invoice_pdf($order_id) {
        $upload_dir = wp_upload_dir();
        $pdf_path = $upload_dir['basedir'] . "/factor/invoice_{$order_id}.pdf";
    
        if (file_exists($pdf_path)) {
            unlink($pdf_path); 
            delete_post_meta($order_id, '_invoice_pdf_url'); 
        } else {
        }
    }
    
    
    
    public function check_invoice_pdf() {
        if (!isset($_POST['order_id']) || !isset($_POST['_wpnonce'])) {
            wp_send_json_error(['message' => '❌ ' . esc_html__('Invalid request.', 'kavehTheme')]);
        }
    
        if (!wp_verify_nonce($_POST['_wpnonce'], 'kaveh_download_invoice')) {
            wp_send_json_error(['message' => '🚫 نانس نامعتبر است!']);
        }
    
        $order_id = intval($_POST['order_id']);
        $pdf_url = get_post_meta($order_id, '_invoice_pdf_url', true);
    
        $upload_dir = wp_upload_dir();
        $pdf_path = $upload_dir['basedir'] . "/factor/invoice_{$order_id}.pdf";
    
        if ($pdf_url && file_exists($pdf_path)) {
            wp_send_json_success(['pdf_url' => $pdf_url]);
        } else {
            delete_post_meta($order_id, '_invoice_pdf_url'); 
            wp_send_json_error(['message' => '🚫 ' . esc_html__('PDF not found! Needs to be recreated.', 'kavehTheme')]);
        }
    }
    



    public function add_download_invoice_link($order_id) {
        $download_url = wp_nonce_url(
            add_query_arg('kaveh_download_invoice', $order_id, home_url()), 
            'kaveh_download_invoice'
        );
        echo '<a href="' . esc_url($download_url) . '" class="button">' . esc_html__('Download Invoice', 'kavehTheme') . '</a>';
    }
    

    public function handle_invoice_download() {
        if (isset($_GET['kaveh_download_invoice']) && isset($_GET['_wpnonce'])) {
            if (!wp_verify_nonce($_GET['_wpnonce'], 'kaveh_download_invoice')) {
                wp_die(esc_html__('Invalid download link.', 'kavehTheme'));
            }
    
            $order_id = intval($_GET['kaveh_download_invoice']);
            if (!$order_id) {
                wp_die(esc_html__('Order not found.', 'kavehTheme'));
            }
    
            $invoice = new self($order_id);
            $html = $invoice->generate_html();


            echo $html;
            exit;
        }
    }
    

    public function add_preview_invoice_link() {
        if (WC()->cart->get_cart_contents_count() > 0) {
            $preinvoicebutton = $this->options['kaveh_preinvoice_button_text'];
            $preinvoicehelp = $this->options['kaveh_preinvoice_help_text'];

            ?>
            <button id="preview-invoice-btn" class="button"><?php echo $preinvoicebutton; ?></button>
            <span><?php echo $preinvoicehelp; ?></span>
            <?php
        }
    }
    
    public function create_guest_order() {
        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'kaveh_create_guest_order')) {
            wp_send_json_error(['message' => '🚫 نانس نامعتبر است!']);
        }
    
        if (WC()->cart->is_empty()) {
            wp_send_json_error(['message' => '❌ ' . esc_html__('Your cart is empty!', 'kavehTheme')]);
        }
    
        $order = wc_create_order();
        foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
            $order->add_product(
                wc_get_product($cart_item['product_id']),
                $cart_item['quantity']
            );
        }
    
        $order->set_status('pending');
        $user_id = false;
        $phone = $_POST['billing_phone'];
        $numberWithoutFirstZero = ltrim( $phone, '0');
        global $wpdb;
        $query = $wpdb->prepare(
            "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'billing_phone' AND meta_value = %s
            UNION
            SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'digits_phone_no' AND meta_value = %s",
            $phone,
            $numberWithoutFirstZero
        );
        $user_ids = $wpdb->get_col($query);
        if (!empty($user_ids)) {
            $user_id = $user_ids[0];
        }
        if($user_id){
            $order->set_customer_id($user_id); 
        }
        else{
            $order->set_customer_id(0); 
        }
        $order->set_billing_first_name($_POST['billing_first_name'] ?? esc_html__('Guest', 'kavehTheme'));
        $order->set_billing_last_name($_POST['billing_last_name'] ?? '');
        $order->set_billing_email($_POST['billing_email'] ?? 'guest@example.com');
        $order->set_billing_phone($_POST['billing_phone'] ?? '');
        $order->set_billing_address_1($_POST['billing_address_1'] ?? '');
        $order->set_billing_city($_POST['billing_city'] ?? '');
        $order->set_billing_postcode($_POST['billing_postcode'] ?? '');
        $order->calculate_totals();
        $order->save();
        $expirepreordertime = $this->options['kaveh_expired_preinvoice_payment'];
        $smsPanel = $this->options['kaveh_sms_gateway'];
        $expire_hours = intval( $expirepreordertime); 
        $timestamp = time() + ($expire_hours * HOUR_IN_SECONDS);


        if (function_exists('as_schedule_single_action')) {
            as_schedule_single_action($timestamp, 'kaveh_delete_pending_guest_order', [$order->get_id()]);
        }

        
        $nonce = wp_create_nonce('kaveh_create_guest_order');
    
        $preview_url = add_query_arg([
            'kaveh_create_guest_order' => $order->get_id(),
            '_wpnonce' => $nonce
        ], home_url()); 
    
        wp_send_json_success([
            'order_id' => $order->get_id(),
            'nonce' => $nonce,
            'preview_url' => $preview_url 
        ]);
    }
    
    public function handle_preview_invoice() {
        if (
            isset($_GET['kaveh_create_guest_order']) &&
            isset($_GET['_wpnonce']) &&
            wp_verify_nonce($_GET['_wpnonce'], 'kaveh_create_guest_order')
        ) {
            $order_id = intval($_GET['kaveh_create_guest_order']);
            $order = wc_get_order($order_id);
    
            if (!$order) {
                wp_die('🚨 ' . esc_html__('Order not found!', 'kavehTheme'));
            }
    
            $invoice = new self($order->get_id());
            header('Content-Type: text/html; charset=utf-8');
            echo $invoice->generate_html();
            exit;
        }
    }
    
    

    public function maybe_delete_pending_guest_order($order_id) { 
        $order = wc_get_order($order_id); if (!$order) return;
        if ($order->get_status() === 'pending' && $order->get_customer_id() == 0) {
            wp_delete_post($order_id, true);
        }
    }        
    
    

    public function add_invoice_metabox() {
        add_meta_box(
            'order_invoice_metabox',
            esc_html__('Download and Send Invoice', 'kavehTheme'),
            [$this, 'render_invoice_metabox_content'],
            'shop_order',
            'side',
            'high'
        );
    }

    public function render_invoice_metabox_content($post) {
        $order_id = $post->ID;
        $order = wc_get_order($order_id);
        $order_status = $order->get_status();
    
        $download_url = wp_nonce_url(
            add_query_arg('kaveh_download_invoice', $order_id, home_url()), 
            'kaveh_download_invoice'
        );
    
        $nonce = wp_create_nonce('kaveh_download_invoice');
        $noncerwo = wp_create_nonce('kaveh_send_invoice_sms');
        $noncethree = wp_create_nonce('kaveh_send_invoice_email');

        if ($this->options['kaveh_sms_pre_invoice_link'] === '1'){ 
        $nonce_payment = wp_create_nonce('kaveh_send_payment_link');
        }

        echo '<div style="text-align: center;">';
        echo '<a href="' . esc_url($download_url) . '" target="_blank" class="button button-primary" style="width: 100%; margin-bottom: 10px;">📄 ' . esc_html__('Download Invoice', 'kavehTheme') . '</a>';
        
        echo '<button class="button button-secondary send-invoice-email" 
                data-order-id="' . esc_attr($order_id) . '" 
                data-nonce="' . esc_attr($noncethree) . '" 
                style="width: 100%; margin-bottom: 10px;">
                📧 '. esc_html_e('Send Invoice to Email', 'kavehTheme') .'
              </button>';
    
        echo '<button class="button button-secondary send-invoice-sms" 
              data-order-id="' . esc_attr($order_id) . '" 
              data-nonce="' . esc_attr($noncerwo) . '" 
              style="width: 100%; margin-bottom: 10px;">
              📲 '.esc_html_e('Send Invoice via SMS', 'kavehTheme') .'
          </button>';
    
        if ($this->options['kaveh_sms_pre_invoice_link'] === '1'){ 

        if ($order_status === 'pending') {
            echo '<button class="button button-primary send-payment-link" 
                    data-order-id="' . esc_attr($order_id) . '" 
                    data-nonce="' . esc_attr($nonce_payment) . '" 
                    style="width: 100%;">
                    💳 '. esc_html_e('Send Payment Link to Customer', 'kavehTheme') .'
                  </button>';
        }
    }
    
        echo '</div>';
    }
    


    public function send_invoice_email() {
        if (!isset($_POST['order_id']) || !isset($_POST['_wpnonce'])) {
            wp_send_json_error(['message' => '❌ ' . esc_html__('Invalid request.', 'kavehTheme')]);
        }
    
        if (!wp_verify_nonce($_POST['_wpnonce'], 'kaveh_send_invoice_email')) {
            wp_send_json_error(['message' => '🚫 نانس نامعتبر است!']);
        }
    
        $order_id = intval($_POST['order_id']);
        $order = wc_get_order($order_id);
        if (!$order) {
            wp_send_json_error(['message' => '🚫 سفارش یافت نشد.']);
        }
    
        $pdf_url = get_post_meta($order_id, '_invoice_pdf_url', true);
        $upload_dir = wp_upload_dir();
        $pdf_path = $upload_dir['basedir'] . "/factor/invoice_{$order_id}.pdf";    

        if (!$pdf_url || !file_exists($pdf_path)) {
            $nonce = wp_create_nonce('kaveh_download_invoice');
            $invoice_url = add_query_arg([
                'kaveh_download_invoice' => $order_id,
                '_wpnonce' => $nonce
            ], home_url());
    
            wp_send_json_error(['open_invoice' => $invoice_url, 'message' => '🚨 فاکتور یافت نشد، لطفاً صفحه را باز کنید!']);
        }
    
        $customer_email = $order->get_billing_email();
        $subject = esc_html__('Your Order Invoice', 'kavehTheme');
        $emailpara = $this->options['kaveh_email_thankyou_pattern'];
        $message = esc_html($emailpara) . ' ' . esc_url($pdf_url);
    
        wp_mail($customer_email, $subject, $message);
    
        wp_send_json_success(['message' => '📧 ' . esc_html__('Email sent successfully!', 'kavehTheme')]);
    }
    
    public function send_invoice_sms() {
    
        if (!isset($_POST['order_id']) || !isset($_POST['_wpnonce'])) {
            wp_send_json_error(['message' => '❌ ' . esc_html__('Invalid request.', 'kavehTheme')]);
        }
    
        if (!wp_verify_nonce($_POST['_wpnonce'], 'kaveh_send_invoice_sms')) {
            wp_send_json_error(['message' => '🚫 نانس نامعتبر است!']);
        }
    
        $order_id = intval($_POST['order_id']);
    
        $order = wc_get_order($order_id);
        if (!$order) {
            wp_send_json_error(['message' => '🚫 سفارش یافت نشد.']);
        }
    
        $pdf_url = get_post_meta($order_id, '_invoice_pdf_url', true);
        $upload_dir = wp_upload_dir();
        $pdf_path = $upload_dir['basedir'] . "/factor/invoice_{$order_id}.pdf";
    
        if (!$pdf_url || !file_exists($pdf_path)) {
            $nonce = wp_create_nonce('kaveh_download_invoice');
            $invoice_url = add_query_arg([
                'kaveh_download_invoice' => $order_id,
                '_wpnonce' => $nonce
            ], home_url());
    
            wp_send_json_error(['open_invoice' => $invoice_url, 'message' => '🚨 فاکتور یافت نشد، لطفاً صفحه را باز کنید!']);
        }
    
    
        $customer_phone = $order->get_billing_phone();
        if (!$customer_phone) {
            wp_send_json_error(['message' => '🚨 ' . esc_html__('Error: Customer mobile number not found!', 'kavehTheme')]);
        }
    
        if (!isset($this->options['kaveh_sms_gateway']) || empty($this->options['kaveh_sms_gateway'])) {
            wp_send_json_error(['message' => '🚨 خطا: درگاه پیامک تنظیم نشده است!']);
        }
        $pdf_url = preg_replace("(^https?://)", "", $pdf_url);

        $smsPanel = $this->options['kaveh_sms_gateway'];
        $username = $this->options['kaveh_username_sms'];
        $password = $this->options['kaveh_password_sms'];
        $apiKey = $this->options['kaveh_password_api'];
        $from = $this->options['kaveh_number_sms'];
        $pattern = $this->options['kaveh_sms_thankyou_pattern'];   
    
        try {
            $result = false;
        
            switch ($smsPanel) {
                case 'option-2':
                    $input_data = ["pdf_url" => $pdf_url];
                    $result = SMSIRGateway::sendSMS($apiKey, $customer_phone, $pattern, $input_data);
                    break;
        
                case 'option-1':
                    $input_data = ["pdf_url" =>  $pdf_url];
                    $result = IPPANELGateway::sendSMS($from, $customer_phone, $username, $password, $pattern, $input_data);
                    break;
        
                case 'option-3':
                    $input_data = "pdf_url=" . $pdf_url . ";";
                    $result = MELLIPAYAMAKGateway::sendSMS($username, $password, $customer_phone, $pattern, $input_data);
                    break;
        
                case 'option-4':
                    $input_data = [$pdf_url];
                    $result = KAVEHNEGARGateway::sendSMS($apiKey, $customer_phone, $pattern, $input_data);
                    break;
        
                default:
                    wp_send_json_error(['message' => '🚨 گزینه‌ی نامعتبر برای درگاه پیامک انتخاب شده است!']);
            }
        
            $result = json_decode($result);
            if ($result !== false) {
                wp_send_json_success([
                    'message' => '📲 پیامک با موفقیت ارسال شد!',
                    'server_response' => $result['response']
                ]);
            } else {
                wp_send_json_error([
                    'message' => '🚨 خطا در ارسال پیامک: پاسخ نامعتبر از سرور',
                    'server_response' => $result
                ]);
            }
        
        } catch (Exception $e) {
            wp_send_json_error([
                'message' => '🚨 خطای داخلی هنگام ارسال پیامک!',
                'error_detail' => $e->getMessage()
            ]);
        }
        
    }
    
    

    public function send_payment_link() {
        if (!isset($_POST['order_id']) || !isset($_POST['_wpnonce'])) {
            wp_send_json_error(['message' => '❌ ' . esc_html__('Invalid request.', 'kavehTheme')]);
        }
    

    
        $order_id = intval($_POST['order_id']);
        $order = wc_get_order($order_id);
        if (!$order) {
            wp_send_json_error(['message' => '🚨 ' . esc_html__('Order not found!', 'kavehTheme')]);
        }
    
        if ($order->get_status() !== 'pending') {
            wp_send_json_error(['message' => '⚠️ ' . esc_html__('Only pending payment orders are allowed to send links.', 'kavehTheme')]);
        }
    
        $payment_url = htmlspecialchars_decode($order->get_checkout_payment_url());
    
        $customer_email = $order->get_billing_email();
        $customer_phone = $order->get_billing_phone();
        $subject = esc_html__('Your Order Payment Link', 'kavehTheme');
        $emailparapay = $this->options['kaveh_email_prepayment_pattern'];
        $message = esc_html($emailparapay) . ' ' . esc_url($payment_url);
        wp_mail($customer_email, $subject, $message);
    
        $this->options = kaveh_get_options();  
        if (!isset($this->options['kaveh_sms_gateway']) || empty($this->options['kaveh_sms_gateway'])) {
            wp_send_json_error(['message' => '🚨 خطا: درگاه پیامک تنظیم نشده است!']);
        }
    
        $smsPanel = $this->options['kaveh_sms_gateway'];
        $username = $this->options['kaveh_username_sms'];
        $password = $this->options['kaveh_password_sms'];
        $apiKey = $this->options['kaveh_password_api'];
        $from = $this->options['kaveh_number_sms'];
        $pattern = $this->options['kaveh_sms_preinvoice_pattern'];   
    
        try {
            $result = false;
        
            switch ($smsPanel) {
                case 'option-2':
                    $input_data = ["payment_url" => $payment_url];
                    $result = SMSIRGateway::sendSMS($apiKey, $customer_phone, $pattern, $input_data);
                    break;
        
                case 'option-1':
                    $input_data = ["payment_url" =>  $payment_url];
                    $result = IPPANELGateway::sendSMS($from, $customer_phone, $username, $password, $pattern, $input_data);
                    break;
        
                case 'option-3':
                    $input_data = "payment_url=" . $payment_url . ";";
                    $result = MELLIPAYAMAKGateway::sendSMS($username, $password, $customer_phone, $pattern, $input_data);
                    break;
        
                case 'option-4':
                    $input_data = [$payment_url];
                    $result = KAVEHNEGARGateway::sendSMS($apiKey, $customer_phone, $pattern, $input_data);
                    break;
        
                default:
                    wp_send_json_error(['message' => '🚨 گزینه‌ی نامعتبر برای درگاه پیامک انتخاب شده است!']);
            }
        
            $result = json_decode($result);
            if ($result !== false) {
                wp_send_json_success([
                    'message' => '📲 پیامک با موفقیت ارسال شد!',
                    'server_response' => $result['response']
                ]);
            } else {
                wp_send_json_error([
                    'message' => '🚨 خطا در ارسال پیامک: پاسخ نامعتبر از سرور',
                    'server_response' => $result
                ]);
            }
        
        } catch (Exception $e) {
            wp_send_json_error([
                'message' => '🚨 خطای داخلی هنگام ارسال پیامک!',
                'error_detail' => $e->getMessage()
            ]);
        }
    }


    
    public function enqueue_scripts($hook = '') {
        $is_admin = is_admin();
    
        if (!$is_admin) {
            wp_enqueue_script('html2canvas', KAVEH_TEMPLATE_URI . '/assets/js/lib/html2canvas.min.js', [], null, true);
            wp_enqueue_script('jspdf', KAVEH_TEMPLATE_URI . '/assets/js/lib/jspdf.umd.min.js', [], null, true);
            wp_enqueue_script('kaveh-invoice', KAVEH_TEMPLATE_URI . '/assets/js/kaveh-invoice.js', ['jquery', 'html2canvas', 'jspdf'], null, true);
    
            wp_localize_script('kaveh-invoice', 'kavehInvoiceData', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce_download' => wp_create_nonce('kaveh_download_invoice'), 
                'pre_invoice' => wp_create_nonce('kaveh_create_guest_order'), 
            ]);
        }
    
        if ($is_admin && isset($_GET['post']) && isset($_GET['action']) && $_GET['action'] === 'edit') {
            $post_id = intval($_GET['post']);
            if (get_post_type($post_id) === 'shop_order') {
                wp_enqueue_script('html2canvas', KAVEH_TEMPLATE_URI . '/assets/js/lib/html2canvas.min.js', [], null, true);
                wp_enqueue_script('jspdf', KAVEH_TEMPLATE_URI . '/assets/js/lib/jspdf.umd.min.js', [], null, true);
                wp_enqueue_script('kaveh-invoice-admin', KAVEH_TEMPLATE_URI . '/assets/js/kaveh-invoice.js', ['jquery', 'html2canvas', 'jspdf'], null, true);
    
                wp_localize_script('kaveh-invoice-admin', 'kavehInvoiceData', [
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce_download' => wp_create_nonce('kaveh_download_invoice'), 
                    'pre_invoice' => wp_create_nonce('kaveh_create_guest_order'), 


                ]);
    
            }
        }
    }





    public function handle_manual_delete_all_factors() {
        if (
            isset($_POST['delete_all_factors']) &&
            isset($_POST['kaveh_delete_all_factors_nonce']) &&
            wp_verify_nonce($_POST['kaveh_delete_all_factors_nonce'], 'kaveh_delete_all_factors_action')
        ) {
            $upload_dir = wp_upload_dir();
            $factor_dir = $upload_dir['basedir'] . '/factor';
    
            if (file_exists($factor_dir) && is_dir($factor_dir)) {
                $files = glob($factor_dir . '/*.pdf');
    
                foreach ($files as $file) {
                    if (is_file($file)) {
                        unlink($file);
                    }
                }
    
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-success is-dismissible"><p>✅ ' . esc_html__('All invoices deleted.', 'kavehTheme') . '</p></div>';
                });
            } else {
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-warning is-dismissible"><p>⚠️ ' . esc_html__('Invoice folder not found or was empty.', 'kavehTheme') . '</p></div>';
                });
            }
        }
    }


    public function dequeue_assets_on_invoice_page() {
        if (!isset($_GET['kaveh_download_invoice'])) return;
    
        // حذف CSS
        add_action('wp_enqueue_scripts', function () {
            $styles = [ 
                'woocommerce-layout-rtl',
                'woocommerce-smallscreen-rtl',
                'woocommerce-general-rtl',
                'elementor-frontend',
                'elementor-wp-admin-bar',
                'elementor-post-98',
                'elementor-post-4244',
                'elementor-post-3459',
                'boostify-sticky-style',
                'wp-mail-smtp-admin-bar',
                'hint',
                'perfect-scrollbar',
                'perfect-scrollbar-wpc',
                'woosc-icons',
                'woosc-frontend',
                'woosw-icons',
                'woosw-frontend',
                'wpcvs-frontend',
                'swiper-bundle.min',
                'nouislider.min',
                'select2.min',
                'notiflix',
                'icomoon',
                'iconsax',
                'iconly',
                'single-product-page-one',
                'single-product-page-two',
                'single-product-page-three',
                'single-product-page-four',
                'panel-one-style',
                'kaveh',
                'ag-theme-builder',
                'dynamic-css',
                'fontawesome-5-free',
                'boostify-hf-nav-menu-css',
                'boostify-hf-search',
                'boostify-hf-style',
                'boostify-hf-cart-icon',
                'ionicons',
                'fontawesome',
            ];
    
            foreach ($styles as $style) {
                if (wp_style_is($style, 'enqueued')) {
                    wp_dequeue_style($style);
                    wp_deregister_style($style);
                }
            }
        }, 100);
    
        // حذف JS
        add_action('wp_print_scripts', function () {
            $scripts = [
                'print-js',
                'table-head-fixer-js',
                'perfect-scrollbar-js',
                'jquery-ui-core',
                'jquery-ui-mouse',
                'jquery-ui-sortable',
                'woosc-frontend-js',
                'woosw-frontend-js',
                'wpcvs-frontend-js',
                'swiper-bundle.min-js',
                'nouislider.min-js',
                'main-js',
                'notiflix-js',
                'select2.min-js',
                'kaveh-ajax-method-js',
                'html2canvas-js',
                'jspdf-js',
                'kaveh-invoice-js',
                'ag-theme-builder-js',
                'sourcebuster-js-js',
                'wc-order-attribution-js',
            ];
    
            foreach ($scripts as $script) {
                if (wp_script_is($script, 'enqueued')) {
                    wp_dequeue_script($script);
                    wp_deregister_script($script);
                }
            }
        }, 100);
    }
    
    
    
    
}

