<?php

class NBSmartInvoiceBackend{
    
    private $_menu_slug = 'nb-smart-invoice-create-pages';
    private $template_setting_option;
    private $_NBCreatePDF;
    private $_nd_invoice_license_key="";
    public function __construct()
    {
        $this->_NBCreatePDF = new NBCreatePDF();
        $this->admin_hook();
        $this->template_setting_option = get_option( 'nd_invoice_template_settings', array() );
        $this->_nd_invoice_license_key = get_option( 'nd_invoice_license_key');
    }
    public function admin_hook(){
        add_action('admin_enqueue_scripts', array($this, 'admin_style'), 10, 1);
        add_action('admin_menu', array($this, 'nbinvoice_menu'));
        add_action( 'add_meta_boxes', array($this, 'invoice_add_meta_box_order_detail') );
        add_filter( 'woocommerce_email_attachments',array($this, 'nb_invoice_woocommerce_email_attachments'), 1000, 3);
        add_action( 'wp_ajax_downloadInvoicePDF', array($this, 'invoice_manage_invoices') );
        add_action( 'admin_footer', array($this, 'add_loadding') );
    }
    function add_loadding( $data ){
        echo '<div style="display:none;" id="nb_loadding_license"><img src="' . NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/images/load.svg' .'"/></div>';
    }
    function admin_style($hook) {
        if (strlen(strstr($hook, 'nb-smart-invoice-create-pages')) > 0 
            || strlen(strstr($hook, 'nb-smart-invoice-listing-pages')) > 0
            || strlen(strstr($hook, 'nb-smart-pdf-template-import')) > 0
            || strlen(strstr($hook, 'nb-smart-delivery-listing-pages')) > 0){
            wp_enqueue_style('bootstrap', NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/lib/bootstrap/css/bootstrap.min.css');
            wp_enqueue_script('angular', NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/lib/angular/angular.min.js');
            wp_enqueue_script('jquery', NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/lib/jquery/jquery-3.4.1.min.js');
            wp_enqueue_script('bootstrap', NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/lib/bootstrap/js/bootstrap.min.js');
            wp_enqueue_script('jscolor', NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/lib/color/jscolor.js');
        }
        wp_enqueue_style('nb-backend-list-css', NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/css/nb_backend.css');
        if(isset($_GET['tab'])){
            if($_GET['tab'] == 'nb-invoice-setting-tab6'){
                wp_enqueue_style('bootstrap', NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/lib/bootstrap/css/bootstrap.min.css');
                wp_enqueue_style('nb-template-review-css', NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/css/template_review.css');
            }
        }
        wp_enqueue_script('nb-invoice_admin_script', NETBASE_SMART_INVOICE_PLUGIN_URL . '/assets/js/main.js', array('jquery'), '1.0.4', true);
    }
    public function nbinvoice_menu(){

        add_menu_page(
                        $page_title = 'NBSmart Invoice Settings',
                        $menu_title ='NBInvoice',
                        $capability ='manage_options',
                        $menu_slug = $this->_menu_slug,
                        $function = array($this, 'ndSmartInvoiceCreatePage'),NETBASE_SMART_INVOICE_PLUGIN_URL . 'assets/images/logo-icon-r.svg', 28);
        add_submenu_page( 
                        $this->_menu_slug,
                        'Create New Invoice Template', 
                        'New Template', 
                        'manage_options', 
                        $this->_menu_slug,
                        array($this, 'ndSmartInvoiceCreatePage'));
        add_submenu_page( 
                        $this->_menu_slug,
                        'NB Invoice Templates', 
                        'Invoice', 
                        'manage_options', 
                        'nb-smart-invoice-listing-pages',
                        array($this, 'ndSmartInvoiceListingPage'));
        add_submenu_page( 
                        $this->_menu_slug,
                        'NB Delivery Templates', 
                        'Delivery', 
                        'manage_options', 
                        'nb-smart-delivery-listing-pages',
                        array($this, 'ndSmartDeliveryListingPage'));
        // add_submenu_page( 
        //                 $this->_menu_slug,
        //                 'NB Templates Import Layout', 
        //                 'Import Layout', 
        //                 'manage_options', 
        //                 'nb-smart-pdf-template-import',
        //                 array($this, 'nbInvoiceTemplateImport'));
        add_submenu_page(
                            $this->_menu_slug, 'NBSmart Invoice Settings', 'Settings', 'manage_options', 'nb-smart-invoice-setting-pages', array($this, 'ndSmartInvoiceSettingPage')
                        );
    }
    public function nbInvoiceTemplateImport(){
        if(isset($_POST["license_key"]) && $_POST["license_key"] != ''){
            $page = "nb-smart-pdf-template-import";
            if($this->_nd_invoice_license_key != ""){
                update_option( 'nd_invoice_license_key', trim($_POST["license_key"]) );
            } else {
                add_option( 'nd_invoice_license_key', trim($_POST["license_key"]) );
            }
        }
        if(isset($_POST["data_import"])){
            global $wpdb;
            $data_insert = array(
                'name_template' 		=> (string)$_POST['name_template'],
                'template_landscape' 			=> (int)$_POST['template_landscape'],
                'template_invoice_header' 		=> ((string)$_POST['template_invoice_header']),
                'template_invoice_content' 		=> ((string)$_POST['template_invoice_content']),
                'template_invoice_footer' 		=> ((string)$_POST['template_invoice_footer']),
                'template_custom_css' => (string)$_POST['template_custom_css'],
                'columns_number' 		=> (int)$_POST['columns_number'],
                'item_title_json' 		=> (string) stripcslashes($_POST['item_title']),
                'item_key_value_json' 	=>  (string) stripcslashes($_POST['item_key_value']),
                'item_title_color_json' 	 => (string) stripcslashes($_POST['item_title_color']) ,
                'item_title_background_Json' 	=> (string) stripcslashes($_POST['item_title_background']) ,
                'public' 		=> (int)$_POST['public'] ,
                'type' 					=> (string)$_POST['type_template'],
            );
            $wpdb->insert("{$wpdb->prefix}netbase_invoice_templates", $data_insert );
        }
        // $nbinvoice_import_tabs = array(
        //     'nb-invoice-import-allLayout' => 'All Template'
        // );
        // echo $this->netbase_invoice_template_import_tabs($nbinvoice_import_tabs);
    }
    public function ndSmartInvoiceSettingPage(){
        $this->nbInvoiceTemplateImport();
        if($_POST){
            $data_update = $this->template_setting_option;
            if(isset($_POST["debug"])){
                if(isset($_POST["debug"]["pdf_template_debug"])){
                    $data_update["pdf_template_debug"] = $_POST["debug"]["pdf_template_debug"];
                } else {
                    $data_update["pdf_template_debug"] = 0;
                }
                update_option( 'nd_invoice_template_settings', $data_update );
            }
            // Invoice For Order
            if(isset($_POST["invoice_order"])){
                if(isset($_POST["invoice_order"]["nb_order_status_wc-pending"])){
                    $data_update["nb_order_status_wc-pending"] = $_POST["invoice_order"]["nb_order_status_wc-pending"];
                } else {
                    $data_update["nb_order_status_wc-pending"] = 0;
                }
                if(isset($_POST["invoice_order"]["nb_order_status_wc-processing"])){
                    $data_update["nb_order_status_wc-processing"] = $_POST["invoice_order"]["nb_order_status_wc-processing"];
                } else {
                    $data_update["nb_order_status_wc-processing"] = 0;
                }
                if(isset($_POST["invoice_order"]["nb_order_status_wc-on-hold"])){
                    $data_update["nb_order_status_wc-on-hold"] = $_POST["invoice_order"]["nb_order_status_wc-on-hold"];
                } else {
                    $data_update["nb_order_status_wc-on-hold"] = 0;
                }
                if(isset($_POST["invoice_order"]["nb_order_status_wc-completed"])){
                    $data_update["nb_order_status_wc-completed"] = $_POST["invoice_order"]["nb_order_status_wc-completed"];
                } else {
                    $data_update["nb_order_status_wc-completed"] = 0;
                }
                if(isset($_POST["invoice_order"]["nb_order_status_wc-cancelled"])){
                    $data_update["nb_order_status_wc-cancelled"] = $_POST["invoice_order"]["nb_order_status_wc-cancelled"];
                } else {
                    $data_update["nb_order_status_wc-cancelled"] = 0;
                }
                if(isset($_POST["invoice_order"]["nb_order_status_wc-refunded"])){
                    $data_update["nb_order_status_wc-refunded"] = $_POST["invoice_order"]["nb_order_status_wc-refunded"];
                } else {
                    $data_update["nb_order_status_wc-refunded"] = 0;
                }
                if(isset($_POST["invoice_order"]["nb_order_status_wc-failed"])){
                    $data_update["nb_order_status_wc-failed"] = $_POST["invoice_order"]["nb_order_status_wc-failed"];
                } else {
                    $data_update["nb_order_status_wc-failed"] = 0;
                }
                update_option( 'nd_invoice_template_settings', $data_update );
            }
            // Attach Invoice Email
            if(isset($_POST["attach_invoice"])){
                if(isset($_POST["attach_invoice"]["new_order_email"])){
                    $data_update["new_order_email"] = $_POST["attach_invoice"]["new_order_email"];
                } else {
                    $data_update["new_order_email"] = 0;
                }
                if(isset($_POST["attach_invoice"]["customer_invoice"])){
                    $data_update["customer_invoice"] = $_POST["attach_invoice"]["customer_invoice"];
                } else {
                    $data_update["customer_invoice"] = 0;
                }
                if(isset($_POST["attach_invoice"]["processing_order_email"])){
                    $data_update["processing_order_email"] = $_POST["attach_invoice"]["processing_order_email"];
                } else {
                    $data_update["processing_order_email"] = 0;
                }
                if(isset($_POST["attach_invoice"]["completed_order_email"])){
                    $data_update["completed_order_email"] = $_POST["attach_invoice"]["completed_order_email"];
                } else {
                    $data_update["completed_order_email"] = 0;
                }
                if(isset($_POST["attach_invoice"]["users_can_register"])){
                    $data_update["users_can_register"] = $_POST["attach_invoice"]["users_can_register"];
                } else {
                    $data_update["users_can_register"] = 0;
                }
                if(isset($_POST["attach_invoice"]["failed_order_email"])){
                    $data_update["failed_order_email"] = $_POST["attach_invoice"]["failed_order_email"];
                } else {
                    $data_update["failed_order_email"] = 0;
                }
                if(isset($_POST["attach_invoice"]["order_onhold_email"])){
                    $data_update["order_onhold_email"] = $_POST["attach_invoice"]["order_onhold_email"];
                } else {
                    $data_update["order_onhold_email"] = 0;
                }
                if(isset($_POST["attach_invoice"]["refunded_order_email"])){
                    $data_update["refunded_order_email"] = $_POST["attach_invoice"]["refunded_order_email"];
                } else {
                    $data_update["refunded_order_email"] = 0;
                }
                update_option( 'nd_invoice_template_settings', $data_update );
            }
            // download pdf
            if(isset($_POST['download_pdf'])){
                if(isset($_POST["download_pdf"]["customer_can_download_pdf"])){
                    $data_update["customer_can_download_pdf"]["wc-pending"] = $_POST["download_pdf"]["customer_can_download_pdf"];
                }
                if(isset($_POST["customer_download_invoice_status"]["wc-pending"])){
                    $data_update["customer_download_invoice_status"]["wc-pending"] = $_POST["customer_download_invoice_status"]["wc-pending"];
                } else {
                    $data_update["customer_download_invoice_status"]["wc-pending"] = 0;
                }
                if(isset($_POST["customer_download_invoice_status"]["wc-processing"])){
                    $data_update["customer_download_invoice_status"]["wc-processing"] = $_POST["customer_download_invoice_status"]["wc-processing"];
                } else {
                    $data_update["customer_download_invoice_status"]["wc-processing"] = 0;
                }
                if(isset($_POST["customer_download_invoice_status"]["wc-on-hold"])){
                    $data_update["customer_download_invoice_status"]["wc-on-hold"] = $_POST["customer_download_invoice_status"]["wc-on-hold"];
                } else {
                    $data_update["customer_download_invoice_status"]["wc-on-hold"] = 0;
                }
                if(isset($_POST["customer_download_invoice_status"]["wc-completed"])){
                    $data_update["customer_download_invoice_status"]["wc-completed"] = $_POST["customer_download_invoice_status"]["wc-completed"];
                } else {
                    $data_update["customer_download_invoice_status"]["wc-completed"] = 0;
                }
                if(isset($_POST["customer_download_invoice_status"]["wc-cancelled"])){
                    $data_update["customer_download_invoice_status"]["wc-cancelled"] = $_POST["customer_download_invoice_status"]["wc-cancelled"];
                } else {
                    $data_update["customer_download_invoice_status"]["wc-cancelled"] = 0;
                }
                if(isset($_POST["customer_download_invoice_status"]["wc-refunded"])){
                    $data_update["customer_download_invoice_status"]["wc-refunded"] = $_POST["customer_download_invoice_status"]["wc-refunded"];
                } else {
                    $data_update["customer_download_invoice_status"]["wc-refunded"] = 0;
                }
                if(isset($_POST["customer_download_invoice_status"]["wc-failed"])){
                    $data_update["customer_download_invoice_status"]["wc-failed"] = $_POST["customer_download_invoice_status"]["wc-failed"];
                } else {
                    $data_update["customer_download_invoice_status"]["wc-failed"] = 0;
                }
                update_option( 'nd_invoice_template_settings', $data_update );
            }
            // setting format
            if(isset($_POST["setting_format"])){
                if(isset($_POST["setting_format"]["digits"])){
                    $data_update["digits"] = $_POST["setting_format"]["digits"];
                } else {
                    $data_update["digits"] = 0;
                }
                if(isset($_POST["setting_format"]["invoice_number_start"])){
                    $data_update["invoice_number_start"] = $_POST["setting_format"]["invoice_number_start"];
                } else {
                    $data_update["invoice_number_start"] = 0;
                }
                if(isset($_POST["setting_format"]["invoice_number_format"])){
                    $data_update["invoice_number_format"] = $_POST["setting_format"]["invoice_number_format"];
                } else {
                    $data_update["invoice_number_format"] = "";
                }
                if(isset($_POST["setting_format"]["delivery_number_start"])){
                    $data_update["delivery_number_start"] = $_POST["setting_format"]["delivery_number_start"];
                } else {
                    $data_update["delivery_number_start"] = 0;
                }
                if(isset($_POST["setting_format"]["delivery_number_format"])){
                    $data_update["delivery_number_format"] = $_POST["setting_format"]["delivery_number_format"];
                } else {
                    $data_update["delivery_number_format"] = "";
                }
                if(isset($_POST["setting_format"]["date_format"])){
                    $data_update["date_format"] = $_POST["setting_format"]["date_format"];
                } else {
                    $data_update["date_format"] = "";
                }
                update_option( 'nd_invoice_template_settings', $data_update );
            }
            if(isset($_POST["import_template"])){
                // echo "Import Layout";
            }
            if(isset($_GET['tab'])){
                $tab_active = $_GET['tab'];
                wp_redirect("?page=nb-smart-invoice-setting-pages&tab=" . $tab_active );
            } else {
                wp_redirect("?page=nb-smart-invoice-setting-pages");
            }
        }
        $nbinvoice_settings_tabs = array(
            'nb-invoice-setting-tab1' => 'Template Debug',
            'nb-invoice-setting-tab2' => 'Invoice For Order',
            'nb-invoice-setting-tab3' => 'Attach Invoice Email ',
            'nb-invoice-setting-tab4' => 'Download PDF',
            'nb-invoice-setting-tab5' => 'Settings & Format',
            'nb-invoice-setting-tab6' => 'Import Layout'
        );
        echo $this->netbase_admin_setting_tabs($nbinvoice_settings_tabs);
    }

    public function ndSmartInvoiceListingPage(){
        $_invoice_displayMessages = $this->NB_invoice_displayMessages();
        require_once NETBASE_SMART_INVOICE_PLUGIN_VIEW_DIR . '/backend/invoice_list.php';
    }

    public function ndSmartDeliveryListingPage(){
        $_invoice_displayMessages = $this->NB_invoice_displayMessages();
        require_once NETBASE_SMART_INVOICE_PLUGIN_VIEW_DIR . '/backend/delivery_list.php';
    }
    public function netbase_admin_setting_tabs($tabs, $current=NULL){
        require_once NETBASE_SMART_INVOICE_PLUGIN_VIEW_DIR . '/backend/settingPage.php';
    }
    public function netbase_invoice_template_import_tabs($tabs, $current=NULL){
        require_once NETBASE_SMART_INVOICE_PLUGIN_VIEW_DIR . '/backend/layout_template_import.php';
    }
    public static function nb_template_checkDemo($page) {
        if(NETBASE_TEPLATE_DEMO == true) {
            $this->template_ms_addMsg(__('You are use Demo Mode, so some buttons, functions will be disabled because of security. You can use them in Live mode after you puchase our plugin.', 'netbase-smart-invoice'));
            wp_redirect( esc_url('?page='.$page) );
            exit();
        }
    }
    public function delete_template_invoice($id){
        global $wpdb;
        
        $wpdb->delete("{$wpdb->prefix}netbase_invoice_templates", array(
            'id' => $id
        ), array(
            '%d'
        ));
    }
    public function ndSmartInvoiceCreatePage(){
        global $wpdb;
        $order_preview_sql = "SELECT order_id FROM {$wpdb->prefix}woocommerce_order_items ORDER BY order_id ASC";
        $order_preview = $wpdb->get_results( $order_preview_sql );
        $id_order = 0;
        if(isset($order_preview[0])){
            $id_order = $order_preview[0]->order_id;
        }
        $_invoice_displayMessages = $this->NB_invoice_displayMessages();
        if(isset($_GET['delete'])){
            $_page = "";
            if($_GET['type_template'] == 'invoice'){
                $_page = "nb-smart-invoice-listing-pages";
            }
            if($_GET['type_template'] == 'delivery'){
                $_page = "nb-smart-delivery-listing-pages";
            }
            $this->nb_template_checkDemo($_page);
            $this->delete_template_invoice($_GET['delete']);
            if($_GET['type_template'] == 'invoice'){
                wp_redirect("?page=nb-smart-invoice-listing-pages");
            }
            if($_GET['type_template'] == 'delivery'){
                wp_redirect("?page=nb-smart-delivery-listing-pages");
            }
        }
        if(!isset($_GET['btask']) && !isset($_GET['preview']) ){
            $_getOptionDataProduct = $this->getOptionDataProduct();
            $data_template = [];
            if(isset($_GET["edit"])){
                if($_GET['type_template'] == 'delivery'){
                    $delivery = new NBDeliveryTable();
                    $data_template = $delivery->getTemplateByIdDelivery($_GET["edit"]);
                }
                if($_GET['type_template'] == 'invoice'){
                    $invoices = new NBInvoiceTable();
                    $data_template = $invoices->getTemplateByIdInvoice($_GET["edit"]);
                }
            }
            if($_POST){
                if($_POST){
                    $this->insertDataTemplate($_POST);
                    if((int)$_POST["id"] == 0){
                        $type_template = $_POST['type_template'];
                        $id_query = "SELECT id FROM {$wpdb->prefix}netbase_invoice_templates WHERE type = '" . $type_template ."' ORDER BY id DESC";
                        $id_save = $wpdb->get_results( $id_query );
                        wp_redirect("?page=nb-smart-invoice-create-pages&edit=" . $id_save[0]->id . "&type_template=" . $_POST['type_template']);
                    }
                    if((int)$_POST["id"] > 0){
                        wp_redirect("?page=nb-smart-invoice-create-pages&edit=" . $_POST["id"] . "&type_template=" . $_POST['type_template']);
                    }
                }
            }
            require_once NETBASE_SMART_INVOICE_PLUGIN_VIEW_DIR . '/backend/create_template.php';
        }
        if(isset($_GET['btask'])){
            $this->invoice_generatePDF();
        }
        if(isset($_GET['preview'])){
            $this->_NBCreatePDF->invoice_createPDF($_GET['order_ids'],$type="invoice", $output="I", $path = '', $thanks_download = false, $id_template = $_GET['id_template']);
        }
    }

    public function displayTableInvoices(){
        $invoices = new NBInvoiceTable();
        echo esc_html($invoices->current_action());
        $invoices->prepare_items();
        $invoices->display();  
    }

    public function displayTableDelivery(){
        $delivery = new NBDeliveryTable();
        echo esc_html($delivery->current_action());
        $delivery->prepare_items();
        $delivery->display();  
    }

    public function insertDataTemplate($data){
        global $wpdb;
        $data_insert = array(
            'name_template' 		=> (string)$data['name_template'],
            'template_landscape' 			=> 0,
            'template_invoice_header' 		=> ((string)$data['template_invoice_header']),
            'template_invoice_content' 		=> ((string)$data['template_invoice_content']),
            'template_invoice_footer' 		=> ((string)$data['template_invoice_footer']),
            'template_custom_css' => (string)$data['template_custom_css'],
            'columns_number' 		=> (int)$data['columns_number'],
            'item_title_json' 		=> json_encode( $data['item_title'] ),
            'item_key_value_json' 	=> json_encode( $data['item_key_value'] ),
            'item_title_color_json' 		=> json_encode( $data['item_title_color'] ),
            'item_title_background_Json' 	=> json_encode( $data['item_title_background'] ),
            'public' 		=> 0,
            'type' 					=> (string)$data['type_template'],
        );
        if(isset($data["public"]) && $data["public"] == 'on'){
            $data_insert['public'] = 1;
        }
        if(isset($data["template_landscape"]) && $data["template_landscape"] == 'on'){
            $data_insert['template_landscape'] = 1;
        }
        if((int)$data['id'] > 0){
            if((int)$data_insert['public'] == 1){
                $this->unPublicInvoiceTemplate($data_insert['type']);
            }
            $wpdb->update("{$wpdb->prefix}netbase_invoice_templates", $data_insert, array('id'=>$data['id']) );

        } else {
            if((int)$data_insert['public'] == 1){
                $this->unPublicInvoiceTemplate($data_insert['type']);
            }
            $wpdb->insert("{$wpdb->prefix}netbase_invoice_templates", $data_insert );
        }

        return true;
    }
    public function unPublicInvoiceTemplate($type_template){
        global $wpdb;
        
        $sql = "SELECT * FROM {$wpdb->prefix}netbase_invoice_templates WHERE type ='" . esc_sql($type_template) . "'";

        $result = $wpdb->get_results($sql, 'ARRAY_A');
        foreach ($result as $value_data) {
            $value_data['public'] = 0;
            $wpdb->update("{$wpdb->prefix}netbase_invoice_templates", $value_data, array('id'=>$value_data['id']) );
        }
        return;
    }

    public function getOptionDataProduct(){
        $data = [
            "p_name" => esc_html__("Product Name",'netbase-smart-invoice'),
            "p_name_custom" => esc_html__("Product Name with Customization",'netbase-smart-invoice'),
            "p_desc" => esc_html__("Product Full Description",'netbase-smart-invoice'),
            "p_shor_desc" => esc_html__("Product Short Description",'netbase-smart-invoice'),
            "p_image" => esc_html__("Product Image",'netbase-smart-invoice'),
            "p_sku" => esc_html__("SKU",'netbase-smart-invoice'),
            "qty" => esc_html__("Quantity",'netbase-smart-invoice'),
            "unit_price_ex_tax" => esc_html__("Unit Price(Tax Excl)",'netbase-smart-invoice'),
            "unit_price_in_tax_no_old_price" => esc_html__("Unit Price(Tax Incl) - Without Old Price",'netbase-smart-invoice'),
            "unit_price_in_tax_in_old_price" => esc_html__("Unit Price(Tax Incl) - With Old Price",'netbase-smart-invoice'),
            "unit_price_ex_tax_has_discount" => esc_html__("Unit Price(Tax Excl) has Discount",'netbase-smart-invoice'),
            "unit_price_in_tax_has_discount" => esc_html__("Unit Price(Tax Incl) has Discount",'netbase-smart-invoice'),
            "p_tax" => esc_html__("Tax Amount",'netbase-smart-invoice'),
            "tax_name" => esc_html__("Tax Name",'netbase-smart-invoice'),
            "tax_rate" => esc_html__("Tax Rate(%)",'netbase-smart-invoice'),
            "discounted" => esc_html__("Unit Discounted Amount",'netbase-smart-invoice'),
            "total_ex_tax" => esc_html__("Total(Tax excl)",'netbase-smart-invoice'),
            "total_in_tax" => esc_html__("Total(Tax Incl)",'netbase-smart-invoice'),
            "total_ex_tax_has_discount" => esc_html__("Total(Tax Excl) has Discount",'netbase-smart-invoice'),
            "total_incl_tax_has_discount" => esc_html__("Total(Tax Incl) has Discount",'netbase-smart-invoice')
        ];
        return $data;
    }

    function invoice_add_meta_box_order_detail(){
        add_meta_box(
                'nb_invoice_meta_box_order_detail_backend',
                esc_html__('NETBASE Smart Invoice & Delivery','netbase-smart-invoice'),
                array($this, 'nb_invoice_display_meta_box_order_detail'),
                'shop_order',
                'side',
                'high'
            );
    }
    function nb_invoice_display_meta_box_order_detail(){
        if (!isset($_GET['post'])) {
            return ;
        }
        $order_id = absint($_GET['post']);
        $order = wc_get_order($order_id);
        //
        if($this->_NBCreatePDF->invoice_checkOrderStatus($order) === false) {
            echo esc_html__('No Invoice & Delivery','netbase-smart-invoice');
            return ;
        }

        $invoice_info = $this->_NBCreatePDF->invoice_getInvoiceOrder($order_id);
        if(isset($invoice_info['invoice_date']) && !empty($invoice_info['invoice_date'])) {
            echo esc_html__('Invoice on Date: ','netbase-smart-invoice').date_i18n( $this->template_setting_option['date_format'], strtotime( $invoice_info['invoice_date'] ) ).'<br />';
            echo esc_html__('Invoice Number: ').$this->_NBCreatePDF->invoice_formatInvoiceNumber($invoice_info).'<br />';
        }
        if(isset($invoice_info['delivery_date']) && !empty($invoice_info['delivery_date'])) {
            echo esc_html__('Delivery on Date: ','netbase-smart-invoice').date_i18n( $this->template_setting_option['date_format'], strtotime( $invoice_info['delivery_date'] ) ).'<br />';
            echo esc_html__('Delivery Number: ','netbase-smart-invoice').$this->_NBCreatePDF->invoice_formatDeliveryNumber($invoice_info).'<br />';
        }
        echo '<div style="margin-top:7px;">';
        $this->invoice_add_buttons_to_list($order);
        echo '</div>';
    }
    function invoice_add_buttons_to_list($order) {
	
        if ( $order->get_status() == 'trash' ) {
            return;
        }

        if($this->_NBCreatePDF->invoice_checkOrderStatus($order) === false) {
            return '';
        }
        $plugin_url = NETBASE_SMART_INVOICE_PLUGIN_URL;
        $listing_actions = array(
            'invoice'		=> array (
                'url'		=> wp_nonce_url( admin_url( 'admin.php?page=nb-smart-invoice-create-pages&btask=generatePDF&type=invoice&order_ids=' . $order->get_id() ), 'netbase_generate_invoice' ),
                'img'		=> $plugin_url . 'views/images/invoice.svg',
                'alt'		=> esc_html__( 'Invoice','netbase-smart-invoice'),
            ),
            'packing-slip'	=> array (
                'url'		=> wp_nonce_url( admin_url( 'admin.php?page=nb-smart-invoice-create-pages&btask=generatePDF&type=delivery&&order_ids=' . $order->get_id() ), 'netbase_generate_invoice' ),
                'img'		=> $plugin_url . 'views/images/delivery.svg',
                'alt'		=> esc_html__( 'Delivery Slip','netbase-smart-invoice'),
            ),
        );
    
        foreach ($listing_actions as $action => $data) {
            ?>
            <a href="<?php echo esc_html($data['url']); ?>" class="button tips nb_btn_export_pdf <?php echo esc_html($action); ?>" target="_blank" alt="<?php echo esc_html($data['alt']); ?>" data-tip="<?php echo esc_html($data['alt']); ?>">
                <img src="<?php echo esc_html($data['img']); ?>" alt="<?php echo esc_html($data['alt']); ?>" width="16">
            </a>
            <?php
        }
    }

    function invoice_generatePDF() {
        $nonce = esc_attr( $_REQUEST['_wpnonce'] ,'netbase-smart-invoice');
        $order_ids = absint($_GET['order_ids']);
        if ( ! wp_verify_nonce( $nonce, 'netbase_generate_invoice' )  || empty($order_ids)) {
            wp_die( __('Go get a life script kiddies','netbase-smart-invoice','netbase-smart-invoice') );
        }

        $order = new WC_Order ( $order_ids);

        if($this->_NBCreatePDF->invoice_checkOrderStatus($order) === false) {
            wp_die( esc_html__( 'This Order do not have Invoice & Delivery','netbase-smart-invoice' ) );
        }
        
        if ( ! defined('WP_USER_ADMIN') && $order->user_id != get_current_user_id() ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.','netbase-smart-invoice' ) );
        }
        if ($this->_NBCreatePDF->invoice_customer_can_download($order) == false && ! defined('WP_USER_ADMIN')) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.','netbase-smart-invoice' ) );
        }
        $this->_NBCreatePDF->invoice_createPDF($_GET['order_ids'],$_GET['type'],"I");
    }
    function customer_download_generatePDF() {
        $nonce = esc_attr( $_REQUEST['_wpnonce'] ,'netbase-smart-invoice');
        $order_ids = absint($_GET['order_ids']);
        if ( ! wp_verify_nonce( $nonce, 'netbase_generate_invoice' )  || empty($order_ids)) {
            wp_die( __('Go get a life script kiddies','netbase-smart-invoice','netbase-smart-invoice') );
        }

        $order = new WC_Order ( $order_ids);

        if($this->_NBCreatePDF->invoice_checkOrderStatus($order) === false) {
            wp_die( esc_html__( 'This Order do not have Invoice & Delivery','netbase-smart-invoice' ) );
        }
        
        if ( ! defined('WP_USER_ADMIN') && $order->user_id != get_current_user_id() ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.','netbase-smart-invoice' ) );
        }
        if ($this->_NBCreatePDF->invoice_customer_can_download($order) == false && ! defined('WP_USER_ADMIN')) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.','netbase-smart-invoice' ) );
        }
        $this->_NBCreatePDF->invoice_createPDF($_GET['order_ids'],$_GET['type'],"D");
    }
    function nb_invoice_woocommerce_email_attachments($attachments, $status, $order) {

        if ( !is_object( $order ) || !isset( $status ) ) {
            return $attachments;
        }

        if ( get_post_type( $order->get_id() ) == 'wc_booking' && isset($order->order) ) {
            $order = $order->order;
        }
    
        if ( in_array( $status, array( 'no_stock', 'low_stock', 'backorder', 'customer_new_account', 'customer_reset_password' ) ) || get_post_type( $order->get_id() ) != 'shop_order' ) {
            return $attachments; 
        }

        if ( get_class( $order ) == 'WP_User' ) {
            return $attachments;
        }
        $pdf_path_tmp = $this->_NBCreatePDF->nb_invoice_create_file_tmp();

        array_map('unlink', ( glob( $pdf_path_tmp.'*.pdf' ) ? glob( $pdf_path_tmp.'*.pdf' ) : array() ) );
        
 
        $is_attached = false;
        if($status == "new_order" && $this->template_setting_option["new_order_email"] == 1)
            $is_attached =true;
        else if($status == "customer_invoice" && $this->template_setting_option["customer_invoice"] == 1)
            $is_attached =true;
        else if($status == "customer_processing_order" && $this->template_setting_option["processing_order_email"] == 1)
            $is_attached =true;
        else if($status == "customer_completed_order" && $this->template_setting_option["completed_order_email"] == 1)
            $is_attached =true;
        else if($status == "cancelled_order" && $this->template_setting_option["users_can_register"] == 1)
            $is_attached =true;
        else if($status == "failed_order" && $this->template_setting_option["failed_order_email"] == 1)
            $is_attached =true;
        else if($status == "customer_on_hold_order" && $this->template_setting_option["order_onhold_email"] == 1)
            $is_attached =true;
        else if($status == "customer_refunded_order" && $this->template_setting_option["refunded_order_email"] == 1)
            $is_attached =true;

        if($is_attached == true) {

            $pdf_file = $this->_NBCreatePDF->invoice_createPDF(absint($order->get_id()), 'invoice', 'F', $pdf_path_tmp);
            $pdf_path = $pdf_path_tmp . $pdf_file;
            $attachments[] = $pdf_path;
        }

        return $attachments;
    }
    function invoice_manage_invoices(){
        $task 	= $_REQUEST['btask'];
        if($task == 'download_invoice_PDF' ){
            $this->customer_download_generatePDF();
        }
        return;
    }
    public static function template_ms_addMsg($msg, $type='') {
        if(!isset($_SESSION["invoice_msg"])) {
            $_SESSION["invoice_msg"] = array();
        }
        $_SESSION["invoice_msg"][] = array($msg, $type);
    }
    function NB_invoice_displayMessages() {
        if(!isset($_SESSION["invoice_msg"]) || empty($_SESSION["invoice_msg"]))
            return;
        $html = '';
        foreach($_SESSION["invoice_msg"] AS $v) {
            $html .= invoice_renderMsg($v[0], $v[1]);
        }
        $_SESSION["invoice_msg"] = array();
        return $html;
    }
}