<?php

class SCWC_Public
{
	private $plugin_name;
	private $version;
	private $birinci_sozlesme_link_ismi;
	private $ikinci_sozlesme_link_ismi;
	private $blocks_registered = false;
	private $block_type_registered = false;
	private $classic_hidden_fields_rendered = false;
	private $classic_nonce_rendered = false;

	public function __construct($plugin_name, $version)
	{
		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->birinci_sozlesme_link_ismi = get_option('birinci_sozlesme_link_ismi');
		$this->ikinci_sozlesme_link_ismi = get_option('ikinci_sozlesme_link_ismi');
	}

	private function is_checkout_request(): bool
	{
		if (!class_exists('WooCommerce')) {
			return false;
		}

		if (is_admin() || wp_doing_ajax()) {
			return false;
		}

		// Conditional tags are safe only after main query is initialized.
		if (!did_action('wp')) {
			return false;
		}

		return function_exists('is_checkout') && is_checkout();
	}

	public function enqueue_styles()
	{
		if ($this->is_checkout_request()) {
			wp_enqueue_style(
				$this->plugin_name . '-tingle',
				plugin_dir_url(__FILE__) . 'css/tingle.min.css',
				array(),
				$this->asset_version('css/tingle.min.css'),
				'all'
			);
			wp_enqueue_style(
				$this->plugin_name,
				plugin_dir_url(__FILE__) . 'css/korkmaz_contract-public.css',
				array($this->plugin_name . '-tingle'),
				$this->asset_version('css/korkmaz_contract-public.css'),
				'all'
			);
		}
	}

	public function enqueue_scripts()
	{
		if ($this->is_checkout_request()) {
			$tingle_handle = $this->plugin_name . '_tingle';
			$print_script_handle = $this->plugin_name . '_print';
			$custom_script_handle = $this->plugin_name . '_contracts'; // quicktag bağlı ön yüz güncelleme

			wp_enqueue_script('jquery');

			wp_enqueue_script(
				$tingle_handle,
				plugin_dir_url(__FILE__) . 'js/tingle.min.js',
				array(),
				$this->asset_version('js/tingle.min.js'),
				true
			);

			wp_enqueue_script(
				$print_script_handle,
				plugin_dir_url(__FILE__) . 'js/printThis.js',
				array('jquery'),
				$this->asset_version('js/printThis.js'),
				true
			);

			// Ön yüzde quicktag placeholder’larını dolduran yeni betik
			wp_enqueue_script(
				$custom_script_handle,
				plugin_dir_url(__FILE__) . 'js/checkout-contracts.js',
				array('jquery', $tingle_handle),
				$this->asset_version('js/checkout-contracts.js'),
				true
			);

			// Ayar alan haritalarını JS'e aktar
			$options = get_option('alanlar_options');
			$data_for_js = is_array($options) ? $options : array();
				wp_localize_script($custom_script_handle, 'korkmaz_var', $data_for_js);

				wp_localize_script(
					$custom_script_handle,
					'kc_contracts',
					array(
						'ajax_url' => admin_url('admin-ajax.php'),
						'nonce' => wp_create_nonce('kc_checkout_contracts'),
						'record_admin_warnings' => current_user_can('manage_woocommerce'),
						'strings' => array(
							'required' => __('required', 'wc-korkmaz-contract'),
							'optional' => __('optional', 'wc-korkmaz-contract'),
							'field_billing_first_name' => __('Billing first name', 'wc-korkmaz-contract'),
							'field_billing_last_name' => __('Billing last name', 'wc-korkmaz-contract'),
							'field_billing_company' => __('Billing company', 'wc-korkmaz-contract'),
							'field_billing_tax_number' => __('Billing tax number', 'wc-korkmaz-contract'),
							'field_billing_tax_office' => __('Billing tax office', 'wc-korkmaz-contract'),
							'field_billing_address' => __('Billing address', 'wc-korkmaz-contract'),
							'field_billing_city' => __('Billing city', 'wc-korkmaz-contract'),
							'field_billing_phone' => __('Billing phone', 'wc-korkmaz-contract'),
							'field_billing_email' => __('Billing email', 'wc-korkmaz-contract'),
							'field_national_id' => __('National ID field', 'wc-korkmaz-contract'),
							'field_shipping_first_name' => __('Shipping first name', 'wc-korkmaz-contract'),
							'field_shipping_last_name' => __('Shipping last name', 'wc-korkmaz-contract'),
							'field_shipping_company' => __('Shipping company', 'wc-korkmaz-contract'),
							'field_shipping_address' => __('Shipping address', 'wc-korkmaz-contract'),
							'field_shipping_city' => __('Shipping city', 'wc-korkmaz-contract'),
							'field_payment_method' => __('Payment method', 'wc-korkmaz-contract'),
						),
						'approval_required' => (int) get_option('sozlesme_ozellik_3') === 1,
						'approval_nonce' => wp_create_nonce('kc_contract_action'),
					)
				);

				wp_localize_script(
					$custom_script_handle,
				'kc_modal_strings',
				array(
					'eyebrow' => __('Contract', 'wc-korkmaz-contract'),
					'subtitle' => __('Please review the details carefully.', 'wc-korkmaz-contract'),
					'empty' => __('The contract is not ready yet…', 'wc-korkmaz-contract'),
					'close' => __('Close', 'wc-korkmaz-contract'),
					'title1' => $this->contract_display_name('first'),
					'title2' => $this->contract_display_name('second'),
				)
			);
		}
	}

	private function asset_version(string $relative_path): string
	{
		$path = plugin_dir_path(__FILE__) . ltrim($relative_path, '/');
		if (file_exists($path)) {
			return (string) filemtime($path);
		}

		return (string) $this->version;
	}

		private static function is_logging_enabled(): bool
		{
			return (int) get_option('korkmaz_contract_log_enabled', 0) === 1;
		}

		private function verify_checkout_ajax_nonce(): bool
		{
			if (check_ajax_referer('kc_checkout_contracts', 'nonce', false)) {
				return true;
			}

			status_header(403);
			return false;
		}

	public function sozlesme_goruntule()
	{
		if ($this->is_checkout_request()) {
			$amount = '';
			if (function_exists('WC') && WC()->cart) {
				$amount = WC()->cart->get_total(); // HTML formatlı toplam
			}
			$cart_table = $this->cart_items_table();
			$geo = new WC_Geolocation();
			$musteri_ipadresi = $geo->get_ip_address();
			$musteri_external_ip = '';
			?>
			<textarea name="" id="urunbilgileri" cols="30" rows="10">
				<?php echo esc_textarea($cart_table); ?>
																																				  </textarea>

			<input type="hidden" id="sepettoplami" value="<?php echo esc_attr(wp_strip_all_tags($amount)); ?>" />
			<input type="hidden" id="firmaadi" value="<?php echo esc_attr(get_option('firmaadi')); ?>" />
			<input type="hidden" id="firmaadresi" value="<?php echo esc_attr(get_option('firmaadresi')); ?>" />
			<input type="hidden" id="firmatelno" value="<?php echo esc_attr(get_option('firmatelno')); ?>" />
			<input type="hidden" id="firmaverdaire" value="<?php echo esc_attr(get_option('firmaverdaire')); ?>" />
			<input type="hidden" id="firmaverno" value="<?php echo esc_attr(get_option('firmaverno')); ?>" />
			<input type="hidden" id="odemeyontemiinput" value="" />
			<input type="hidden" id="musteri_ipadresi" value="<?php echo esc_attr($musteri_ipadresi); ?>" />
			<input type="hidden" id="musteri_external_ip" value="<?php echo esc_attr($musteri_external_ip); ?>" />

			<?php
		}
	}

