<?php

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

/**
 * PDF export for the monthly client report (same HTML as on-screen preview).
 *
 * Dompdf does not handle Hebrew RTL correctly and ignores CSS gradients.
 * Before render we fix both so the attached PDF matches the admin preview.
 */
final class IComm_SM_Pdf {

	public static function autoload(): bool {
		$autoload = ICOMM_SM_PLUGIN_DIR . 'vendor/autoload.php';
		if (!is_readable($autoload)) {
			return false;
		}
		require_once $autoload;
		return class_exists('\\Dompdf\\Dompdf');
	}

	public static function available(): bool {
		return self::autoload();
	}

	/**
	 * UTF-8 safe string reverse (for Dompdf Hebrew glyph order workaround).
	 */
	public static function utf8_strrev(string $str): string {
		if ($str === '') {
			return '';
		}
		if (function_exists('mb_str_split')) {
			$chars = mb_str_split($str, 1, 'UTF-8');
			if (is_array($chars)) {
				return implode('', array_reverse($chars));
			}
		}
		preg_match_all('/./us', $str, $m);
		return implode('', array_reverse($m[0] ?? []));
	}

	/**
	 * Dompdf draws Hebrew letter runs backwards. Pre-reverse Hebrew segments so the PDF reads correctly.
	 */
	public static function fix_hebrew_for_dompdf(string $text): string {
		if ($text === '' || !preg_match('/[\x{0590}-\x{05FF}]/u', $text)) {
			return $text;
		}

		return (string) preg_replace_callback(
			'/[\x{0590}-\x{05FF}]+/u',
			static function (array $m): string {
				return IComm_SM_Pdf::utf8_strrev($m[0]);
			},
			$text
		);
	}

	/**
	 * Adapt screen HTML for Dompdf: solid header colors + Hebrew glyph fix in text nodes.
	 */
	public static function prepare_html_for_dompdf(string $html): string {
		// Dompdf ignores linear-gradient. Keep solid background-color; strip gradient image.
		$html = (string) preg_replace(
			'/background-image\s*:\s*linear-gradient\([^;)]+\)\s*;?/iu',
			'',
			$html
		);
		$html = (string) preg_replace(
			'/background\s*:\s*linear-gradient\([^;)]+\)/iu',
			'background:#1e3a5f',
			$html
		);

		// Fix Hebrew inside text nodes only (between tags), leave attributes/URLs alone.
		$html = (string) preg_replace_callback(
			'/>[^<]*[\x{0590}-\x{05FF}][^<]*</u',
			static function (array $m): string {
				$chunk = $m[0];
				// Keep leading '>' and trailing '<'.
				$inner = substr($chunk, 1, -1);
				return '>' . IComm_SM_Pdf::fix_hebrew_for_dompdf($inner) . '<';
			},
			$html
		);

		return $html;
	}

	/**
	 * Full HTML document used for PDF.
	 *
	 * @param array<string, string>|null $period
	 */
	public static function report_document_html(?array $period = null): string {
		$inner = IComm_SM_Report_Builder::monthly_client_report_html($period);
		$inner = self::prepare_html_for_dompdf($inner);

		return '<!DOCTYPE html><html lang="he"><head><meta charset="UTF-8">'
			. '<style>'
			. 'body{margin:0;padding:16px;background:#f0f0f1;font-family:DejaVu Sans,Arial,Helvetica,sans-serif;direction:rtl;text-align:right;color:#1d2327;}'
			. 'h1,h2,h3,p,td,th,div,span,strong,label{font-family:DejaVu Sans,Arial,Helvetica,sans-serif !important;}'
			. '.icomm-sm-monthly-report{max-width:720px !important;}'
			. '.icomm-sm-monthly-report td h1,.icomm-sm-monthly-report td p{font-family:DejaVu Sans,Arial,Helvetica,sans-serif !important;}'
			. '</style></head><body dir="rtl">'
			. $inner
			. '</body></html>';
	}

	/**
	 * @param array<string, string>|null $period
	 * @return array{ok:bool,pdf?:string,error?:string,filename?:string,detail?:string}
	 */
	public static function render_monthly_report(?array $period = null): array {
		if (!self::autoload()) {
			return ['ok' => false, 'error' => 'pdf_lib_missing'];
		}

		$period = is_array($period) ? $period : IComm_SM_Report_Builder::previous_month_period();
		$html = self::report_document_html($period);

		try {
			$options = new \Dompdf\Options();
			$options->set('isHtml5ParserEnabled', true);
			$options->set('isRemoteEnabled', true);
			$options->set('isFontSubsettingEnabled', true);
			$options->set('defaultFont', 'DejaVu Sans');
			$options->setChroot(ICOMM_SM_PLUGIN_DIR);

			$dompdf = new \Dompdf\Dompdf($options);
			$dompdf->loadHtml($html, 'UTF-8');
			$dompdf->setPaper('A4', 'portrait');
			$dompdf->render();
			$pdf = $dompdf->output();
			if (!is_string($pdf) || $pdf === '') {
				return ['ok' => false, 'error' => 'pdf_empty'];
			}

			$domain = preg_replace('/[^a-z0-9\-\.]+/i', '-', (string) ($period['domain'] ?? 'report'));
			$domain = trim((string) $domain, '-');
			if ($domain === '') {
				$domain = 'report';
			}
			$month = preg_replace('/\s+/', '-', (string) ($period['label'] ?? 'month'));
			$filename = 'icomm-metrix-' . $domain . '-' . $month . '.pdf';

			return [
				'ok' => true,
				'pdf' => $pdf,
				'filename' => sanitize_file_name($filename),
			];
		} catch (Throwable $e) {
			if (defined('WP_DEBUG') && WP_DEBUG && function_exists('error_log')) {
				error_log('icomm-metrix PDF failed: ' . $e->getMessage());
			}
			return ['ok' => false, 'error' => 'pdf_failed', 'detail' => $e->getMessage()];
		}
	}
}
