<?php

namespace Devikit\Sellsy\Frontend;

use Devikit\Sellsy\Admin\Settings;
use Devikit\Sellsy\VatIdField;

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

class Checkout {

	public function __construct() {
		add_action( 'woocommerce_checkout_init', [ $this, 'init_checkout' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_checkout_scripts' ] );
	}

	public function init_checkout() {
		add_action( 'woocommerce_checkout_process', [ $this, 'validate_checkout_fields' ] );
	}

	public function validate_checkout_fields() {
		if ( ! $this->is_valid_checkout_request() ) {
			return;
		}

		$settings         = get_option( Settings::OPTION_NAME, [] );
		$display_mode     = isset( $settings['siret_display_mode'] ) ? $settings['siret_display_mode'] : 'always';
		$siret_required   = isset( $settings['siret_required'] ) && $settings['siret_required'] === 'yes';
		$validate_siret   = ! isset( $settings['validate_siret_format'] ) || $settings['validate_siret_format'] === 'yes';
		$vat_display_mode = isset( $settings['vat_id_display_mode'] ) ? $settings['vat_id_display_mode'] : 'always';
		$vat_required     = isset( $settings['vat_id_required'] ) && $settings['vat_id_required'] === 'yes';
		$validate_vat     = ! isset( $settings['validate_vat_id_format'] ) || $settings['validate_vat_id_format'] === 'yes';

		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_checkout_request().
		$siret = isset( $_POST['billing_siret'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_siret'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_checkout_request().
		$vat = isset( $_POST['billing_vat_id'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_vat_id'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified in is_valid_checkout_request().
		$want_invoice = isset( $_POST['billing_want_invoice'] ) && sanitize_text_field( wp_unslash( $_POST['billing_want_invoice'] ) ) === '1';

		if ( $display_mode === 'checkbox' && $want_invoice && $siret_required && $siret === '' ) {
			wc_add_notice(
				__( 'SIRET number is required when requesting an invoice.', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'error'
			);
		}

		if ( $display_mode === 'always' && $siret_required && $siret === '' ) {
			wc_add_notice(
				__( 'SIRET number is required.', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'error'
			);
		}

		if ( $siret !== '' && $validate_siret ) {
			$siret_clean = preg_replace( '/[^0-9]/', '', $siret );
			if ( strlen( $siret_clean ) !== 14 ) {
				wc_add_notice(
					__( 'SIRET must contain exactly 14 digits.', 'invoicing-integration-for-sellsy-and-woocommerce' ),
					'error'
				);
			}
		}

		if ( VatIdField::is_external_vat_field_available() || $vat_display_mode === 'hidden' ) {
			return;
		}

		if ( $vat_display_mode === 'checkbox' && $want_invoice && $vat_required && $vat === '' ) {
			wc_add_notice(
				__( 'VAT number is required when requesting an invoice.', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'error'
			);
		}

		if ( $vat_display_mode === 'always' && $vat_required && $vat === '' ) {
			wc_add_notice(
				__( 'VAT number is required.', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'error'
			);
		}

		if ( $vat !== '' && $validate_vat && ! preg_match( '/^[A-Z]{2}\d{2,13}$/i', $vat ) ) {
			wc_add_notice(
				__( 'VAT number must start with a 2-letter country code followed by 2-13 digits (e.g. FR12345678901).', 'invoicing-integration-for-sellsy-and-woocommerce' ),
				'error'
			);
		}
	}

	/**
	 * @return bool
	 */
	private function is_valid_checkout_request() {
		if ( isset( $_POST['woocommerce-process-checkout-nonce'] ) ) {
			$valid = wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_POST['woocommerce-process-checkout-nonce'] ) ),
				'woocommerce-process_checkout'
			);
			if ( $valid ) {
				return true;
			}
			return did_action( 'woocommerce_checkout_process' ) > 0
				|| did_action( 'woocommerce_before_checkout_process' ) > 0;
		}

		return false;
	}

	public function enqueue_checkout_scripts() {
		if ( ! is_checkout() ) {
			return;
		}

		$settings         = get_option( Settings::OPTION_NAME, [] );
		$display_mode     = isset( $settings['siret_display_mode'] ) ? $settings['siret_display_mode'] : 'always';
		$vat_display_mode = isset( $settings['vat_id_display_mode'] ) ? $settings['vat_id_display_mode'] : 'always';
		$add_vat          = ( $vat_display_mode !== 'hidden' ) && ! VatIdField::is_external_vat_field_available();

		$has_checkbox_fields = ( $display_mode === 'checkbox' || ( $add_vat && $vat_display_mode === 'checkbox' ) );
		if ( ! $has_checkbox_fields ) {
			return;
		}

		wp_add_inline_style(
			'woocommerce-layout',
			'.sellsy-field-hidden-initially { display: none; }'
		);

		$inline_js = "
			jQuery(function($) {
				function toggleSellsyFields() {
					var checked = $('#billing_want_invoice').is(':checked');
					$('.sellsy-field-hidden-initially').each(function() {
						if (checked) {
							$(this).slideDown(200);
						} else {
							$(this).slideUp(200);
						}
					});
				}

				$(document.body).on('change', '#billing_want_invoice', toggleSellsyFields);
				toggleSellsyFields();
			});
		";
		wp_add_inline_script( 'woocommerce', $inline_js );
	}
}