	public function onayla_uyari()
	{
		if ((int) get_option('sozlesme_ozellik_3') !== 1) {
			return;
		}

		if (!isset($_POST['kc_contract_nonce'])) {
			wc_add_notice(esc_html__('The contract approval field could not be found. Please refresh the checkout page or contact the store.', 'wc-korkmaz-contract'), 'error');
			return;
		}

		$nonce = sanitize_text_field(wp_unslash($_POST['kc_contract_nonce']));
		if (!$nonce || !wp_verify_nonce($nonce, 'kc_contract_action')) {
			wc_add_notice(esc_html__('Security check failed. Please refresh the checkout page and try again.', 'wc-korkmaz-contract'), 'error');
			return;
		}

		$approved = isset($_POST['sozlesme_onayla'])
			&& !is_array($_POST['sozlesme_onayla'])
			&& in_array((string) wp_unslash($_POST['sozlesme_onayla']), array('1', 'true', 'yes', 'on'), true);

		if (!$approved) {
			wc_add_notice(esc_html__('Please read and approve the contracts.', 'wc-korkmaz-contract'), 'error');
		}
	}

	public function odeme_ekrani_custom_input_ekle($fields)
	{
		if (get_option('sozlesme_ozellik_6') == 1) {
			$fields['billing']['musteri_tipi'] = array(
				'type' => 'radio',
				'label' => __('Customer Type', 'wc-korkmaz-contract'),
				'class' => array('form-row-wide', 'musteri-tipi-radio'),
				'options' => array(
					'bireysel' => __('Individual', 'wc-korkmaz-contract'),
					'kurumsal' => __('Corporate', 'wc-korkmaz-contract'),
				),
				'default' => 'bireysel',
				'priority' => 20,
			);

			$fields['billing']['shipping_tc'] = array(
				'label' => __('National ID Number', 'wc-korkmaz-contract'),
				'placeholder' => __('11-digit national ID number', 'wc-korkmaz-contract'),
				'class' => array('form-row-wide'),
				'priority' => 33,
				'clear' => true,
				'required' => false,
			);

			$fields['billing']['billing_vergi_dairesi'] = array(
				'label' => __('Tax Office', 'wc-korkmaz-contract'),
				'placeholder' => _x('Tax Office', 'placeholder', 'wc-korkmaz-contract'),
				'class' => array('form-row', 'form-row-first'),
				'required' => false,
				'priority' => 32,
				'clear' => true,
			);

			$fields['billing']['billing_vergi_nosu'] = array(
				'label' => __('Tax Number', 'wc-korkmaz-contract'),
				'placeholder' => __('Tax Number', 'wc-korkmaz-contract'),
				'class' => array('form-row', 'form-row-last'),
				'required' => false,
				'priority' => 32,
				'clear' => true,
			);
		}
		return $fields;
	}

	public function register_block_checkout_fields()
	{
		if (!did_action('init')) {
			add_action('init', array($this, 'register_block_checkout_fields'), 20);
			return;
		}

		if ((int) get_option('sozlesme_ozellik_6', 0) !== 1) {
			return;
		}

		if (!function_exists('woocommerce_register_additional_checkout_field')) {
			return;
		}

		$fields = array(
			array(
				'id' => 'wc-korkmaz-contract/shipping_tc',
				'label' => __('National ID Number', 'wc-korkmaz-contract'),
				'location' => 'order',
				'type' => 'text',
				'required' => false,
				'attributes' => array(
					'autocomplete' => 'off',
					'pattern' => '[0-9]*',
					'maxLength' => '11',
				),
				'sanitize_callback' => static function ($value) {
					return preg_replace('/\D/', '', sanitize_text_field((string) $value));
				},
			),
			array(
				'id' => 'wc-korkmaz-contract/billing_vergi_dairesi',
				'label' => __('Tax Office', 'wc-korkmaz-contract'),
				'location' => 'order',
				'type' => 'text',
				'required' => false,
				'attributes' => array(
					'autocomplete' => 'off',
				),
				'sanitize_callback' => 'sanitize_text_field',
			),
			array(
				'id' => 'wc-korkmaz-contract/billing_vergi_nosu',
				'label' => __('Tax Number', 'wc-korkmaz-contract'),
				'location' => 'order',
				'type' => 'text',
				'required' => false,
				'attributes' => array(
					'autocomplete' => 'off',
					'pattern' => '[0-9]*',
				),
				'sanitize_callback' => static function ($value) {
					return preg_replace('/\D/', '', sanitize_text_field((string) $value));
				},
			),
		);

		foreach ($fields as $field) {
			try {
				woocommerce_register_additional_checkout_field($field);
			} catch (\Throwable $e) {
				$this->debug_log('Block checkout field registration failed: ' . $e->getMessage());
			}
		}
	}

		public function soz_fn_cagir()
		{
			if (!$this->verify_checkout_ajax_nonce()) {
				wp_send_json_error(array('message' => __('Security check failed.', 'wc-korkmaz-contract')), 403);
			}

			$sozlesme1 = isset($_POST['sozlesme1']) ? wp_kses_post(wp_unslash($_POST['sozlesme1'])) : '';
			$sozlesme2 = isset($_POST['sozlesme2']) ? wp_kses_post(wp_unslash($_POST['sozlesme2'])) : '';

		$result = array();
		$result['birinci_sozlesme'] = $sozlesme1;
		$result['ikinci_sozlesme'] = $sozlesme2;

		wp_send_json($result);
	}

		public function metin_getir()
		{
			if (!$this->verify_checkout_ajax_nonce()) {
				wp_send_json_error(array('message' => __('Security check failed.', 'wc-korkmaz-contract')), 403);
			}

			$metin1 = stripslashes(get_option('birinci_sozlesme_metni', ''));
			$metin2 = stripslashes(get_option('ikinci_sozlesme_metni', ''));

		if (empty($metin1) || empty($metin2)) {
			$defaultmetin = get_transient('korkmaz_contract_default_template');

			if (false === $defaultmetin) {
				$response = wp_remote_get(
					'https://yemlihakorkmaz.com/sozlesmeornek.txt',
					array('timeout' => 5)
				);

				if (is_wp_error($response)) {
					$defaultmetin = __('Could not retrieve the sample text.', 'wc-korkmaz-contract');
					self::action_log('metin_getir: remote fetch failed - ' . $response->get_error_message());
				} else {
					$defaultmetin = wp_remote_retrieve_body($response);
					if ('' !== trim((string) $defaultmetin)) {
						set_transient('korkmaz_contract_default_template', $defaultmetin, DAY_IN_SECONDS);
						self::action_log('metin_getir: remote template fetched successfully.');
					} else {
						$defaultmetin = __('Could not retrieve the sample text.', 'wc-korkmaz-contract');
						self::action_log('metin_getir: remote template empty.');
					}
				}
			}

			if (empty($metin1)) {
				$metin1 = $defaultmetin;
			}
			if (empty($metin2)) {
				$metin2 = $defaultmetin;
			}
		}

		wp_send_json(
			array(
				'birinci' => $metin1,
				'ikinci' => $metin2,
			)
		);
	}

		public function cart_summary()
		{
			if (!$this->verify_checkout_ajax_nonce()) {
				wp_send_json_error(array('message' => __('Security check failed.', 'wc-korkmaz-contract')), 403);
			}

			if (function_exists('wc_load_cart')) {
				wc_load_cart();
			}

		if (!function_exists('WC') || !WC()->cart) {
			wp_send_json(
				array(
					'table' => '',
					'total' => '',
				)
			);
		}

		$table = $this->cart_items_table();
		$total = wp_strip_all_tags(WC()->cart->get_total());

		wp_send_json(
			array(
				'table' => $table,
				'total' => $total,
			)
		);
	}

	public function record_missing_checkout_fields()
	{
		if (!current_user_can('manage_woocommerce')) {
			wp_send_json_error(array('message' => __('You do not have permission to record checkout field notices.', 'wc-korkmaz-contract')), 403);
		}

		if (!$this->verify_checkout_ajax_nonce()) {
			wp_send_json_error(array('message' => __('Security check failed.', 'wc-korkmaz-contract')), 403);
		}

		$fields = isset($_POST['fields']) && is_array($_POST['fields'])
			? wp_unslash($_POST['fields'])
			: array();

		$fields = array_values(
			array_unique(
				array_filter(
					array_map(
						static function ($field) {
							return sanitize_text_field((string) $field);
						},
						$fields
					)
				)
			)
		);

		$fields = array_slice($fields, 0, 20);
		$user_id = get_current_user_id();
		$meta_key = 'korkmaz_contract_missing_checkout_fields_notice';

		if (empty($fields)) {
			delete_user_meta($user_id, $meta_key);
			wp_send_json_success();
		}

		update_user_meta(
			$user_id,
			$meta_key,
			array(
				'fields' => $fields,
				'checked_at' => time(),
			)
		);

		wp_send_json_success();
	}

