<?php

	class Korkmaz_woo_sales_contract_Admin {
		private $plugin_name;
		private $version;
		private $birinci_sozlesme_link_ismi;
		private $ikinci_sozlesme_link_ismi;

		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' );
		}

		public function enqueue_styles( $hook_suffix = '' ) {
			if ( ! $this->is_plugin_admin_screen( $hook_suffix ) && ! $this->is_order_admin_screen() ) {
				return;
			}

			wp_enqueue_style(
				$this->plugin_name,
				plugin_dir_url( __FILE__ ) . 'css/korkmaz_contract-admin.css',
				array(),
				$this->asset_version( 'css/korkmaz_contract-admin.css' ),
				'all'
			);
		}

		public function enqueue_scripts( $hook_suffix = '' ) {
			if ( ! $this->is_plugin_admin_screen( $hook_suffix ) ) {
				return;
			}

			wp_enqueue_script(
				$this->plugin_name . '3',
				plugin_dir_url( __FILE__ ) . 'js/korkmaz_contract-admin.js',
				array( 'wp-i18n', 'jquery' ),
				$this->asset_version( 'js/korkmaz_contract-admin.js' ),
				false
			);
		}

		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 function is_plugin_admin_screen( string $hook_suffix ): bool {
			$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
			$plugin_pages = array(
				'sozlesme_ekrani',
				'birinci_sozlesme',
				'ikinci_sozlesme',
				'alanlar',
			);

			return in_array( $page, $plugin_pages, true ) || false !== strpos( $hook_suffix, 'sozlesme' );
		}

		private function is_order_admin_screen(): bool {
			if ( ! function_exists( 'get_current_screen' ) ) {
				return false;
			}

			$screen = get_current_screen();
			if ( ! $screen ) {
				return false;
			}

			return in_array(
				$screen->id,
				array(
					'shop_order',
					'edit-shop_order',
					'woocommerce_page_wc-orders',
					'woocommerce_page_wc-orders--shop_order',
				),
				true
			);
		}

		public function missing_checkout_fields_admin_notice() {
			if ( ! current_user_can( 'manage_woocommerce' ) || ! $this->should_show_missing_fields_notice() ) {
				return;
			}

			$notice = get_user_meta( get_current_user_id(), 'korkmaz_contract_missing_checkout_fields_notice', true );
			if ( ! is_array( $notice ) || empty( $notice['fields'] ) || ! is_array( $notice['fields'] ) ) {
				return;
			}

			$fields = array_values(
				array_filter(
					array_map(
						array( $this, 'translate_missing_checkout_field_label' ),
						array_map( 'sanitize_text_field', $notice['fields'] )
					)
				)
			);
			if ( empty( $fields ) ) {
				return;
			}

			$checked_at = isset( $notice['checked_at'] ) ? absint( $notice['checked_at'] ) : 0;
			if ( $checked_at > 0 && ( time() - $checked_at ) > WEEK_IN_SECONDS ) {
				delete_user_meta( get_current_user_id(), 'korkmaz_contract_missing_checkout_fields_notice' );
				return;
			}

			$fields_url = admin_url( 'admin.php?page=alanlar' );
			?>
			<div class="notice notice-warning">
				<p>
					<strong><?php esc_html_e( 'WC Korkmaz Contract notice', 'wc-korkmaz-contract' ); ?></strong>
				</p>
				<p>
					<?php esc_html_e( 'Some checkout fields used in the contract templates were not found during the latest admin checkout preview. Customers do not see this warning on the checkout page.', 'wc-korkmaz-contract' ); ?>
				</p>
				<p>
					<strong><?php esc_html_e( 'Missing fields:', 'wc-korkmaz-contract' ); ?></strong>
					<?php echo esc_html( implode( ', ', $fields ) ); ?>
				</p>
				<p>
					<a class="button button-secondary" href="<?php echo esc_url( $fields_url ); ?>">
						<?php esc_html_e( 'Review field mappings', 'wc-korkmaz-contract' ); ?>
					</a>
				</p>
			</div>
			<?php
		}

		private function translate_missing_checkout_field_label( string $field ): string {
			$labels = array(
				'Billing first name'     => __( 'Billing first name', 'wc-korkmaz-contract' ),
				'Billing last name'      => __( 'Billing last name', 'wc-korkmaz-contract' ),
				'Billing company'        => __( 'Billing company', 'wc-korkmaz-contract' ),
				'Billing tax number'     => __( 'Billing tax number', 'wc-korkmaz-contract' ),
				'Billing tax office'     => __( 'Billing tax office', 'wc-korkmaz-contract' ),
				'Billing address'        => __( 'Billing address', 'wc-korkmaz-contract' ),
				'Billing city'           => __( 'Billing city', 'wc-korkmaz-contract' ),
				'Billing phone'          => __( 'Billing phone', 'wc-korkmaz-contract' ),
				'Billing email'          => __( 'Billing email', 'wc-korkmaz-contract' ),
				'National ID field'      => __( 'National ID field', 'wc-korkmaz-contract' ),
				'Shipping first name'    => __( 'Shipping first name', 'wc-korkmaz-contract' ),
				'Shipping last name'     => __( 'Shipping last name', 'wc-korkmaz-contract' ),
				'Shipping company'       => __( 'Shipping company', 'wc-korkmaz-contract' ),
				'Shipping address'       => __( 'Shipping address', 'wc-korkmaz-contract' ),
				'Shipping city'          => __( 'Shipping city', 'wc-korkmaz-contract' ),
				'Payment method'         => __( 'Payment method', 'wc-korkmaz-contract' ),
			);

			return $labels[ $field ] ?? $field;
		}

		private function should_show_missing_fields_notice(): bool {
			if ( ! function_exists( 'get_current_screen' ) ) {
				return false;
			}

			$screen = get_current_screen();
			if ( ! $screen ) {
				return false;
			}

			return 'dashboard' === (string) $screen->id;
		}

		public function add_admin_menu() {
			add_menu_page(
				__( 'Sales Contract', 'wc-korkmaz-contract' ),
				__( 'Contracts', 'wc-korkmaz-contract' ),
				'manage_options',
				'sozlesme_ekrani',
				array( $this, 'display_admin_page' ),
				'dashicons-welcome-write-blog',
				56
			);

			add_submenu_page(
				'sozlesme_ekrani',
				__( 'Contract Settings', 'wc-korkmaz-contract' ),
				__( 'Settings', 'wc-korkmaz-contract' ),
				'manage_options',
				'sozlesme_ekrani',
				array( $this, 'display_admin_page' )
			);

			add_submenu_page(
				'sozlesme_ekrani',
				esc_html( $this->birinci_sozlesme_link_ismi ),
				esc_html( $this->birinci_sozlesme_link_ismi ),
				'manage_options',
				'birinci_sozlesme',
				array( $this, 'display_birinci_sozlesme' )
			);

			add_submenu_page(
				'sozlesme_ekrani',
				esc_html( $this->ikinci_sozlesme_link_ismi ),
				esc_html( $this->ikinci_sozlesme_link_ismi ),
				'manage_options',
				'ikinci_sozlesme',
				array( $this, 'display_ikinci_sozlesme' )
			);

			add_submenu_page(
				'sozlesme_ekrani',
				__( 'Fields', 'wc-korkmaz-contract' ),
				__( 'Fields', 'wc-korkmaz-contract' ),
				'manage_options',
				'alanlar',
				array( $this, 'display_alanlar_page' )
			);
		}

		public function display_admin_page() {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			$template = korkmaz_contract_dir . '/admin/partials/korkmaz_contract-admin-display.php';
			if ( file_exists( $template ) ) {
				include $template;
			} else {
				echo '<div class="notice notice-error"><p>' . esc_html__( 'Admin template not found.', 'wc-korkmaz-contract' ) . '</p></div>';
			}
		}

		public function display_birinci_sozlesme() {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			$template = korkmaz_contract_dir . '/admin/partials/bir_sozlesme_ekrani.php';
			if ( file_exists( $template ) ) {
				include $template;
			} else {
				echo '<div class="notice notice-error"><p>' . esc_html__( 'First contract template not found.', 'wc-korkmaz-contract' ) . '</p></div>';
			}
		}

		public function display_ikinci_sozlesme() {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			$template = korkmaz_contract_dir . '/admin/partials/iki_sozlesme_ekrani.php';
			if ( file_exists( $template ) ) {
				include $template;
			} else {
				echo '<div class="notice notice-error"><p>' . esc_html__( 'Second contract template not found.', 'wc-korkmaz-contract' ) . '</p></div>';
			}
		}

		public function display_alanlar_page() {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}
			?>
		  <div class="wrap">
			<h1><?php esc_html_e( 'Fields', 'wc-korkmaz-contract' ); ?></h1>
			<form method="post" action="options.php">
				<?php
					settings_fields( 'alanlar_options' );
					do_settings_sections( 'alanlar_options' );
					submit_button();
				?>
			</form>
		  </div>
			<?php
		}

		public function sanitize_checkbox( $value ) {
			return $value ? 1 : 0;
		}

		public function sanitize_mail_status( $value ) {
			$value = str_replace( '_', '-', sanitize_key( (string) $value ) );
			if ( 'new-order' === $value ) {
				$value = 'pending';
			}

			$allowed = array( 'pending', 'processing', 'on-hold', 'completed' );
			return in_array( $value, $allowed, true ) ? $value : 'completed';
		}

		public function get_action_log_path(): string {
			$upload_dir = wp_upload_dir( null, false );
			return trailingslashit( $upload_dir['basedir'] ) . 'korkmazsozlesme/action_log.log';
		}

		public function get_action_log_excerpt( int $line_limit = 200, int $byte_limit = 131072 ): string {
			$log_path = $this->get_action_log_path();
			if ( ! file_exists( $log_path ) || ! is_readable( $log_path ) ) {
				return '';
			}

			$size = @filesize( $log_path );
			if ( false === $size || $size <= 0 ) {
				return '';
			}

			$handle = @fopen( $log_path, 'rb' );
			if ( ! $handle ) {
				return '';
			}

			$offset = max( 0, $size - max( 1024, $byte_limit ) );
			fseek( $handle, $offset );
			if ( $offset > 0 ) {
				fgets( $handle );
			}

			$content = stream_get_contents( $handle );
			fclose( $handle );

			if ( ! is_string( $content ) || '' === $content ) {
				return '';
			}

			$lines = preg_split( '/\r\n|\r|\n/', $content );
			$lines = array_values(
				array_filter(
					$lines,
					static function ( $line ) {
						return '' !== $line;
					}
				)
			);

			if ( count( $lines ) > $line_limit ) {
				$lines = array_slice( $lines, -$line_limit );
			}

			return implode( PHP_EOL, $lines );
		}

		public function get_pdf_storage_security_status(): array {
			if ( ! current_user_can( 'manage_options' ) ) {
				return array();
			}

			$transient_key = 'korkmaz_contract_pdf_security_status_' . get_current_blog_id();

			if (
				isset( $_GET['korkmaz_contract_refresh_pdf_security'], $_GET['_wpnonce'] )
				&& wp_verify_nonce(
					sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
					'korkmaz_contract_refresh_pdf_security'
				)
			) {
				delete_transient( $transient_key );
			}

			$cached = get_transient( $transient_key );
			if ( is_array( $cached ) ) {
				return $cached;
			}

			$upload_dir = wp_upload_dir( null, false );
			if ( ! empty( $upload_dir['error'] ) ) {
				return array(
					'status'              => 'unknown',
					'message'             => $upload_dir['error'],
					'server_label'        => $this->detect_web_server(),
					'directory_path'      => '',
					'directory_url'       => '',
					'htaccess_status'     => 'unknown',
					'htaccess_message'    => __( 'The uploads directory could not be resolved.', 'wc-korkmaz-contract' ),
					'nginx_rule'          => '',
					'apache_rule'         => $this->get_apache_pdf_rule(),
					'refresh_url'         => $this->get_pdf_security_refresh_url(),
					'checked_at'          => time(),
				);
			}

			$directory_path = trailingslashit( $upload_dir['basedir'] ) . 'korkmazsozlesme';
			$directory_url  = trailingslashit( $upload_dir['baseurl'] ) . 'korkmazsozlesme/';
			$htaccess_path  = trailingslashit( $directory_path ) . '.htaccess';

			$htaccess_status  = 'missing';
			$htaccess_message = __( 'The Apache .htaccess file is missing.', 'wc-korkmaz-contract' );
			if ( file_exists( $htaccess_path ) && is_readable( $htaccess_path ) ) {
				$htaccess_body = (string) file_get_contents( $htaccess_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions
				if (
					false !== strpos( $htaccess_body, 'Require all denied' )
					&& false !== strpos( $htaccess_body, 'mod_authz_core.c' )
				) {
					$htaccess_status  = 'ok';
					$htaccess_message = __( 'The Apache .htaccess deny rule is present.', 'wc-korkmaz-contract' );
				} else {
					$htaccess_status  = 'incomplete';
					$htaccess_message = __( 'The Apache .htaccess file exists, but the PDF deny rule is incomplete.', 'wc-korkmaz-contract' );
				}
			}

			$direct_access = $this->test_pdf_direct_access( $directory_path, $directory_url );

			$status = array(
				'status'           => $direct_access['status'],
				'message'          => $direct_access['message'],
				'http_code'        => $direct_access['http_code'],
				'test_url'         => $direct_access['test_url'],
				'server_label'     => $this->detect_web_server(),
				'directory_path'   => $directory_path,
				'directory_url'    => $directory_url,
				'htaccess_status'  => $htaccess_status,
				'htaccess_message' => $htaccess_message,
				'nginx_rule'       => $this->get_nginx_pdf_rule( $upload_dir ),
				'apache_rule'      => $this->get_apache_pdf_rule(),
				'refresh_url'      => $this->get_pdf_security_refresh_url(),
				'checked_at'       => time(),
			);

			set_transient( $transient_key, $status, 10 * MINUTE_IN_SECONDS );

			return $status;
		}

		private function test_pdf_direct_access( string $directory_path, string $directory_url ): array {
			if ( '' === $directory_path || '' === $directory_url ) {
				return array(
					'status'    => 'unknown',
					'message'   => __( 'The PDF storage path could not be resolved.', 'wc-korkmaz-contract' ),
					'http_code' => 0,
					'test_url'  => '',
				);
			}

			if ( ! wp_mkdir_p( $directory_path ) ) {
				return array(
					'status'    => 'unknown',
					'message'   => __( 'The PDF storage directory could not be created for the security check.', 'wc-korkmaz-contract' ),
					'http_code' => 0,
					'test_url'  => '',
				);
			}

			$token          = function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : wp_hash( microtime( true ) . wp_rand() );
			$test_file_name = 'korkmaz-security-check-' . sanitize_file_name( $token ) . '.pdf';
			$test_file_path = trailingslashit( $directory_path ) . $test_file_name;
			$test_file_url  = trailingslashit( $directory_url ) . $test_file_name;
			$created_file   = false;

			if ( is_writable( $directory_path ) ) {
				$created_file = false !== file_put_contents( // phpcs:ignore WordPress.WP.AlternativeFunctions
					$test_file_path,
					"%PDF-1.4\n% Korkmaz Contract security check\n%%EOF\n",
					LOCK_EX
				);
			}

			if ( ! $created_file ) {
				$existing_file = $this->find_existing_contract_pdf( $directory_path );
				if ( '' === $existing_file ) {
					return array(
						'status'    => 'unknown',
						'message'   => __( 'The direct access test could not create a temporary PDF and no existing PDF was found.', 'wc-korkmaz-contract' ),
						'http_code' => 0,
						'test_url'  => '',
					);
				}

				$test_file_name = wp_basename( $existing_file );
				$test_file_url  = trailingslashit( $directory_url ) . rawurlencode( $test_file_name );
			}

			$response = wp_remote_get(
				$test_file_url,
				array(
					'timeout'             => 5,
					'redirection'         => 0,
					'sslverify'           => false,
					'limit_response_size' => 64,
					'headers'             => array(
						'Cache-Control' => 'no-cache',
					),
				)
			);

			if ( $created_file && file_exists( $test_file_path ) ) {
				wp_delete_file( $test_file_path );
			}

			if ( is_wp_error( $response ) ) {
				return array(
					'status'    => 'unknown',
					'message'   => sprintf(
						/* translators: %s: HTTP error message */
						__( 'The loopback direct-access check could not be completed: %s', 'wc-korkmaz-contract' ),
						$response->get_error_message()
					),
					'http_code' => 0,
					'test_url'  => $test_file_url,
				);
			}

			$http_code = (int) wp_remote_retrieve_response_code( $response );
			if ( 200 === $http_code ) {
				return array(
					'status'    => 'exposed',
					'message'   => __( 'Direct PDF URLs are reachable. Add the Nginx rule below or enable Apache .htaccess overrides.', 'wc-korkmaz-contract' ),
					'http_code' => $http_code,
					'test_url'  => $test_file_url,
				);
			}

			if ( in_array( $http_code, array( 401, 403, 404 ), true ) ) {
				return array(
					'status'    => 'protected',
					'message'   => __( 'Direct PDF access is blocked.', 'wc-korkmaz-contract' ),
					'http_code' => $http_code,
					'test_url'  => $test_file_url,
				);
			}

			return array(
				'status'    => 'unknown',
				'message'   => __( 'The direct PDF access check returned an unexpected HTTP status. Review your web server rules manually.', 'wc-korkmaz-contract' ),
				'http_code' => $http_code,
				'test_url'  => $test_file_url,
			);
		}

		private function find_existing_contract_pdf( string $directory_path ): string {
			$files = glob( trailingslashit( $directory_path ) . '*.pdf' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_glob
			if ( ! is_array( $files ) || empty( $files ) ) {
				return '';
			}

			foreach ( $files as $file ) {
				if ( is_file( $file ) && is_readable( $file ) ) {
					return $file;
				}
			}

			return '';
		}

		private function detect_web_server(): string {
			$server_software = isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '';
			if ( '' === $server_software ) {
				return __( 'Unknown web server', 'wc-korkmaz-contract' );
			}

			return $server_software;
		}

		private function get_pdf_security_refresh_url(): string {
			return wp_nonce_url(
				add_query_arg( 'korkmaz_contract_refresh_pdf_security', '1' ),
				'korkmaz_contract_refresh_pdf_security'
			);
		}

		private function get_nginx_pdf_rule( array $upload_dir ): string {
			$upload_path = wp_parse_url( $upload_dir['baseurl'], PHP_URL_PATH );
			$upload_path = '/' . trim( (string) $upload_path, '/' );
			$location    = trailingslashit( $upload_path ) . 'korkmazsozlesme/';

			return "location ^~ {$location} {\n    deny all;\n    return 403;\n}";
		}

		private function get_apache_pdf_rule(): string {
			return "# wp-content/uploads/korkmazsozlesme/.htaccess\nOptions -Indexes\n\n<Files \"*.pdf\">\n    <IfModule mod_authz_core.c>\n        Require all denied\n    </IfModule>\n    <IfModule !mod_authz_core.c>\n        Order allow,deny\n        Deny from all\n    </IfModule>\n</Files>";
		}

		public function korkmaz_contract_register_settings() {
			// === Company Information ===
			register_setting(
				'korkmaz_contract_options_group',
				'firmaadi',
				array(
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_text_field',
					'default'           => '',
				)
			);

			register_setting(
				'korkmaz_contract_options_group',
				'firmaadresi',
				array(
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_text_field',
					'default'           => '',
				)
			);

			register_setting(
				'korkmaz_contract_options_group',
				'firmatelno',
				array(
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_text_field',
					'default'           => '',
				)
			);

			register_setting(
				'korkmaz_contract_options_group',
				'firmaverdaire',
				array(
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_text_field',
					'default'           => '',
				)
			);

			register_setting(
				'korkmaz_contract_options_group',
				'firmaverno',
				array(
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_text_field',
					'default'           => '',
				)
			);

			register_setting(
				'korkmaz_contract_options_group',
				'birinci_sozlesme_link_ismi',
				array(
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_text_field',
					'default'           => '',
				)
			);

			register_setting(
				'korkmaz_contract_options_group',
				'ikinci_sozlesme_link_ismi',
				array(
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_text_field',
					'default'           => '',
				)
			);

			// === Visibility / Checkboxes ===
			foreach ( range( 1, 6 ) as $i ) {
				register_setting(
					'korkmaz_contract_options_group',
					"sozlesme_ozellik_{$i}",
					array(
						'type'              => 'boolean',
						'sanitize_callback' => array( $this, 'sanitize_checkbox' ),
						'default'           => 0,
					)
				);
			}

			// === Mail Status ===
			register_setting(
				'korkmaz_contract_options_group',
				'sozlesme_mail_durumu',
				array(
					'type'              => 'string',
					'sanitize_callback' => array( $this, 'sanitize_mail_status' ),
					'default'           => 'completed',
				)
			);

			// === Logging ===
			register_setting(
				'korkmaz_contract_options_group',
				'korkmaz_contract_log_enabled',
				array(
					'type'              => 'boolean',
					'sanitize_callback' => array( $this, 'sanitize_checkbox' ),
					'default'           => 0,
				)
			);
		}

		public function alanlar_settings_init() {
			register_setting(
				'alanlar_options',
				'alanlar_options',
				array(
					'type'              => 'array',
					'sanitize_callback' => array( $this, 'alanlar_options_sanitize' ),
					'default'           => array(),
				)
			);

			add_settings_section(
				'alanlar_section',
				__( 'Fields Settings', 'wc-korkmaz-contract' ),
				array( $this, 'alanlar_section_cb' ),
				'alanlar_options'
			);

			$alan_names = array(
				__( 'Billing First Name Field', 'wc-korkmaz-contract' ),
				__( 'Billing Last Name Field', 'wc-korkmaz-contract' ),
				__( 'Billing Company Name Field', 'wc-korkmaz-contract' ),
				__( 'Billing Tax Number Field', 'wc-korkmaz-contract' ),
				__( 'Billing Tax Office Field', 'wc-korkmaz-contract' ),
				__( 'Billing Address 1 Field', 'wc-korkmaz-contract' ),
				__( 'Billing Address 2 Field', 'wc-korkmaz-contract' ),
				__( 'Billing City Field', 'wc-korkmaz-contract' ),
				__( 'Billing Postcode Field', 'wc-korkmaz-contract' ),
				__( 'Billing Country Field', 'wc-korkmaz-contract' ),
				__( 'Billing District Field', 'wc-korkmaz-contract' ),
				__( 'Billing Email Field', 'wc-korkmaz-contract' ),
				__( 'Billing Phone Field', 'wc-korkmaz-contract' ),
				__( 'Billing National ID Field', 'wc-korkmaz-contract' ),
				__( 'Billing Product Details Field', 'wc-korkmaz-contract' ),
				__( 'Billing Cart Total Field', 'wc-korkmaz-contract' ),
				__( 'Shipping First Name Field', 'wc-korkmaz-contract' ),
				__( 'Shipping Last Name Field', 'wc-korkmaz-contract' ),
				__( 'Shipping Company Name Field', 'wc-korkmaz-contract' ),
				__( 'Shipping Address 1 Field', 'wc-korkmaz-contract' ),
				__( 'Shipping Address 2 Field', 'wc-korkmaz-contract' ),
				__( 'Shipping District Field', 'wc-korkmaz-contract' ),
				__( 'Shipping Postcode Field', 'wc-korkmaz-contract' ),
				__( 'Shipping Country Field', 'wc-korkmaz-contract' ),
				__( 'Shipping State Field', 'wc-korkmaz-contract' ),
				__( 'Payment Method Field', 'wc-korkmaz-contract' ),
				__( 'Field 27', 'wc-korkmaz-contract' ),
				__( 'Field 28', 'wc-korkmaz-contract' ),
				__( 'Field 29', 'wc-korkmaz-contract' ),
				__( 'Field 30', 'wc-korkmaz-contract' ),
			);

			foreach ( range( 1, 30 ) as $i ) {
				add_settings_field(
					"alan_$i",
					$alan_names[ $i - 1 ],
					array( $this, 'alan_field_cb' ),
					'alanlar_options',
					'alanlar_section',
					array( 'label_for' => "alan_$i" )
				);
			}
		}

		public function alanlar_section_cb() {
			echo '<div class="notice notice-info"><p>';
			esc_html_e(
				'Choose a checkout field from the list or enter a custom CSS selector for fields added by your theme or another plugin. The saved selector is used only for live checkout previews; final PDFs are generated from saved order data when available.',
				'wc-korkmaz-contract'
			);
			echo '</p></div>';
		}

		private function checkout_field_selector_choices(): array {
			$choices = array(
				__( 'Billing fields', 'wc-korkmaz-contract' )  => array(
					'#billing_first_name'                => __( 'Billing first name', 'wc-korkmaz-contract' ),
					'#billing_last_name'                 => __( 'Billing last name', 'wc-korkmaz-contract' ),
					'#billing_company'                   => __( 'Billing company', 'wc-korkmaz-contract' ),
					'#billing_tax_number'                => __( 'Billing tax number', 'wc-korkmaz-contract' ),
					'#billing_vergi_nosu'                => __( 'Billing tax number', 'wc-korkmaz-contract' ),
					'#billing_tax_office'                => __( 'Billing tax office', 'wc-korkmaz-contract' ),
					'#billing_vergi_dairesi'             => __( 'Billing tax office', 'wc-korkmaz-contract' ),
					'#billing_address_1'                 => __( 'Billing address 1', 'wc-korkmaz-contract' ),
					'#billing_address_2'                 => __( 'Billing address 2', 'wc-korkmaz-contract' ),
					'#billing_city'                      => __( 'Billing city', 'wc-korkmaz-contract' ),
					'#billing_postcode'                  => __( 'Billing postcode', 'wc-korkmaz-contract' ),
					'#billing_state'                     => __( 'Billing state', 'wc-korkmaz-contract' ),
					'#select2-billing_state-container'   => __( 'Billing state text', 'wc-korkmaz-contract' ),
					'#billing_country'                   => __( 'Billing country', 'wc-korkmaz-contract' ),
					'#select2-billing_country-container' => __( 'Billing country text', 'wc-korkmaz-contract' ),
					'#billing_email'                     => __( 'Billing email', 'wc-korkmaz-contract' ),
					'#billing_phone'                     => __( 'Billing phone', 'wc-korkmaz-contract' ),
					'#billing_tc_number'                 => __( 'National ID', 'wc-korkmaz-contract' ),
					'#shipping_tc'                       => __( 'National ID', 'wc-korkmaz-contract' ),
				),
				__( 'Shipping fields', 'wc-korkmaz-contract' ) => array(
					'#shipping_first_name'                 => __( 'Shipping first name', 'wc-korkmaz-contract' ),
					'#shipping_last_name'                  => __( 'Shipping last name', 'wc-korkmaz-contract' ),
					'#shipping_company'                    => __( 'Shipping company', 'wc-korkmaz-contract' ),
					'#shipping_address_1'                  => __( 'Shipping address 1', 'wc-korkmaz-contract' ),
					'#shipping_address_2'                  => __( 'Shipping address 2', 'wc-korkmaz-contract' ),
					'#shipping_city'                       => __( 'Shipping city', 'wc-korkmaz-contract' ),
					'#shipping_postcode'                   => __( 'Shipping postcode', 'wc-korkmaz-contract' ),
					'#shipping_state'                      => __( 'Shipping state', 'wc-korkmaz-contract' ),
					'#select2-shipping_state-container'    => __( 'Shipping state text', 'wc-korkmaz-contract' ),
					'#shipping_country'                    => __( 'Shipping country', 'wc-korkmaz-contract' ),
					'#select2-shipping_country-container'  => __( 'Shipping country text', 'wc-korkmaz-contract' ),
				),
				__( 'Order and calculated fields', 'wc-korkmaz-contract' ) => array(
					'table.woocommerce-checkout-review-order-table' => __( 'Checkout order table', 'wc-korkmaz-contract' ),
					'#sepettoplami'                                 => __( 'Cart total hidden value', 'wc-korkmaz-contract' ),
					'#odemeyontemiinput'                            => __( 'Payment method hidden value', 'wc-korkmaz-contract' ),
				),
			);

			$registered_fields = $this->registered_checkout_field_choices();
			if ( ! empty( $registered_fields ) ) {
				$choices[ __( 'Registered checkout fields', 'wc-korkmaz-contract' ) ] = $registered_fields;
			}

			/**
			 * Filter admin field selector choices.
			 *
			 * Return format: array( 'Group label' => array( 'selector' => 'Field label' ) ).
			 *
			 * @since 2.4.2
			 */
			return apply_filters( 'korkmaz_contract_admin_field_selector_choices', $choices );
		}

		private function registered_checkout_field_choices(): array {
			if ( ! function_exists( 'WC' ) || ! WC() || ! is_callable( array( WC(), 'checkout' ) ) ) {
				return array();
			}

			try {
				$checkout = WC()->checkout();
			} catch ( Throwable $e ) {
				return array();
			}

			if ( ! is_object( $checkout ) || ! is_callable( array( $checkout, 'get_checkout_fields' ) ) ) {
				return array();
			}

			$fields = $checkout->get_checkout_fields();
			if ( ! is_array( $fields ) ) {
				return array();
			}

			$choices = array();
			foreach ( $fields as $group_key => $group_fields ) {
				if ( ! is_array( $group_fields ) ) {
					continue;
				}

				foreach ( $group_fields as $field_key => $field ) {
					$field_key = (string) $field_key;
					if ( '' === $field_key ) {
						continue;
					}

					$selector = sprintf( '[name="%s"]', esc_attr( $field_key ) );
					$label    = isset( $field['label'] ) && '' !== trim( (string) $field['label'] )
						? wp_strip_all_tags( (string) $field['label'] )
						: $field_key;

					$choices[ $selector ] = sprintf(
						/* translators: 1: checkout field label, 2: checkout field key, 3: checkout field group */
						__( '%1$s (%2$s, %3$s)', 'wc-korkmaz-contract' ),
						$label,
						$field_key,
						(string) $group_key
					);
				}
			}

			return $choices;
		}

		private function default_field_selector_values(): array {
			return array(
				'#billing_first_name',
				'#billing_last_name',
				'#billing_company',
				'#billing_vergi_nosu',
				'#billing_vergi_dairesi',
				'#billing_address_1',
				'#billing_address_2',
				'#select2-billing_state-container',
				'#billing_postcode',
				'#select2-billing_country-container',
				'#billing_city',
				'#billing_email',
				'#billing_phone',
				'#shipping_tc',
				'table.woocommerce-checkout-review-order-table',
				'#sepettoplami',
				'#shipping_first_name',
				'#shipping_last_name',
				'#shipping_company',
				'#shipping_address_1',
				'#shipping_address_2',
				'#shipping_city',
				'#shipping_postcode',
				'#select2-shipping_country-container',
				'#select2-shipping_state-container',
				'#odemeyontemiinput',
				'',
				'',
				'',
				'',
			);
		}

		public function alan_field_cb( $args ) {
			$options = get_option( 'alanlar_options' );
			$id      = $args['label_for'];

			$alan_index   = (int) str_replace( 'alan_', '', $id ) - 1;
			$default_text = $this->default_field_selector_values()[ $alan_index ] ?? '';
			$has_value    = is_array( $options ) && array_key_exists( $id, $options );
			$value        = $has_value ? (string) $options[ $id ] : $default_text;
			$choices      = $this->checkout_field_selector_choices();
			$select_id    = $id . '_choice';
			$selected     = $value;
			$has_choice   = false;
			foreach ( $choices as $group_choices ) {
				if ( is_array( $group_choices ) && array_key_exists( $selected, $group_choices ) ) {
					$has_choice = true;
					break;
				}
			}
			?>
			<div class="kc-field-map">
				<select id="<?php echo esc_attr( $select_id ); ?>" class="kc-field-selector" data-target="#<?php echo esc_attr( $id ); ?>">
					<option value=""><?php esc_html_e( 'Manual / custom selector', 'wc-korkmaz-contract' ); ?></option>
					<?php foreach ( $choices as $group_label => $group_choices ) : ?>
						<?php if ( empty( $group_choices ) || ! is_array( $group_choices ) ) : ?>
							<?php continue; ?>
						<?php endif; ?>
						<optgroup label="<?php echo esc_attr( $group_label ); ?>">
							<?php foreach ( $group_choices as $selector => $label ) : ?>
								<option value="<?php echo esc_attr( $selector ); ?>" <?php selected( $has_choice && $selected === $selector ); ?>>
									<?php echo esc_html( $label ); ?> - <?php echo esc_html( $selector ); ?>
								</option>
							<?php endforeach; ?>
						</optgroup>
					<?php endforeach; ?>
				</select>
				<div class="kc-field-map__row">
					<input type="text" id="<?php echo esc_attr( $id ); ?>" name="alanlar_options[<?php echo esc_attr( $id ); ?>]" value="<?php echo esc_attr( $value ); ?>" placeholder="<?php esc_attr_e( 'CSS selector, e.g. #billing_first_name', 'wc-korkmaz-contract' ); ?>" />
					<?php if ( '' !== $default_text ) : ?>
						<button type="button" class="button kc-field-reset" data-target="#<?php echo esc_attr( $id ); ?>" data-default="<?php echo esc_attr( $default_text ); ?>">
							<?php esc_html_e( 'Reset', 'wc-korkmaz-contract' ); ?>
						</button>
					<?php endif; ?>
				</div>
				<p class="description">
					<?php
					printf(
						/* translators: %s: default CSS selector */
						esc_html__( 'Default selector: %s. Select a field above or type a custom selector for custom checkout fields.', 'wc-korkmaz-contract' ),
						esc_html( '' !== $default_text ? $default_text : __( 'none', 'wc-korkmaz-contract' ) )
					);
					?>
				</p>
			</div>
			<?php
		}

		public function alanlar_options_sanitize( $input ) {
			$output = array();

			foreach ( range( 1, 30 ) as $i ) {
				if ( isset( $input[ "alan_$i" ] ) ) {
					$output[ "alan_$i" ] = sanitize_text_field( $input[ "alan_$i" ] );
				}
			}
			return $output;
		}

		public function kisayol_ekle() {}

		public function buton_ekle( $buttons ) {
			array_push( $buttons, 'wdm_mce_button' );
			return $buttons;
		}

		public function js_buton_ekle( $plugin_array ) {
			$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
			if ( 'birinci_sozlesme' === $page || 'ikinci_sozlesme' === $page ) {
				// check user permissions
				if ( ! current_user_can( 'manage_options' ) ) {
					return $plugin_array;
				} else {
					$plugin_array['wdm_mce_button'] = plugins_url( 'js/quicktagsekle.js', __FILE__ );
					return $plugin_array;
				}
			}

			return $plugin_array;
		}

		public function custom_shop_order_column( $columns ) {
			$reordered_columns = array();
			// Inserting columns to a specific location
			foreach ( $columns as $key => $column ) {
				$reordered_columns[ $key ] = $column;
				if ( 'order_status' === $key ) {
					// Inserting after "Status" column
					$reordered_columns['sozlesmeler'] = __( 'Contracts', 'wc-korkmaz-contract' );
				}
			}
			return $reordered_columns;
		}

		public function custom_orders_list_column_content( $column, $post_id ) {
			switch ( $column ) {
				case 'sozlesmeler':
					$order = wc_get_order( $post_id );
					$this->butonlari_goster_admin( $order );
					break;
			}
		}

		/**
		 * HPOS (High-Performance Order Storage) uyumlu sütun içerik metodu.
		 * woocommerce_shop_order_list_table_custom_column hook'u WC_Order nesnesi geçirir.
		 *
		 * @param string   $column Sütun adı.
		 * @param WC_Order $order  Sipariş nesnesi.
		 */
		public function custom_orders_list_column_content_hpos( $column, $order ) {
			if ( 'sozlesmeler' === $column ) {
				$this->butonlari_goster_admin( $order );
			}
		}

		public function butonlari_goster_admin( $order ) {
			if ( ! $order instanceof WC_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 ( $birlink ) : ?>
				<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 ( $ikilink ) : ?>
				<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_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' )
			);
		}

		public function field_callback( $args ) {
			$option = get_option( $args['id'] );
			printf(
				'<input type="%s" id="%s" name="%s" value="%s" class="regular-text">',
				esc_attr( $args['type'] ),
				esc_attr( $args['id'] ),
				esc_attr( $args['id'] ),
				esc_attr( $option )
			);
		}

		public function checkbox_callback( $args ) {
			$option = get_option( $args['id'] );
			printf(
				'<input type="checkbox" id="%s" name="%s" value="1" %s>',
				esc_attr( $args['id'] ),
				esc_attr( $args['id'] ),
				checked( 1, $option, false )
			);
			printf(
				'<label for="%s">%s</label>',
				esc_attr( $args['id'] ),
				esc_html( $args['label'] )
			);
		}

		public function select_callback( $args ) {
			$option = get_option( $args['id'] );
			echo '<select id="' . esc_attr( $args['id'] ) . '" name="' . esc_attr( $args['id'] ) . '">';
			foreach ( $args['options'] as $value => $label ) {
				printf(
					'<option value="%s" %s>%s</option>',
					esc_attr( $value ),
					selected( $option, $value, false ),
					esc_html( $label )
				);
			}
			echo '</select>';
		}

		public function vergi_no_dairesi( $order ) {
			$billingCompany = $order->get_billing_company();

			if ( empty( $billingCompany ) ) {
				$shippingTc = $this->first_order_meta(
					$order,
					array(
						'_billing_tc_number',
						'billing_tc_number',
						'_shipping_tc',
						'shipping_tc',
						'_wc_other/wc-korkmaz-contract/shipping_tc',
					)
				);
				if ( ! empty( $shippingTc ) ) {
					echo '<p><strong>' . esc_html__( 'National ID', 'wc-korkmaz-contract' ) . ':</strong> ' . esc_html( $shippingTc ) . '</p>';
				}
			} else {
				$vergiDaire = $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',
					)
				);
				if ( empty( $vergiDaire ) ) {
					$vergiDaire = $order->get_billing_state();
				}
				$vergiNum   = $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',
					)
				);

				if ( ! empty( $vergiDaire ) ) {
					echo '<p><strong>' . esc_html__( 'Tax Office', 'wc-korkmaz-contract' ) . ':</strong> ' . esc_html( $vergiDaire ) . '</p>';
				}

				if ( ! empty( $vergiNum ) ) {
					echo '<p><strong>' . esc_html__( 'Tax Number', 'wc-korkmaz-contract' ) . ':</strong> ' . esc_html( $vergiNum ) . '</p>';
				}
			}
		}

		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 '';
		}
	}
