<?php
/*
 * @Author   yemlihakorkmaz
 * @Copyright yemlihakorkmaz
 */

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

use Dompdf\Dompdf;
use Dompdf\Options;

class SCWC_Dompdf
{

	public function generate_pdf(string $html, int $order_id = 0, bool $save_pdf = true, string $sozlesmeismi = 'korkmaz')
	{

		/* --- 1. Validate order ID ------------------------------------------------ */
		if (!$order_id) {
			$this->debug_log('Invalid order ID provided.');
			return new WP_Error('invalid_data', __('Invalid order ID.', 'wc-korkmaz-contract'));
		}

		/* --- 2. Bootstrap WP_Filesystem ----------------------------------------- */
		if (!function_exists('request_filesystem_credentials')) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		WP_Filesystem();
		global $wp_filesystem;

		if (empty($wp_filesystem) || !is_object($wp_filesystem)) {
			$this->debug_log('WP_Filesystem could not be initialized (check FS_METHOD/credentials).');
			return new WP_Error('fs_unavailable', __('Filesystem API is not available to write PDFs.', 'wc-korkmaz-contract'));
		}

		$upload_dir_info = wp_upload_dir();
		$dir_path = trailingslashit($upload_dir_info['basedir']) . 'korkmazsozlesme';

		/* --- 3. Create directory if missing ------------------------------------- */
		if (!$wp_filesystem->is_dir($dir_path)) {
			if (!$wp_filesystem->mkdir($dir_path, FS_CHMOD_DIR)) {
				$this->debug_log('Could not create PDF directory: ' . $dir_path);
				return new WP_Error('dir_creation_failed', __('Failed to create the PDF directory.', 'wc-korkmaz-contract'));
			}
		}

		/* --- 3b. Write privacy helpers (block indexing/listing) ----------------- */
		$this->ensure_privacy_files($wp_filesystem, $dir_path);

		/* --- 4. Unique file name ------------------------------------------------- */
		$uniqid = function_exists('wp_generate_uuid4') ? wp_generate_uuid4() : uniqid('', true);
		$clean_slug = sanitize_file_name($sozlesmeismi);
		$file_name = "{$clean_slug}-contract-{$order_id}-" . sanitize_file_name($uniqid) . '.pdf';
		$file_path = trailingslashit($dir_path) . $file_name;
		$file_url = trailingslashit($upload_dir_info['baseurl']) . 'korkmazsozlesme/' . $file_name;

		/* --- 5. Render PDF via Dompdf ------------------------------------------- */
		$options = new Options();
		$default_remote_hosts = array_filter(
			array_unique(
				array(
					wp_parse_url(home_url(), PHP_URL_HOST),
					wp_parse_url(site_url(), PHP_URL_HOST),
					wp_parse_url($upload_dir_info['baseurl'], PHP_URL_HOST),
				)
			)
		);
		$allowed_remote_hosts = apply_filters('korkmaz_contract_pdf_allowed_remote_hosts', $default_remote_hosts);
		$allowed_remote_hosts = is_array($allowed_remote_hosts) ? array_filter(array_map('sanitize_text_field', $allowed_remote_hosts)) : array();
		$options->setIsRemoteEnabled(!empty($allowed_remote_hosts));
		if (!empty($allowed_remote_hosts) && method_exists($options, 'setAllowedRemoteHosts')) {
			$options->setAllowedRemoteHosts($allowed_remote_hosts);
		}
		$options->setChroot(plugin_dir_path(__DIR__));
		$options->setTempDir($dir_path);

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

		if ($save_pdf) {
			$pdf_output = $dompdf->output();

			if (!$wp_filesystem->put_contents($file_path, $pdf_output, FS_CHMOD_FILE)) {
				$this->debug_log('PDF rendered but could not be saved: ' . $file_path);
				return new WP_Error('pdf_save_failed', __('Failed to save the PDF file.', 'wc-korkmaz-contract'));
			}

			if (!$wp_filesystem->exists($file_path)) {
				$this->debug_log('PDF saved but file not found: ' . $file_path);
				return new WP_Error('pdf_not_found', __('The PDF file was created but could not be found.', 'wc-korkmaz-contract'));
			}

			$this->debug_log('PDF successfully generated: ' . $file_path);
		}

		return $file_url;
	}

	private function debug_log(string $message): void
	{
		if ((int) get_option('korkmaz_contract_log_enabled', 0) !== 1) {
			return;
		}

		error_log('[Korkmaz Contract] ' . $message); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
	}

	private function ensure_privacy_files($fs, string $dir): void
	{
		$htaccess_path = trailingslashit($dir) . '.htaccess';
		$htaccess_body = "# Auto-generated by Korkmaz Contract\nOptions -Indexes\n<Files \"*.pdf\">\n\t<IfModule mod_authz_core.c>\n\t\tRequire all denied\n\t</IfModule>\n\t<IfModule !mod_authz_core.c>\n\t\tOrder allow,deny\n\t\tDeny from all\n\t</IfModule>\n</Files>\n";

		$current_htaccess = $fs->exists($htaccess_path) ? (string) $fs->get_contents($htaccess_path) : '';
		if (!$fs->exists($htaccess_path) || strpos($current_htaccess, 'Require all denied') === false || strpos($current_htaccess, 'mod_authz_core.c') === false) {
			$fs->put_contents($htaccess_path, $htaccess_body, FS_CHMOD_FILE);
		}

		$index_path = trailingslashit($dir) . 'index.php';
		if (!$fs->exists($index_path)) {
			$fs->put_contents($index_path, "<?php\n// Silence is golden.\n", FS_CHMOD_FILE);
		}
	}
}