	public function myplugin_ajaxurl()
	{
		if (!$this->is_checkout_request()) {
			return;
		}

		$ajax_url = esc_url_raw(admin_url('admin-ajax.php'));
		?>
		<script type="text/javascript">
			var ajaxurl = <?php echo wp_json_encode($ajax_url); ?>;
		</script>
		<?php
	}

	public function sozlesme_goster_odeme_sayfasi()
	{
		if (get_option('sozlesme_ozellik_3') == 1) {
			$link1 = '<a href="#kc-modal-1" class="kc-contract-link" data-kc-modal="1">' . esc_html($this->contract_display_name('first')) . '</a>';
			$link2 = '<a href="#kc-modal-2" class="kc-contract-link" data-kc-modal="2">' . esc_html($this->contract_display_name('second')) . '</a>';

			$label = sprintf(
				/* translators: 1: First contract link (HTML), 2: Second contract link (HTML) */
				__('I have read and agree to %1$s and %2$s.', 'wc-korkmaz-contract'),
				$link1,
				$link2
			);

			$allowed = array(
				'a' => array(
					'href' => true,
					'class' => true,
					'data-kc-modal' => true,
				),
			);
			?>
			<div class="form-row privacy kc-classic-contracts" id="sozlesme_onayla_field">
				<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox kc-classic-contracts__label">
					<input type="checkbox"
						class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox"
						name="sozlesme_onayla"
						id="sozlesme_onayla"
						value="1"
						required />
					<span class="woocommerce-terms-and-conditions-checkbox-text kc-classic-contracts__text">
						<?php echo wp_kses($label, $allowed); ?>
					</span>
				</label>
				<?php $this->render_classic_checkout_nonce(); ?>
			</div>
			<?php
		}
	}

	private function contract_display_name(string $contract): string
	{
		$raw = 'second' === $contract ? $this->ikinci_sozlesme_link_ismi : $this->birinci_sozlesme_link_ismi;
		$raw = trim(wp_strip_all_tags((string) $raw));

		if ('' !== $raw) {
			return $raw;
		}

		return 'second' === $contract
			? __('Pre-Information Form', 'wc-korkmaz-contract')
			: __('Distance Sales Contract', 'wc-korkmaz-contract');
	}

	private function render_classic_checkout_nonce(): void
	{
		if ($this->classic_nonce_rendered || (int) get_option('sozlesme_ozellik_3') !== 1) {
			return;
		}

		wp_nonce_field('kc_contract_action', 'kc_contract_nonce', false);
		$this->classic_nonce_rendered = true;
	}

	private function render_classic_contract_snapshot_fields(): void
	{
		if ($this->classic_hidden_fields_rendered) {
			return;
		}

		$this->classic_hidden_fields_rendered = true;
		?>
		<div id="manuel_checkout_alanlari" class="kc-classic-contract-meta-fields" aria-hidden="true">
			<textarea name="billing_satis_sozlesme" class="input-text kc-contract-snapshot-field" id="billing_satis_sozlesme" tabindex="-1"></textarea>
			<textarea name="billing_mesafeli_sozlesme" class="input-text kc-contract-snapshot-field" id="billing_mesafeli_sozlesme" tabindex="-1"></textarea>
		</div>
		<?php
	}

	public function view_order_sozlesme_goster($order_id)
	{
		if (get_option('sozlesme_ozellik_5') == 1) {
			$order = wc_get_order($order_id);
			if (!$order) {
				return;
			}

			$birinci_sozlesme = $order->get_meta('birinci_sozlesme_dosya');
			$ikinci_sozlesme = $order->get_meta('ikinci_sozlesme_dosya');

			$pdf_file_name1 = $this->dosya_ismi_al($birinci_sozlesme);
			$pdf_file_name2 = $this->dosya_ismi_al($ikinci_sozlesme);
			$birlink = $pdf_file_name1 ? $this->contract_download_url($order, 'first') : '';
			$ikilink = $pdf_file_name2 ? $this->contract_download_url($order, 'second') : '';
			?>
			<div class="sozlemelertesekkur yemliha">
				<?php if ($pdf_file_name1): ?>
					<a target="_blank" rel="noopener noreferrer"
						href="<?php echo esc_url($birlink); ?>"><?php echo esc_html($this->birinci_sozlesme_link_ismi); ?></a><br>
				<?php endif; ?>
				<?php if ($pdf_file_name2): ?>
					<a target="_blank" rel="noopener noreferrer"
						href="<?php echo esc_url($ikilink); ?>"><?php echo esc_html($this->ikinci_sozlesme_link_ismi); ?></a><br>
				<?php endif; ?>
			</div>
			<?php
		}
	}

	public function dosya_ismi_al($link)
	{
		$path = wp_parse_url((string) $link, PHP_URL_PATH);
		return sanitize_file_name(wp_basename($path ? $path : (string) $link));
	}

	private function contract_file_meta_key(string $contract): string
	{
		return 'second' === $contract ? 'ikinci_sozlesme_dosya' : 'birinci_sozlesme_dosya';
	}

	private function contract_download_url(\WC_Order $order, string $contract): string
	{
		$contract = 'second' === $contract ? 'second' : 'first';
		$order_id = $order->get_id();

		return add_query_arg(
			array(
				'action' => 'korkmaz_contract_download',
				'order_id' => $order_id,
				'contract' => $contract,
				'key' => $order->get_order_key(),
				'_wpnonce' => wp_create_nonce("korkmaz_contract_download_{$order_id}_{$contract}"),
			),
			admin_url('admin-post.php')
		);
	}

	private function contract_file_path_from_url(string $file_url): string
	{
		$file_name = $this->dosya_ismi_al($file_url);
		if ('' === $file_name) {
			return '';
		}

		$upload_dir = wp_upload_dir(null, false, get_current_blog_id());
		$dir = wp_normalize_path(trailingslashit($upload_dir['basedir']) . 'korkmazsozlesme');
		$file_path = wp_normalize_path(trailingslashit($dir) . $file_name);
		$real_dir = realpath($dir);
		$real_file = realpath($file_path);

		if (!$real_dir || !$real_file) {
			return '';
		}

		$real_dir = wp_normalize_path(trailingslashit($real_dir));
		$real_file = wp_normalize_path($real_file);

		if (strpos($real_file, $real_dir) !== 0) {
			return '';
		}

		return $real_file;
	}

	private function current_request_can_access_order(\WC_Order $order): bool
	{
		if (current_user_can('manage_woocommerce') || current_user_can('edit_shop_order', $order->get_id()) || current_user_can('edit_shop_orders')) {
			return true;
		}

		$user_id = get_current_user_id();
		if ($user_id && (int) $order->get_customer_id() === (int) $user_id) {
			return true;
		}

		$key = isset($_GET['key']) ? sanitize_text_field(wp_unslash($_GET['key'])) : '';
		return '' !== $key && hash_equals((string) $order->get_order_key(), $key);
	}

