<?php
class NBT_Pdf_Creator_Ajax{

	protected static $initialized = false;
	
    /**
     * Initialize functions.
     *
     * @return  void
     */
    public static function initialize() {
        if ( self::$initialized ) {
            return;
        }

	    self::admin_hooks();
        self::$initialized = true;
    }


    public static function admin_hooks(){
		add_action( 'wp_ajax_nopriv_nbtpdf_download', array( __CLASS__, 'nbtpdf_download') );
		add_action( 'wp_ajax_nbtpdf_download', array( __CLASS__, 'nbtpdf_download') );
    }

    public static function nbtpdf_download(){
    	$order_id = absint($_REQUEST['order_id'] );
    	if(is_numeric($order_id)){
			$order = wc_get_order($order_id);

			$settings = array(
				'paper_size'		=> 'A4',
				'paper_orientation'	=> 'portrait',
				'font_subsetting'	=> false,
			);
			$pdf_settings = get_option('pdf-creator_settings');
			
			

			
			
			
			if(isset($pdf_settings['nbt_pdf_logo'])){
				$logo = $pdf_settings['nbt_pdf_logo'];
			}

			if(isset($pdf_settings['nbt_pdf_brands'])){
				$brands = $pdf_settings['nbt_pdf_brands'];
			}

			if(isset($pdf_settings['nbt_pdf_address'])){
				$address = $pdf_settings['nbt_pdf_address'];
			}


			$primary_color = '#cd3334';
			if(isset($pdf_settings['nbt_pdf_primary_color'])){
				$primary_color = $pdf_settings['nbt_pdf_primary_color'];
			}

			$text_color = '#000';
			if(isset($pdf_settings['nbt_pdf_text_color'])){
				$text_color = $pdf_settings['nbt_pdf_text_color'];
			}
			
			$fullname_order = get_post_meta($order_id, '_billing_first_name', true). ' ' .get_post_meta($order_id, '_billing_last_name', true);

		
			$order_item_totals_show = array('cart_subtotal', 'order_total');

			if(file_exists(NBT_PDF_PATH.'temp/pdf_'.$pdf_settings['nbt_pdf_template'].'.php')){




			

				ob_start();
				include NBT_PDF_PATH.'temp/dl_pdf_'.$pdf_settings['nbt_pdf_template'].'.php';
				$html = ob_get_clean();
				
				
				
				$pdf_maker = NBT_Solutions_Pdf_Creator::pdf_maker($html, $settings);
				

				
				
				$pdf = $pdf_maker->output();
				$filename = 'invoice-'.$order->get_id().'.pdf';

				NBT_Solutions_Pdf_Creator::wpdf_headers( $filename, 'download', $pdf );
				echo $pdf;
			}else{
				_e('Template '.$pdf_settings['nbt_pdf_template'].' not exists!');
			}

		}
    	wp_die();
    }

 
}