<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use Dompdf\Dompdf;
use Dompdf\Options;

class Pdf extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
	}

	/**
	 * Sales invoices
	 * 3. Default Format (now uses modern HTML view)
	 * 4. GST invoice Format
	 * 5. Multi-Unit Format (shows both main and alternate units)
	*/
	public function sales($sales_id=null){

		$params = array();

		//Validate Record Authenttication
		$this->belong_to('db_sales',$sales_id);
		if(!$this->permissions('sales_add') && !$this->permissions('sales_edit')){
			$this->show_access_denied_page();
		}

		// Check if download is requested (default is print view)
		$download = $this->input->get('download') == '1';
		
		if(!$download){
			// Default: Show HTML page with embedded PDF that auto-triggers print
			$this->_show_pdf_print_view($sales_id);
			return;
		}

		//Select Store Invoice Format
		$invoice_format_id = get_invoice_format_id();

		$params['sales_id'] = $sales_id;

		if($invoice_format_id==4){
			//GST invoice
			$this->load->library('tcpdf/invoice/GstInvoice',$params);

			$this->gstinvoice->show_pdf();
		}
		elseif($invoice_format_id==5){
			//Multi-Unit invoice - use HTML view with DomPDF
			$this->_generate_pdf_fast($sales_id);
		}
		else{
			//Default invoice - now uses modern HTML view (format 3 or any other)
			$this->_generate_pdf_fast($sales_id);
		}

	}

	/**
	 * Fast PDF generation with optimizations
	 */
	private function _generate_pdf_fast($sales_id){
		// Set output buffering and disable time limit for faster processing
		ob_start();
		if(function_exists('set_time_limit')){
			@set_time_limit(30);
		}
		
		$data = $this->data;
		$data['page_title'] = $this->lang->line('sales_invoice');
		$data = array_merge($data, array('sales_id' => $sales_id));

		// Get HTML from the view
		$html = $this->load->view('print-sales-invoice-5', $data, true);
		
		// Optimized DomPDF options for speed and compression
		$options = new Options();
		$options->set('isRemoteEnabled', true);
		$options->set('isHtml5ParserEnabled', true);
		$options->set('isPhpEnabled', false);
		$options->set('defaultFont', 'Arial');
		$options->set('isFontSubsettingEnabled', false); // Disable for speed
		$options->set('dpi', 72); // Lower DPI for faster rendering and smaller file size
		$options->set('enableCssFloat', false);
		$options->set('isJavascriptEnabled', false); // Disable JS for speed
		$options->set('debugKeepTemp', false);
		$options->set('debugCss', false);
		$options->set('chroot', FCPATH);
		$options->set('compress', true); // Enable compression
		$options->set('imageScale', 0.8); // Scale down images slightly to reduce size
		$options->set('logOutputFile', ''); // Disable logging for speed
		$options->set('tempDir', sys_get_temp_dir()); // Use system temp for faster I/O
		$options->set('fontCache', sys_get_temp_dir()); // Cache fonts in temp
		$options->set('fontDir', sys_get_temp_dir()); // Use temp for fonts
		
		$dompdf = new Dompdf($options);

		// Load HTML content
		$dompdf->loadHtml($html, 'UTF-8');
		
		// Setup the paper size and orientation
		$dompdf->setPaper('A4', 'portrait');
		
		// Render the HTML as PDF
		$dompdf->render();
		
		// Enable PDF compression for smaller file size
		try {
			$canvas = $dompdf->getCanvas();
			if (method_exists($canvas, 'get_cpdf')) {
				$cpdf = $canvas->get_cpdf();
				if (method_exists($cpdf, 'setCompression')) {
					$cpdf->setCompression(true);
				}
			}
		} catch (Exception $e) {
			// Compression not available, continue without it
		}
		
		// Clear output buffer
		ob_end_clean();
		
		// Output the generated PDF for printing in browser (Attachment=0 allows printing)
		$filename = "Sales-invoice-$sales_id-".date('M')."_".date('d')."_".date('Y').".pdf";
		$dompdf->stream($filename, array("Attachment"=>0));
		exit;

	}

	/**
	 * Show HTML invoice view for printing - User controls when to print
	 * No PDF generation delay - shows HTML invoice instantly
	 * User can use browser print button or Ctrl+P when ready
	 */
	private function _show_pdf_print_view($sales_id){
		// Load data - same as Sales controller print_invoice method
		$data = $this->data;
		$data = array_merge($data, array('sales_id' => $sales_id));
		$data['page_title'] = $this->lang->line('sales_invoice');
		
		// Set back URL for the back button
		$data['back_url'] = base_url("sales/invoice/$sales_id");
		
		// Always use Multi-Unit Format (Format 5) - the only format now
		$this->load->view('print-sales-invoice-5', $data);
	}

	/**
	 * Direct PDF stream (used by print view)
	 */
	public function sales_direct($sales_id=null){
		$params = array();

		//Validate Record Authenttication
		$this->belong_to('db_sales',$sales_id);
		if(!$this->permissions('sales_add') && !$this->permissions('sales_edit')){
			$this->show_access_denied_page();
		}

		//Select Store Invoice Format
		$invoice_format_id = get_invoice_format_id();

		$params['sales_id'] = $sales_id;

		if($invoice_format_id==4){
			//GST invoice
			$this->load->library('tcpdf/invoice/GstInvoice',$params);
			$this->gstinvoice->show_pdf();
		}
		elseif($invoice_format_id==5){
			//Multi-Unit invoice - use HTML view with DomPDF
			$this->_generate_pdf_fast($sales_id);
		}
		else{
			//Default invoice - now uses modern HTML view (format 3 or any other)
			$this->_generate_pdf_fast($sales_id);
		}
	}

	/**
	 * Purchase invoices - Print view
	 */
	public function purchase($purchase_id=null){
		//Validate Record Authentication
		$this->belong_to('db_purchase',$purchase_id);
		if(!$this->permissions('purchase_add') && !$this->permissions('purchase_edit')){
			$this->show_access_denied_page();
		}

		// Check if download is requested (default is print view)
		$download = $this->input->get('download') == '1';
		
		if(!$download){
			// Default: Show HTML print view
			$this->_show_purchase_print_view($purchase_id);
			return;
		}

		// Generate PDF for download
		$this->_generate_purchase_pdf($purchase_id);
	}

	/**
	 * Show HTML purchase invoice view for printing - User controls when to print
	 */
	private function _show_purchase_print_view($purchase_id){
		// Load data
		$data = $this->data;
		$data = array_merge($data, array('purchase_id' => $purchase_id));
		$data['page_title'] = $this->lang->line('purchase_invoice');
		
		// Set back URL for the back button
		$data['back_url'] = base_url("purchase/invoice/$purchase_id");
		
		// Load purchase invoice view (typically print-purchase-invoice-2)
		$this->load->view('print-purchase-invoice-2', $data);
	}

	/**
	 * Generate Purchase PDF
	 */
	private function _generate_purchase_pdf($purchase_id){
		// Set output buffering and disable time limit for faster processing
		ob_start();
		if(function_exists('set_time_limit')){
			@set_time_limit(30);
		}
		
		$data = $this->data;
		$data = array_merge($data, array('purchase_id' => $purchase_id));
		$data['page_title'] = $this->lang->line('purchase_invoice');
		
		// Get HTML from the view
		$html = $this->load->view('print-purchase-invoice-2', $data, true);
		
		mb_internal_encoding('UTF-8');

		// Optimized DomPDF options for speed and compression
		$options = new Options();
		$options->set('isRemoteEnabled', true);
		$options->set('isHtml5ParserEnabled', true);
		$options->set('isPhpEnabled', false);
		$options->set('defaultFont', 'Arial');
		$options->set('isFontSubsettingEnabled', false);
		$options->set('dpi', 72);
		$options->set('enableCssFloat', false);
		$options->set('isJavascriptEnabled', false);
		$options->set('debugKeepTemp', false);
		$options->set('debugCss', false);
		$options->set('chroot', FCPATH);
		$options->set('compress', true);
		$options->set('imageScale', 0.8);
		$options->set('logOutputFile', '');
		$options->set('tempDir', sys_get_temp_dir());
		$options->set('fontCache', sys_get_temp_dir());
		$options->set('fontDir', sys_get_temp_dir());
		
		$dompdf = new Dompdf($options);
		$dompdf->loadHtml($html, 'UTF-8');
		$dompdf->setPaper('A4', 'portrait');
		$dompdf->render();
		
		// Enable PDF compression
		try {
			$canvas = $dompdf->getCanvas();
			if (method_exists($canvas, 'get_cpdf')) {
				$cpdf = $canvas->get_cpdf();
				if (method_exists($cpdf, 'setCompression')) {
					$cpdf->setCompression(true);
				}
			}
		} catch (Exception $e) {
			// Compression not available, continue without it
		}
		
		// Clear output buffer
		ob_end_clean();
		
		// Output the generated PDF for printing in browser
		$filename = "Purchase-invoice-$purchase_id-".date('M')."_".date('d')."_".date('Y').".pdf";
		$dompdf->stream($filename, array("Attachment"=>0));
		exit;
	}

	/**
	 * Sales return invoices – same fast pattern as sales/purchase
	 * Default: show HTML print view (instant). ?download=1: generate optimized PDF.
	 */
	public function sales_return($return_id = null){
		$this->belong_to('db_salesreturn', $return_id);
		if (!$this->permissions('sales_return_add') && !$this->permissions('sales_return_edit')) {
			$this->show_access_denied_page();
		}

		$download = $this->input->get('download') == '1';

		if (!$download) {
			$this->_show_sales_return_print_view($return_id);
			return;
		}

		$this->_generate_sales_return_pdf($return_id);
	}

	/**
	 * Show HTML sales return invoice for printing – instant, no PDF generation
	 */
	private function _show_sales_return_print_view($return_id){
		$data = $this->data;
		$data = array_merge($data, array('return_id' => $return_id));
		$data['page_title'] = $this->lang->line('return_invoice');
		$data['back_url'] = base_url('sales_return/invoice/' . $return_id);
		$this->load->view('print-sales-return-invoice-2', $data);
	}

	/**
	 * Generate sales return PDF with same optimizations as sales/purchase
	 */
	private function _generate_sales_return_pdf($return_id){
		ob_start();
		if (function_exists('set_time_limit')) {
			@set_time_limit(30);
         
		}

		$data = $this->data;
		$data = array_merge($data, array('return_id' => $return_id));
		$data['page_title'] = $this->lang->line('return_invoice');
		$html = $this->load->view('print-sales-return-invoice-2', $data, true);

		$options = new Options();
		$options->set('isRemoteEnabled', true);
		$options->set('isHtml5ParserEnabled', true);
		$options->set('isPhpEnabled', false);
		$options->set('defaultFont', 'Arial');
		$options->set('isFontSubsettingEnabled', false);
		$options->set('dpi', 72);
		$options->set('enableCssFloat', false);
		$options->set('isJavascriptEnabled', false);
		$options->set('debugKeepTemp', false);
		$options->set('debugCss', false);
		$options->set('chroot', FCPATH);
		$options->set('compress', false);
		$options->set('imageScale', 0.8);
		$options->set('logOutputFile', '');
		$options->set('tempDir', sys_get_temp_dir());
		$options->set('fontCache', sys_get_temp_dir());
		$options->set('fontDir', sys_get_temp_dir());

		$dompdf = new Dompdf($options);
		$dompdf->loadHtml($html, 'UTF-8');
		$dompdf->setPaper('A4', 'portrait');
		$dompdf->render();

		try {
			$canvas = $dompdf->getCanvas();
			if (method_exists($canvas, 'get_cpdf')) {
				$cpdf = $canvas->get_cpdf();
				if (method_exists($cpdf, 'setCompression')) {
					$cpdf->setCompression(true);
				}
			}
		} catch (Exception $e) {
		}

		ob_end_clean();
		$filename = "Sales-return-$return_id-".date('M')."_".date('d')."_".date('Y').".pdf";
		$dompdf->stream($filename, array("Attachment"=>0));
		exit;
	}

}