	public function download_contract_pdf()
	{
		$order_id = isset($_GET['order_id']) ? absint($_GET['order_id']) : 0;
		$contract = isset($_GET['contract']) ? sanitize_key(wp_unslash($_GET['contract'])) : '';

		if (!$order_id || !in_array($contract, array('first', 'second'), true)) {
			wp_die(esc_html__('Invalid contract request.', 'wc-korkmaz-contract'), '', array('response' => 400));
		}

		$nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
		if (!wp_verify_nonce($nonce, "korkmaz_contract_download_{$order_id}_{$contract}")) {
			wp_die(esc_html__('Security check failed.', 'wc-korkmaz-contract'), '', array('response' => 403));
		}

		$order = wc_get_order($order_id);
		if (!$order instanceof \WC_Order) {
			wp_die(esc_html__('Order not found.', 'wc-korkmaz-contract'), '', array('response' => 404));
		}

		if (!$this->current_request_can_access_order($order)) {
			wp_die(esc_html__('You do not have permission to view this contract.', 'wc-korkmaz-contract'), '', array('response' => 403));
		}

		$file_url = (string) $order->get_meta($this->contract_file_meta_key($contract), true);
		$file_path = $this->contract_file_path_from_url($file_url);

		if ('' === $file_path || !is_readable($file_path)) {
			wp_die(esc_html__('Contract file not found.', 'wc-korkmaz-contract'), '', array('response' => 404));
		}

		nocache_headers();
		header('Content-Type: application/pdf');
		header('Content-Disposition: inline; filename="' . basename($file_path) . '"');
		header('Content-Length: ' . filesize($file_path));
		readfile($file_path); // phpcs:ignore WordPress.WP.AlternativeFunctions
		exit;
	}

	public function front_sozlesme_goster($order_id)
	{
		if (get_option('sozlesme_ozellik_2') == 1) {
			$order = wc_get_order($order_id);
			if (!$order) {
				return;
			}
			$birinci_sozlesme = $order->get_meta('birinci_sozlesme_dosya');
			$ikinci_sozlesme = $order->get_meta('ikinci_sozlesme_dosya');

			$pdf_file_name1 = $this->dosya_ismi_al($birinci_sozlesme);
			$pdf_file_name2 = $this->dosya_ismi_al($ikinci_sozlesme);
			$birlink = $pdf_file_name1 ? $this->contract_download_url($order, 'first') : '';
			$ikilink = $pdf_file_name2 ? $this->contract_download_url($order, 'second') : '';
			?>
			<div class="sozlemelertesekkur">
				<?php if ($pdf_file_name1): ?>
					<a target="_blank" rel="noopener noreferrer"
						href="<?php echo esc_url($birlink); ?>"><?php echo esc_html($this->birinci_sozlesme_link_ismi); ?></a><br>
				<?php endif; ?>
				<?php if ($pdf_file_name2): ?>
					<a target="_blank" rel="noopener noreferrer"
						href="<?php echo esc_url($ikilink); ?>"><?php echo esc_html($this->ikinci_sozlesme_link_ismi); ?></a><br>
				<?php endif; ?>
			</div>
			<?php
		}
	}

	public function tc_numara_dogrula()
	{
		if (get_option('sozlesme_ozellik_6') == 1) {
			$raw_tc = $this->first_request_value(
				$_POST,
				array(
					'shipping_tc',
					'billing_tc_number',
				)
			);
			$tcno = preg_replace('/\D/', '', $raw_tc); // Only digits

			$tcdogrula = $this->is_valid_tckn($tcno);
			if (!empty($tcno) && !$tcdogrula) {
				wc_add_notice(__('Please enter a valid National ID number.', 'wc-korkmaz-contract'), 'error');
			}
		}
	}

	private function is_valid_tckn(string $tckn): bool
	{
		$tckn = trim($tckn);

		if (strlen($tckn) !== 11 || !ctype_digit($tckn) || $tckn[0] === '0') {
			return false;
		}

		$digits = array_map('intval', str_split($tckn));

		$d10 = (($digits[0] + $digits[2] + $digits[4] + $digits[6] + $digits[8]) * 7
			- ($digits[1] + $digits[3] + $digits[5] + $digits[7])) % 10;

		if ($d10 !== $digits[9]) {
			return false;
		}

		$d11 = array_sum(array_slice($digits, 0, 10)) % 10;

		return $d11 === $digits[10];
	}

	public function sozlesme_olustur_pdf($order)
	{
		self::action_log('sozlesme_olustur_pdf() START');

		if (is_numeric($order)) {
			$order = wc_get_order($order);
			self::action_log('Numeric param → wc_get_order() used.');
		}

		if (!($order instanceof WC_Order)) {
			self::action_log('Invalid $order → aborted.');
			return;
		}

		$order_id = $order->get_id();
		self::action_log(sprintf('Order ID: %d', $order_id));

		$this->store_server_contract_snapshots($order);

		$birincisozlesmeismi = sanitize_title($this->contract_display_name('first'));
		$ikincisozlesmeismi = sanitize_title($this->contract_display_name('second'));

		$existing_first_pdf = (string) $order->get_meta('birinci_sozlesme_dosya', true);
		if ($this->contract_file_path_from_url($existing_first_pdf)) {
			self::action_log('First contract PDF already exists; skipped generation.');
		} else {
			self::action_log('Generating first contract PDF…');
			$birinci_sozlesme = $this->pdf_url($order_id, '_billing_satis_sozlesme', $birincisozlesmeismi);

			if (is_wp_error($birinci_sozlesme)) {
				self::action_log('First contract error: ' . $birinci_sozlesme->get_error_message());
			} else {
				$order->update_meta_data('birinci_sozlesme_dosya', $birinci_sozlesme);
				$order->save();
				self::action_log('First contract saved: ' . $birinci_sozlesme);
			}
		}

		$existing_second_pdf = (string) $order->get_meta('ikinci_sozlesme_dosya', true);
		if ($this->contract_file_path_from_url($existing_second_pdf)) {
			self::action_log('Second contract PDF already exists; skipped generation.');
		} else {
			self::action_log('Generating second contract PDF…');
			$ikinci_sozlesme = $this->pdf_url($order_id, '_billing_mesafeli_sozlesme', $ikincisozlesmeismi);

			if (is_wp_error($ikinci_sozlesme)) {
				self::action_log('Second contract error: ' . $ikinci_sozlesme->get_error_message());
			} else {
				$order->update_meta_data('ikinci_sozlesme_dosya', $ikinci_sozlesme);
				$order->save();
				self::action_log('Second contract saved: ' . $ikinci_sozlesme);
			}
		}

		self::action_log('sozlesme_olustur_pdf() END — Order #' . $order_id);
	}

	public static function action_log($text)
	{
		if (!self::is_logging_enabled()) {
			return;
		}

		$upload_dir = wp_upload_dir(null, false, get_current_blog_id());
		$log_dir = trailingslashit($upload_dir['basedir']) . 'korkmazsozlesme';

		if (!wp_mkdir_p($log_dir)) {
			error_log('[Korkmaz Contract] Failed to create log dir: ' . $log_dir); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
			return;
		}

		$log_file = trailingslashit($log_dir) . 'action_log.log';
		$log_message = '[' . gmdate('Y-m-d H:i:s') . '] ' . $text . PHP_EOL;

		if (is_writable($log_dir)) {
			file_put_contents($log_file, $log_message, FILE_APPEND | LOCK_EX); // phpcs:ignore WordPress.WP.AlternativeFunctions
		} else {
			error_log('[Korkmaz Contract] Log dir not writable: ' . $log_dir . ' | Message: ' . $text); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
		}
	}

	public function pdf_url($order_id, $ismi, $sozlesmeadi)
	{
		if (empty($order_id) || empty($ismi) || empty($sozlesmeadi)) {
			$this->debug_log("[pdf_url] Missing params: order_id={$order_id}, meta_key={$ismi}, name={$sozlesmeadi}");
			return new WP_Error('missing_params', __('Required parameters are missing.', 'wc-korkmaz-contract'));
		}

		$icerik = $this->kc_get_order_meta($order_id, $ismi);

		if (empty($icerik)) {
			$this->debug_log("[pdf_url] Empty content. order_id={$order_id}, meta_key={$ismi}");
			return new WP_Error('empty_content', __('No content found for PDF.', 'wc-korkmaz-contract'));
		}

		$order_obj = wc_get_order($order_id);
		if ($order_obj instanceof WC_Order) {
			$icerik = $this->apply_order_tokens($icerik, $order_obj);
		} else {
			$this->debug_log("[pdf_url] Order not found for token replacement. order_id={$order_id}");
		}

		$icerik = $this->render_shortcodes($icerik);

		$pdfolustur = new SCWC_Dompdf();
		$pdf_html_metin = $this->pdf_metni_hazirla($icerik);

		if (empty($pdf_html_metin)) {
			$this->debug_log("[pdf_url] Could not generate HTML content. order_id={$order_id}");
			return new WP_Error('html_error', __('Could not generate HTML for PDF.', 'wc-korkmaz-contract'));
		}

		$sozlesme = $pdfolustur->generate_pdf($pdf_html_metin, $order_id, true, $sozlesmeadi);

		if (is_wp_error($sozlesme)) {
			$this->debug_log('[pdf_url] PDF error: ' . $sozlesme->get_error_message());
			return $sozlesme;
		}

		return $sozlesme;
	}

