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

require_once FCPATH . 'vendor/autoload.php';

use Mpdf\Mpdf;
use Mpdf\Output\Destination;

if (!defined('ROOTPATH')) {
	define('ROOTPATH', rtrim(FCPATH, '/\\'));
}

if (!function_exists('pdf_create')) {
	function pdf_create($html, $filename = '', $stream = true, $set_paper = '', $attach = null, $folder_name = null, $watermark = null, $inline = false)
	{
		$filename = trim((string) $filename) !== '' ? trim((string) $filename) : 'document';
		$print_view = config_item('invoice_print_view');
		$paper_setting = strtolower((string) $set_paper);
		if (in_array($paper_setting, array('p', 'portrait'), true)) {
			$orientation = 'P';
		} elseif (in_array($paper_setting, array('l', 'landscape'), true) || !empty($set_paper)) {
			$orientation = 'L';
		} else {
			$orientation = strtolower((string) ($print_view ?: 'landscape')) === 'portrait' ? 'P' : 'L';
		}

		$config = array(
			'mode' => 'utf-8',
			'format' => 'A4',
			'orientation' => $orientation,
			'default_font' => 'dejavusanscondensed',
			'setAutoTopMargin' => 'stretch',
			'setAutoBottomMargin' => 'stretch',
			'tempDir' => APPPATH . 'cache/mpdf',
		);

		if (!is_dir($config['tempDir'])) {
			@mkdir($config['tempDir'], 0775, true);
		}

		$mpdf = new Mpdf($config);
		$mpdf->SetCreator(config_item('company_name') ?: 'ERP');
		$mpdf->SetAuthor(config_item('company_name') ?: 'ERP');
		$mpdf->SetTitle($filename);
		$mpdf->SetDisplayMode('fullpage');
		$mpdf->curlAllowUnsafeSslRequests = true;
		$mpdf->showImageErrors = false;

		$watermark_enabled = config_item('show_watermark');
		if (!empty($watermark_enabled) && $watermark_enabled !== 'FALSE' && !empty($watermark)) {
			$mpdf->SetWatermarkText(trim(strip_tags((string) $watermark)));
			$mpdf->showWatermarkText = true;
			$mpdf->watermarkTextAlpha = 0.08;
		}

		$mpdf->WriteHTML((string) $html);

		if (!$stream) {
			return $mpdf->Output('', Destination::STRING_RETURN);
		}

		if (!empty($attach)) {
			$path = !empty($folder_name)
				? FCPATH . 'uploads/' . trim((string) $folder_name, '/')
				: FCPATH . 'uploads';

			if (!is_dir($path)) {
				@mkdir($path, 0775, true);
			}

			$file = rtrim($path, '/\\') . DIRECTORY_SEPARATOR . $filename . '.pdf';
			$mpdf->Output($file, Destination::FILE);
			return $file;
		}

		if (!empty($inline)) {
			return $mpdf->Output($filename . '.pdf', Destination::INLINE);
		}

		return $mpdf->Output($filename . '.pdf', Destination::DOWNLOAD);
	}
}
