<?php

namespace StoreEngine\Addons\Invoice;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use StoreEngine\Addons\Invoice\PDF\Generator;
use StoreEngine\Classes\Order;
use StoreEngine\Mpdf\MpdfException;
use StoreEngine\Utils\Fs;
use StoreEngine\Utils\Helper;
use Throwable;

class HelperAddon {

	public static function get_fonts_dir(): string {
		return Helper::get_upload_dir() . '/invoice/fonts';
	}

	public static function get_setting( string $name, $default = null ) {
		$settings = Settings::get_settings_saved_data();

		return $settings[ $name ] ?? $default;
	}

	public static function get_pdf_url( int $order_id, string $document_type = 'invoice', bool $download = false ): string {
		return add_query_arg( [
			'action'        => 'storeengine_invoice/generate_pdf',
			'document_type' => $document_type,
			'order_id'      => $order_id,
			'download'      => $download,
			'security'      => wp_create_nonce( 'storeengine_nonce' ),
		], admin_url( 'admin-ajax.php' ) );
	}

	public static function get_invoice_preview_url( string $order_key ): string {
		return add_query_arg( [
			'store_document_type' => 'invoice',
			'key'                 => str_replace( 'se_order_', 'store_order_', $order_key ),
		], site_url() );
	}

	public static function generate_pdf( Order $order ): ?string {
		try {
			$invoice_date = null;

			switch ( self::get_setting( 'invoice_date_from', 'order_paid' ) ) {
				case 'order_created':
					$invoice_date = $order->get_date_created_gmt() ? $order->get_date_created_gmt()->format( self::get_setting( 'date_format', 'd F, Y' ) ) : null;
					break;
				case 'order_paid':
				default:
					$invoice_date = $order->get_date_paid_gmt() ? $order->get_date_paid_gmt()->format( self::get_setting( 'date_format', 'd F, Y' ) ) : null;
					break;
			}

			ob_start();
			include STOREENGINE_INVOICE_TEMPLATE_DIR . 'invoice/template.php';
			$invoice_html = ob_get_clean();
			$generator    = new Generator( $invoice_html, Fs::get_contents( STOREENGINE_INVOICE_TEMPLATE_DIR . 'invoice/style.css' ) );

			$dir = Helper::get_upload_dir() . '/tmp-invoices';

			if ( ! is_dir( $dir ) ) {
				wp_mkdir_p( $dir );
			}

			$file_path = $dir . '/invoice-' . $order->get_id() . '.pdf';

			$generator->save( $file_path );

			if ( ! as_next_scheduled_action( 'storeengine/mail/clean_tmp_invoices', [ 'pdf' => $file_path ] ) ) {
				// Delete after 10 minutes.
				as_schedule_single_action( time() + 600, 'storeengine/mail/clean_tmp_invoices', [ 'pdf' => $file_path ] );
			}

			return $file_path;
		} catch ( Throwable $e ) {
			Helper::log_error( 'Failed to create order pdf invoice.' );
			Helper::log_error( $e );

			return null;
		}
	}
}