	private function debug_log(string $msg): void
	{
		if (!self::is_logging_enabled()) {
			return;
		}

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

	private function apply_order_tokens(string $metin, \WC_Order $order): string
	{
		try {
			return strtr($metin, $this->contract_replacements($order));
		} catch (\Throwable $e) {
			$this->debug_log('apply_order_tokens error: ' . $e->getMessage());
			return $metin;
		}
	}

	private function clean_text_for_contract($value): string
	{
		return esc_html(wp_strip_all_tags((string) $value));
	}

	private function join_contract_parts(array $parts): string
	{
		$parts = array_filter(
			array_map(
				static function ($part) {
					return trim((string) $part);
				},
				$parts
			)
		);

		return $this->clean_text_for_contract(implode(', ', $parts));
	}

	private function country_label(string $country): string
	{
		if ('' === $country) {
			return '';
		}

		if (function_exists('WC') && WC()->countries) {
			$countries = WC()->countries->get_countries();
			if (isset($countries[$country])) {
				return (string) $countries[$country];
			}
		}

		return $country;
	}

	private function state_label(string $state, string $country): string
	{
		if ('' === $state) {
			return '';
		}

		if (function_exists('WC') && WC()->countries) {
			$states = WC()->countries->get_states($country);
			if (is_array($states) && isset($states[$state])) {
				return (string) $states[$state];
			}

			$normalized_state = strtoupper($country) . $state;
			if (is_array($states) && isset($states[$normalized_state])) {
				return (string) $states[$normalized_state];
			}
		}

		return $state;
	}

	private function billing_tax_office(\WC_Order $order, string $billing_state_label): string
	{
		$tax_office = $this->first_order_meta(
			$order,
			array(
				'_billing_tax_office',
				'billing_tax_office',
				'_billing_vergi_dairesi',
				'billing_vergi_dairesi',
				'_wc_other/wc-korkmaz-contract/billing_vergi_dairesi',
				'_wc_other/wc-korkmaz-contract/billing_tax_office',
			)
		);

		if ('' === $tax_office) {
			$tax_office = $billing_state_label;
		}

		return $this->clean_text_for_contract($tax_office);
	}

	private function first_order_meta(\WC_Order $order, array $keys): string
	{
		foreach ($keys as $key) {
			$value = trim((string) $order->get_meta($key, true));
			if ('' !== $value) {
				return $value;
			}
		}

		return '';
	}

	private function contract_date(\WC_Order $order): string
	{
		$date = $order->get_date_created();
		$timestamp = $date instanceof \WC_DateTime ? $date->getTimestamp() : time();

		return $this->clean_text_for_contract(wp_date(get_option('date_format'), $timestamp));
	}

	private function contract_replacements(\WC_Order $order): array
	{
		$billing_name = trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name());
		$shipping_name = trim($order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name());
		$billing_country = $this->country_label((string) $order->get_billing_country());
		$billing_state = $this->state_label((string) $order->get_billing_state(), (string) $order->get_billing_country());
		$shipping_country = $this->country_label((string) $order->get_shipping_country());
		$shipping_state = $this->state_label((string) $order->get_shipping_state(), (string) $order->get_shipping_country());
		$billing_tax_office = $this->billing_tax_office($order, $billing_state);
		$billing_address = $this->join_contract_parts(
			array(
				$order->get_billing_address_1(),
				$order->get_billing_address_2(),
				$order->get_billing_city(),
				$billing_state,
				$order->get_billing_postcode(),
				$billing_country,
			)
		);
		$shipping_address = $this->join_contract_parts(
			array(
				$order->get_shipping_address_1(),
				$order->get_shipping_address_2(),
				$order->get_shipping_city(),
				$shipping_state,
				$order->get_shipping_postcode(),
				$shipping_country,
			)
		);

		if ('' === $shipping_address) {
			$shipping_address = $billing_address;
		}

		$company_info = sprintf(
			'%1$s, %2$s: %3$s, %4$s: %5$s, %6$s: %7$s, %8$s: %9$s',
			$this->clean_text_for_contract(get_option('firmaadi')),
			esc_html__('Address', 'wc-korkmaz-contract'),
			$this->clean_text_for_contract(get_option('firmaadresi')),
			esc_html__('Phone', 'wc-korkmaz-contract'),
			$this->clean_text_for_contract(get_option('firmatelno')),
			esc_html__('Tax Office', 'wc-korkmaz-contract'),
			$this->clean_text_for_contract(get_option('firmaverdaire')),
			esc_html__('Tax Number', 'wc-korkmaz-contract'),
			$this->clean_text_for_contract(get_option('firmaverno'))
		);

		$national_id = $this->first_order_meta(
			$order,
			array(
				'_billing_tc_number',
				'billing_tc_number',
				'_shipping_tc',
				'shipping_tc',
				'_wc_other/wc-korkmaz-contract/shipping_tc',
				'_wc_other/wc-korkmaz-contract/billing_tc_number',
			)
		);

		$tax_number = $this->first_order_meta(
			$order,
			array(
				'_billing_tax_number',
				'billing_tax_number',
				'_billing_vergi_nosu',
				'billing_vergi_nosu',
				'_wc_other/wc-korkmaz-contract/billing_vergi_nosu',
				'_wc_other/wc-korkmaz-contract/billing_tax_number',
			)
		);

		$replacements = array(
			'[adsoyad]' => $this->clean_text_for_contract($billing_name),
			'[adi]' => $this->clean_text_for_contract($order->get_billing_first_name()),
			'[soyadi]' => $this->clean_text_for_contract($order->get_billing_last_name()),
			'[firmaadi]' => $this->clean_text_for_contract(get_option('firmaadi')),
			'[firmaadresi]' => $this->clean_text_for_contract(get_option('firmaadresi')),
			'[firmatelno]' => $this->clean_text_for_contract(get_option('firmatelno')),
			'[firmaverdaire]' => $this->clean_text_for_contract(get_option('firmaverdaire')),
			'[firmaverno]' => $this->clean_text_for_contract(get_option('firmaverno')),
			'[alicisirket]' => $this->clean_text_for_contract($order->get_billing_company()),
			'[alicisirketvergino]' => $this->clean_text_for_contract($tax_number),
			'[alicisirketvergidairesi]' => $billing_tax_office,
			'[sirketbilgileri]' => wp_kses_post($company_info),
			'[adres]' => $billing_address,
			'[telefon]' => $this->clean_text_for_contract($order->get_billing_phone()),
			'[email]' => $this->clean_text_for_contract($order->get_billing_email()),
			'[tc]' => $this->clean_text_for_contract($national_id),
			'[satin_alinan_urunler]' => $this->order_items_table($order),
			'[sepettoplami]' => $this->clean_text_for_contract($order->get_formatted_order_total()),
			'[aliciadsoyad]' => $this->clean_text_for_contract($shipping_name ?: $billing_name),
			'[alicisirketismi]' => $this->clean_text_for_contract($order->get_shipping_company() ?: $order->get_billing_company()),
			'[aliciadres]' => $billing_address,
			'[kargo_adress]' => $shipping_address,
			'[ipadresibilgisi]' => $this->clean_text_for_contract($order->get_customer_ip_address()),
			'[odemeyontemi]' => $this->clean_text_for_contract($order->get_payment_method_title()),
			'[tarih]' => $this->contract_date($order),
		);

		$aliases = array(
			'[customer_full_name]' => '[adsoyad]',
			'[customer_first_name]' => '[adi]',
			'[customer_last_name]' => '[soyadi]',
			'[company_name]' => '[firmaadi]',
			'[company_address]' => '[firmaadresi]',
			'[company_phone]' => '[firmatelno]',
			'[company_tax_office]' => '[firmaverdaire]',
			'[company_tax_number]' => '[firmaverno]',
			'[customer_company]' => '[alicisirket]',
			'[customer_company_tax_number]' => '[alicisirketvergino]',
			'[customer_company_tax_office]' => '[alicisirketvergidairesi]',
			'[company_info]' => '[sirketbilgileri]',
			'[customer_address]' => '[adres]',
			'[billing_address]' => '[adres]',
			'[buyer_address]' => '[aliciadres]',
			'[phone]' => '[telefon]',
			'[email_address]' => '[email]',
			'[national_id]' => '[tc]',
			'[purchased_products]' => '[satin_alinan_urunler]',
			'[cart_total]' => '[sepettoplami]',
			'[shipping_full_name]' => '[aliciadsoyad]',
			'[shipping_company]' => '[alicisirketismi]',
			'[shipping_address]' => '[kargo_adress]',
			'[delivery_address]' => '[kargo_adress]',
			'[kargo_adresi]' => '[kargo_adress]',
			'[customer_ip]' => '[ipadresibilgisi]',
			'[payment_method]' => '[odemeyontemi]',
			'[date]' => '[tarih]',
			'[contract_date]' => '[tarih]',
		);

		foreach ($aliases as $alias => $canonical) {
			if (isset($replacements[$canonical])) {
				$replacements[$alias] = $replacements[$canonical];
			}
		}

		return $replacements;
	}

	private function build_contract_snapshot(\WC_Order $order, string $option_key): string
	{
		$template = (string) get_option($option_key, '');
		if ('' === trim($template)) {
			return '';
		}

		$content = strtr(stripslashes($template), $this->contract_replacements($order));
		$content = $this->render_shortcodes($content);

		return wp_kses_post($content);
	}

	private function store_server_contract_snapshots(\WC_Order $order): void
	{
		$has_existing_pdf = $this->contract_file_path_from_url((string) $order->get_meta('birinci_sozlesme_dosya', true))
			|| $this->contract_file_path_from_url((string) $order->get_meta('ikinci_sozlesme_dosya', true));

		if ($has_existing_pdf) {
			self::action_log('Existing contract PDF found; server snapshot update skipped.');
			return;
		}

		$map = array(
			'_billing_satis_sozlesme' => 'birinci_sozlesme_metni',
			'_billing_mesafeli_sozlesme' => 'ikinci_sozlesme_metni',
		);
		$changed = false;

		foreach ($map as $meta_key => $option_key) {
			$snapshot = $this->build_contract_snapshot($order, $option_key);
			if ('' === trim(wp_strip_all_tags($snapshot))) {
				continue;
			}

			$order->update_meta_data($meta_key, $snapshot);
			$changed = true;
			self::action_log(sprintf('Server contract snapshot stored: %s', $meta_key));
		}

		if ($changed) {
			$order->update_meta_data('_korkmaz_contract_snapshot_version', $this->version);
			$order->save();
		}
	}

	private function render_shortcodes(string $text, bool $trusted_source = true): string
	{
		try {
			if (!$trusted_source) {
				$allowed_tags = apply_filters('korkmaz_contract_frontend_shortcode_allowlist', array());
				$allowed_tags = is_array($allowed_tags) ? array_filter(array_map('sanitize_key', $allowed_tags)) : array();

				if (empty($allowed_tags)) {
					return $text;
				}

				global $shortcode_tags;
				$original_shortcode_tags = is_array($shortcode_tags) ? $shortcode_tags : array();
				$shortcode_tags = array_intersect_key($original_shortcode_tags, array_flip($allowed_tags));
			}

			$text = shortcode_unautop($text);
			$rendered = do_shortcode($text);

			if (!$trusted_source) {
				$shortcode_tags = $original_shortcode_tags;
			}

			// PDF icinde the_content fallback kullanilmaz; harici icerik enjekte edilmesini engeller.
			return (string) $rendered;
		} catch (\Throwable $e) {
			if (!$trusted_source && isset($original_shortcode_tags)) {
				$shortcode_tags = $original_shortcode_tags;
			}

			$this->debug_log('render_shortcodes error: ' . $e->getMessage());
			return $text;
		}
	}

	private function cart_items_table(): string
	{
		if (!function_exists('WC') || !WC()->cart) {
			return '';
		}

		$items = WC()->cart->get_cart();
		if (empty($items)) {
			return '';
		}

		$currency = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : '';
		$total_html = WC()->cart->get_total();

		ob_start();
		?>
		<table class="scwc-order-items" style="width:100%;border-collapse:collapse;margin-top:10px;">
			<thead>
				<tr>
					<th style="border:1px solid #BDC3C7;padding:6px;text-align:left;">
						<?php esc_html_e('Product', 'wc-korkmaz-contract'); ?>
					</th>
					<th style="border:1px solid #BDC3C7;padding:6px;text-align:left;">
						<?php esc_html_e('Quantity', 'wc-korkmaz-contract'); ?>
					</th>
					<th style="border:1px solid #BDC3C7;padding:6px;text-align:left;">
						<?php esc_html_e('Total', 'wc-korkmaz-contract'); ?>
					</th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ($items as $item):
					$product = $item['data'] ?? null;
					$product_name = $product ? $product->get_name() : ($item['name'] ?? '');
					$qty = isset($item['quantity']) ? (int) $item['quantity'] : 0;
					$line_total = (float) ($item['line_total'] ?? 0) + (float) ($item['line_tax'] ?? 0);
					$meta_html = wc_get_formatted_cart_item_data($item, true);
					?>
					<tr>
						<td style="border:1px solid #BDC3C7;padding:6px;">
							<?php echo esc_html($product_name); ?>
							<?php if (!empty($meta_html)): ?>
								<div style="margin-top:6px;"><?php echo wp_kses_post($meta_html); ?></div>
							<?php endif; ?>
						</td>
						<td style="border:1px solid #BDC3C7;padding:6px;"><?php echo esc_html($qty); ?></td>
						<td style="border:1px solid #BDC3C7;padding:6px;">
							<?php echo wp_kses_post(wc_price($line_total, array('currency' => $currency))); ?>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
			<?php if (!empty($total_html)): ?>
				<tfoot>
					<tr>
						<th colspan="2" style="border:1px solid #BDC3C7;padding:6px;text-align:left;">
							<?php esc_html_e('Total', 'wc-korkmaz-contract'); ?>
						</th>
						<th style="border:1px solid #BDC3C7;padding:6px;text-align:left;">
							<?php echo wp_kses_post($total_html); ?>
						</th>
					</tr>
				</tfoot>
			<?php endif; ?>
		</table>
		<?php
		return (string) ob_get_clean();
	}

	private function order_items_table(\WC_Order $order): string
	{
		$items = $order->get_items();
		if (empty($items)) {
			return '';
		}

		ob_start();
		?>
		<table class="scwc-order-items" style="width:100%;border-collapse:collapse;margin-top:10px;">
			<thead>
				<tr>
					<th style="border:1px solid #BDC3C7;padding:6px;text-align:left;">

						<?php esc_html_e('Product', 'wc-korkmaz-contract'); ?>
					</th>

					<th style="border:1px solid #BDC3C7;padding:6px;text-align:left;">

						<?php esc_html_e('Quantity', 'wc-korkmaz-contract'); ?>
					</th>
					<th style="border:1px solid #BDC3C7;padding:6px;text-align:left;">
						<?php esc_html_e('Total', 'wc-korkmaz-contract'); ?>
					</th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ($items as $item):
					$product = $item->get_product();
					$product_name = $product ? $product->get_name() : $item->get_name();
					$qty = $item->get_quantity();
					$total = $item->get_total() + $item->get_total_tax();

					$meta_lines = array();
					foreach ($item->get_formatted_meta_data() as $meta) {
						$meta_lines[] = wp_strip_all_tags($meta->display_key . ': ' . $meta->display_value);
					}
					?>

					<tr>
						<td style="border:1px solid #BDC3C7;padding:6px;">
							<?php echo esc_html($product_name); ?>
							<?php if (!empty($meta_lines)): ?>
								<ul style="margin:6px 0 0 12px;padding:0;list-style:disc;">
									<?php foreach ($meta_lines as $line): ?>
										<li style="margin:0;padding:0;"><?php echo esc_html($line); ?></li>
									<?php endforeach; ?>
								</ul>
							<?php endif; ?>
						</td>
						<td style="border:1px solid #BDC3C7;padding:6px;"><?php echo esc_html($qty); ?></td>
						<td style="border:1px solid #BDC3C7;padding:6px;">
							<?php echo wp_kses_post(wc_price($total, array('currency' => $order->get_currency()))); ?>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php
		return (string) ob_get_clean();
	}

	private function kc_get_order_meta($order_id, $key)
	{
		$order = wc_get_order($order_id);
		return $order ? $order->get_meta($key, true) : '';
	}

	public function pdf_metni_hazirla($metin)
	{
		$output = $this->pdf_metin_icerigi($metin);

		if (empty($output)) {
			$this->debug_log('PDF content is empty!');
		} else {
			$this->debug_log('PDF content generated successfully.');
		}

		return $output;
	}

	public function pdf_metin_icerigi(string $metin)
	{
		$font_path = wp_normalize_path(plugin_dir_path(__DIR__) . 'assets/fonts/DejaVuSans.ttf');
		if (!file_exists($font_path)) {
			$this->debug_log('PDF font missing: ' . $font_path);
		}

		$html = '<!DOCTYPE html><html lang="en"><head>';
		$html .= '<meta charset="UTF-8">';
		$html .= '<style>
			@page { margin:40px; }
			@font-face {
				font-family:"DejaVu Sans";
				src:url("file://' . $font_path . '") format("truetype");
				font-weight:normal;
				font-style:normal;
			}
			body   { font-family:"DejaVu Sans", sans-serif; font-size:12px; color:#333; }
			h1     { font-size:18px; text-align:center; color:#2C3E50; margin:0 0 10px; }
			h2     { font-size:14px; color:#2980B9; border-bottom:2px solid #2980B9; padding-bottom:5px; margin:20px 0 10px; }
			p      { line-height:1.5; margin:0 0 8px; }
			table  { width:100%; border-collapse:collapse; margin-top:15px; }
			th,td  { border:1px solid #BDC3C7; padding:8px; text-align:left; font-size:12px; }
			th     { background:#ECF0F1; font-weight:bold; }
			.contract-box { border:1px solid #BDC3C7; background:#F8F9F9; padding:10px; margin-top:15px; }
			.footer { margin-top:30px; font-size:10px; text-align:center; color:#777; }
		</style>';
		$html .= '</head><body>';
		$html .= $metin; // içerik daha önce wp_kses_post ile süzülmüş geliyor
		$html .= '</body></html>';

		return $html;
	}

	public function siparis_mail_ekle($attachments, $email_id, $order, $email)
	{
		if (get_option('sozlesme_ozellik_4') != 1) {
			return $attachments;
		}

		$maildurum = str_replace('_', '-', sanitize_key((string) get_option('sozlesme_mail_durumu', 'completed')));
		if ('new-order' === $maildurum) {
			$maildurum = 'pending';
		}
		$order_obj = null;

		if ($order instanceof WC_Order) {
			$order_obj = $order;
		} elseif (is_numeric($order)) {
			$order_obj = wc_get_order($order);
		} elseif (is_object($order) && !empty($order->id)) {
			$order_obj = wc_get_order($order->id);
		}

		if (!$order_obj instanceof WC_Order) {
			$this->debug_log('Valid order not found or not a WC_Order - email type: ' . $email_id);
			return $attachments;
		}

		$durum = $order_obj->get_status();

		if ($durum !== $maildurum) {
			$this->debug_log("Order status ({$durum}) does not match required status ({$maildurum}).");
			return $attachments;
		} else {
			$this->debug_log("Order status ok: {$durum}");
		}

		$upload_dir = wp_upload_dir(null, false, get_current_blog_id());
		$sozlesme_dosyalari = array(
			'birinci_sozlesme_dosya',
			'ikinci_sozlesme_dosya',
		);

		foreach ($sozlesme_dosyalari as $meta_key) {
			$sozlesme = $order_obj->get_meta($meta_key, true);
			if (!empty($sozlesme) && !is_wp_error($sozlesme)) {
				$dosya_adi = $this->dosya_ismi_al($sozlesme);
				$pdf_file_path = trailingslashit($upload_dir['basedir']) . 'korkmazsozlesme/' . $dosya_adi;
				if (file_exists($pdf_file_path)) {
					$attachments[] = $pdf_file_path;
					$this->debug_log("Attached: {$pdf_file_path}");
				} else {
					$this->debug_log("File not found: {$pdf_file_path}");
				}
			} else {
				$this->debug_log("Contract meta missing or invalid: {$meta_key}");
			}
		}

		return $attachments;
	}

	public function sozlesme_block()
	{
		$this->register_blocks_integration();
	}

	public function register_blocks_integration()
	{
		if ($this->blocks_registered) {
			return;
		}

		$path = plugin_dir_path(__DIR__);

		require_once $path . '/includes/korkmaz-blocks-integration.php';
		require_once $path . '/includes/korkmaz-extend-store-endpoint.php';

		Korkmaz_Blocks_Extend_Store_Endpoint::init();

		add_action(
			'woocommerce_blocks_checkout_block_registration',
			function ($integration_registry) {
				$integration_registry->register(new Korkmaz_Blocks_Integration());
			}
		);

		$this->register_contract_block_type();

		$this->blocks_registered = true;
	}

	public function register_contract_block_type()
	{
		if ($this->block_type_registered) {
			return;
		}

		if (!did_action('init')) {
			add_action('init', array($this, 'register_contract_block_type'), 20);
			return;
		}

		// Frontend'de is_feed doing_it_wrong notice'ini onlemek icin block type kaydini wp sonrasi yap.
		if (!is_admin() && !wp_doing_ajax() && !wp_doing_cron() && !(defined('REST_REQUEST') && REST_REQUEST) && !did_action('wp')) {
			add_action('wp', array($this, 'register_contract_block_type'), 1);
			return;
		}

		$path = plugin_dir_path(__DIR__);
		register_block_type_from_metadata($path . '/build/js/block');
		$this->block_type_registered = true;
	}

	public function register_Irem_block_category($categories)
	{
		return array_merge(
			$categories,
			array(
				array(
					'slug' => 'irem',
					'title' => __('Irem Blocks', 'wc-korkmaz-contract'),
				),
			)
		);
	}

		public function modalicergiduzenleme()
		{
			if (!$this->verify_checkout_ajax_nonce()) {
				status_header(403);
				wp_die(esc_html__('Security check failed.', 'wc-korkmaz-contract'));
			}

			$metin = isset($_POST['metin'])
				? wp_kses_post(wp_unslash($_POST['metin']))
			: '';

		$metin = $this->render_shortcodes($metin, false);

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo wp_kses_post($metin);

		wp_die();
	}

	public function custom_order_meta_register(\WC_Order $order, array $data = array())
	{
		$merged = array_merge($data, $_POST);
		$this->save_contract_meta($order, $merged);
		$this->save_customer_identity_meta($order, $merged);
	}

	public function maybe_auto_insert_checkout_block()
	{
		if (!function_exists('wc_get_page_id')) {
			return;
		}

		$flag_key = 'korkmaz_contract_block_layout_version';
		$current_version = (string) $this->version;
		$layout_version = $current_version . ':contracts-after-terms';
		if (get_option($flag_key, '') === $layout_version) {
			return;
		}

		$checkout_page_id = (int) wc_get_page_id('checkout');
		if ($checkout_page_id <= 0) {
			return;
		}

		$post = get_post($checkout_page_id);
		if (!$post instanceof \WP_Post || $post->post_status !== 'publish') {
			return;
		}

		$content = (string) $post->post_content;
		if ($content === '') {
			return;
		}

		// Classic checkout shortcode page: keep untouched.
		if (strpos($content, '[woocommerce_checkout]') !== false) {
			update_option($flag_key, $layout_version, false);
			return;
		}

		// Only block-based checkout pages are auto-patched.
		if (strpos($content, 'wp:woocommerce/checkout') === false) {
			update_option($flag_key, $layout_version, false);
			return;
		}

		$updated = $this->normalize_checkout_contract_block_position($content);
		if ($updated === $content) {
			update_option($flag_key, $layout_version, false);
			return;
		}

		$result = wp_update_post(
			array(
				'ID' => $checkout_page_id,
				'post_content' => wp_slash($updated),
			),
			true
		);

		if (is_wp_error($result)) {
			$this->debug_log('maybe_auto_insert_checkout_block error: ' . $result->get_error_message());
			return;
		}

		update_option($flag_key, $layout_version, false);
		self::action_log('Block checkout contract block positioned before checkout terms.');
	}

	private function normalize_checkout_contract_block_position(string $content): string
	{
		if (!function_exists('parse_blocks') || !function_exists('serialize_blocks')) {
			return $content;
		}

		$blocks = parse_blocks($content);
		if (!is_array($blocks) || empty($blocks)) {
			return $content;
		}

		$changed = false;
		$blocks = $this->normalize_contract_block_position_in_blocks($blocks, $changed);

		return $changed ? serialize_blocks($blocks) : $content;
	}

	private function normalize_contract_block_position_in_blocks(array $blocks, bool &$changed): array
	{
		foreach ($blocks as &$block) {
			if (!is_array($block)) {
				continue;
			}

			$block_name = isset($block['blockName']) ? (string) $block['blockName'] : '';
			if ('woocommerce/checkout-fields-block' === $block_name) {
				$inner_blocks = isset($block['innerBlocks']) && is_array($block['innerBlocks'])
					? $block['innerBlocks']
					: array();

				$block['innerBlocks'] = $this->normalize_checkout_fields_inner_blocks($inner_blocks, $changed);
				continue;
			}

			if (!empty($block['innerBlocks']) && is_array($block['innerBlocks'])) {
				$block['innerBlocks'] = $this->normalize_contract_block_position_in_blocks($block['innerBlocks'], $changed);
			}
		}
		unset($block);

		return $blocks;
	}

	private function normalize_checkout_fields_inner_blocks(array $inner_blocks, bool &$changed): array
	{
		$contract_block = null;
		$without_contract = array();
		$contract_count = 0;
		$original_contract_index = null;

		foreach ($inner_blocks as $index => $block) {
			$block_name = is_array($block) && isset($block['blockName']) ? (string) $block['blockName'] : '';

			if ('irem/ozel-sozlesmeler' === $block_name) {
				$contract_count++;

				if (null === $contract_block) {
					$contract_block = $block;
					$original_contract_index = count($without_contract);
				}

				continue;
			}

			$without_contract[] = $block;
		}

		if (null === $contract_block) {
			$contract_block = $this->get_default_contract_checkout_block();
			$changed = true;
		}

		if ($contract_count > 1) {
			$changed = true;
		}

		$target_index = count($without_contract);
		$terms_index = null;
		$actions_index = null;
		foreach ($without_contract as $index => $block) {
			$block_name = is_array($block) && isset($block['blockName']) ? (string) $block['blockName'] : '';

			if ('woocommerce/checkout-terms-block' === $block_name) {
				$terms_index = $index;
				continue;
			}

			if ('woocommerce/checkout-actions-block' === $block_name && null === $actions_index) {
				$actions_index = $index;
			}
		}

		if (null !== $terms_index) {
			$target_index = $terms_index + 1;
		} elseif (null !== $actions_index) {
			$target_index = $actions_index;
		}

		if (null !== $original_contract_index && $original_contract_index !== $target_index) {
			$changed = true;
		}

		array_splice($without_contract, $target_index, 0, array($contract_block));

		return $without_contract;
	}

	private function get_default_contract_checkout_block(): array
	{
		$blocks = parse_blocks('<!-- wp:irem/ozel-sozlesmeler /-->');

		return isset($blocks[0]) && is_array($blocks[0])
			? $blocks[0]
			: array(
				'blockName' => 'irem/ozel-sozlesmeler',
				'attrs' => array(),
				'innerBlocks' => array(),
				'innerHTML' => '',
				'innerContent' => array(),
			);
	}

	private function save_contract_meta(\WC_Order $order, array $payload)
	{
		$map = array(
			'billing_satis_sozlesme' => '_billing_satis_sozlesme',
			'billing_mesafeli_sozlesme' => '_billing_mesafeli_sozlesme',
		);

		foreach ($map as $in_key => $meta_key) {
			$raw = $payload[$in_key] ?? '';
			if (is_array($raw) || $raw === '') {
				self::action_log(sprintf('%s field empty; skipped.', $in_key));
				continue;
			}

			$value = wp_kses_post(wp_unslash($raw));
			$order->update_meta_data($meta_key, $value);
			self::action_log(sprintf('Meta updated: %s', $meta_key));
		}
	}

	private function first_request_value(array $payload, array $keys): string
	{
		foreach ($keys as $key) {
			if (!isset($payload[$key]) || is_array($payload[$key])) {
				continue;
			}

			$value = sanitize_text_field(wp_unslash((string) $payload[$key]));
			if ('' !== trim($value)) {
				return $value;
			}
		}

		return '';
	}

	private function save_customer_identity_meta(\WC_Order $order, array $payload): void
	{
		$map = array(
			'_billing_tax_number' => array('billing_tax_number'),
			'_billing_tax_office' => array('billing_tax_office'),
			'_billing_tc_number' => array('billing_tc_number'),
			'_billing_vergi_nosu' => array('billing_vergi_nosu'),
			'_billing_vergi_dairesi' => array('billing_vergi_dairesi'),
			'_shipping_tc' => array('shipping_tc'),
		);

		foreach ($map as $meta_key => $request_keys) {
			$value = $this->first_request_value($payload, $request_keys);
			if ('' === $value) {
				continue;
			}

			$order->update_meta_data($meta_key, $value);
			self::action_log(sprintf('Customer identity meta updated: %s', $meta_key));
		}
	}

	public function update_order_meta_from_request(\WC_Order $order, \WP_REST_Request $request)
	{
		$route = $request->get_route();
		if (!preg_match('#^/wc/store(?:/v[0-9]+)?/checkout$#', $route)) {
			return;
		}

		if (wc_string_to_bool((string) $request->get_param('__experimental_calc_totals'))) {
			return;
		}

		$payload = isset($request['extensions']['irem']) && is_array($request['extensions']['irem'])
			? $request['extensions']['irem']
			: array();

		if ((int) get_option('sozlesme_ozellik_3') === 1) {
			$approved = isset($payload['sozlesme_onay'])
				&& in_array((string) $payload['sozlesme_onay'], array('1', 'true', 'yes', 'on'), true);

			if (!$approved) {
				$message = __('Please read and approve the contracts.', 'wc-korkmaz-contract');

				if (class_exists('\Automattic\WooCommerce\StoreApi\Exceptions\RouteException')) {
					throw new \Automattic\WooCommerce\StoreApi\Exceptions\RouteException(
						'korkmaz_contract_not_approved',
						$message,
						400
					);
				}

				throw new \Exception($message);
			}
		}

		if (empty($payload)) {
			return;
		}
		$this->save_contract_meta($order, $payload);
	}

	public function custom_checkout_fields_add($checkout)
	{
		$this->render_classic_contract_snapshot_fields();
	}

	public function classic_checkout_hidden_contract_fields()
	{
		$this->render_classic_contract_snapshot_fields();
	}
}
