<?php

namespace WPDesk\FakturyKSEF\Dashboard;

use WPDesk\FakturyKSEF\Api\APIClient;
use WPDesk\FakturyKSEF\Api\Environments\DemoEnvironment;
use WPDesk\FakturyKSEF\Api\Environments\ProdEnvironment;
use WPDesk\FakturyKSEF\Api\Environments\TestEnvironment;
use WPDesk\FakturyKSEF\Api\Exceptions\ResponseException;
use WPDesk\FakturyKSEF\Api\Requests\HealthCheckRequest;
use WPDesk\FakturyKSEF\Renderer\KSeFRenderer;
use WPDesk\CoreAlias\SelectField;
use WPDesk\CoreAlias\NoOnceField;
use WPDesk\CoreAlias\Header;
use WPDesk\CoreAlias\InputTextField;
use WPDesk\CoreAlias\TextAreaField;
use WPDesk\CoreAlias\SubmitField;
use WPDesk\CoreAlias\SettingsForm;
use WPDesk\CoreAlias\FieldSettingsTab;
use WPDesk\CoreAlias\GeneralSettingsMenu;
use WPDesk\CoreAlias\FICheckboxField;
use WPDesk\FakturyKSEF\Repository\PluginSettings;
use WPDesk\FakturyKSEF\Services\PageChecker;
use WPDesk\CoreAlias\InvoicesIntegration;


final class SettingsTab extends FieldSettingsTab {

	private APIClient $api;

	private KSeFRenderer $renderer;

	private PageChecker $page_checker;

	private VatRates $vat_rates;

	public function __construct( APIClient $api, KSeFRenderer $renderer, PageChecker $page_checker, VatRates $vat_rates ) {
		$this->vat_rates    = $vat_rates;
		$this->page_checker = $page_checker;
		$this->api          = $api;
		$this->renderer     = $renderer;
	}

	/**
	 * @return array|Field[]
	 */
	protected function get_fields(): array {

		if ( ! $this->page_checker->is_on_ksef_settings_page() ) {
			return [];
		}
		try {
			$is_authenticated = $this->api->authenticate( true );

			if ( ! $is_authenticated ) {
				throw new \RuntimeException(
					sprintf( // translators: every placeholder is <br/>
						__( 'Unable to establish a connection.%1$s%1$sPlease make sure that:%1$s- the selected environment is correct%1$s- the token is valid and intended for the selected environment%1$s- the VAT number is correct%1$s%1$s	If the settings are correct, the most likely cause is an issue on the KSeF system side.%1$sPlease try again in a moment.', 'ksef-for-flexible-invoices' ),
						'<br/>'
					)
				);
			}
			$this->api->execute( new HealthCheckRequest() );
			$connected_info = $this->renderer->render_connection_status( true );
		} catch ( ResponseException $error ) {
			$connected_info = $this->renderer->render_connection_status( false, $error->get_translated_error() );
		} catch ( \RuntimeException $error ) {
			$connected_info = $this->renderer->render_connection_status( false, $error->getMessage() );
		}

		$form_part_1 = [
			( new Header() )
				->set_label( esc_html__( 'KSeF', 'ksef-for-flexible-invoices' ) )
				->set_header_size( 1 )
				// translators: 1. Open <a> tag with docs url. 2. Close </a>
				->set_description( sprintf( esc_html__( 'Read more in the %1$splugin documentation &rarr;%2$s', 'ksef-for-flexible-invoices' ), '<a href="https://wpdesk.link/KSeF-settings-docs" target="_blank" style="color: #4BB04E; font-weight: 700;">', '</a>' ) ),
			( new Header() )
				->set_label( esc_html__( 'Connection', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Configure connection with KSeF. Select the environment and fill proper connection details.', 'ksef-for-flexible-invoices' ) ),
			( new SelectField() )
				->set_name( PluginSettings::KSEF_ENVIRONMENT )
				->set_label( esc_html__( 'Environment', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Select environment version.', 'ksef-for-flexible-invoices' ) )
				->set_options(
					[
						TestEnvironment::SLUG => esc_html__( 'Test', 'ksef-for-flexible-invoices' ),
						DemoEnvironment::SLUG => esc_html__( 'Demo', 'ksef-for-flexible-invoices' ),
						ProdEnvironment::SLUG => esc_html__( 'Prod', 'ksef-for-flexible-invoices' ),
					]
				)
				->set_default_value( TestEnvironment::SLUG ),

			( new InputTextField() )
				->set_name( 'company_nip' )
				->set_label( esc_html__( 'VAT Number', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Enter your NIP. You can find the same setting in: Invoices > Settings > General.', 'ksef-for-flexible-invoices' ) )
				->add_class( 'regular-text' ),

			( new InputTextField() )
				->set_name( PluginSettings::KSEF_TOKEN )
				->set_label( esc_html__( 'Token', 'ksef-for-flexible-invoices' ) )
				// translators: %1 docs url, %2 connected status span
				->set_description( sprintf( esc_html__( 'Read the manual on %1$show to generate a token%2$s.%3$s %4$s', 'ksef-for-flexible-invoices' ), '<a target="_blank" href="https://wpdesk.link/ksef-token-docs">', '</a>', '<br/>', $connected_info ) )
				->add_class( 'hs-beacon-search' ),

			( new Header() )
				->set_label( esc_html__( 'Sending', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Configure sending to KSeF options. ', 'ksef-for-flexible-invoices' ) ),

			( new FICheckboxField() )
				->set_name( PluginSettings::AUTO_DOCUMENT_SENDING )
				->set_label( esc_html__( 'Automatic sending', 'ksef-for-flexible-invoices' ) )
				->set_sublabel( esc_html__( 'Enable', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Select this option if you want invoices to be automatically sent to KSeF after they are generated.', 'ksef-for-flexible-invoices' ) ),
		];

		$cross_border_sending_field = [];
		if ( InvoicesIntegration::is_pro() ) {
			$cross_border_sending_field = [
				( new FICheckboxField() )
					->set_name( PluginSettings::AUTO_CROSS_BORDER_SENDING )
					->set_default_value( 'on' )
					->set_label( esc_html__( 'Cross-border sending', 'ksef-for-flexible-invoices' ) )
					->set_sublabel( esc_html__( 'Enable', 'ksef-for-flexible-invoices' ) )
					->set_description( esc_html__( 'Select this option if you want to enable the ability to send international invoices.', 'ksef-for-flexible-invoices' ) ),
			];
		}

		$form_part_2 = [
			( new Header() )
				->set_label( esc_html__( 'Tax rates', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Configure tax rates.', 'ksef-for-flexible-invoices' ) ),

			( new SelectField() )
				->set_name( PluginSettings::KSEF_EXEMPT_VAT_RATE )
				->set_label( esc_html__( 'ZW rate', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Select your tax exemption rate (ZW). Rates are pulled from: WooCommerce > Settings > Tax.', 'ksef-for-flexible-invoices' ) )
				->set_options(
					$this->vat_rates->get_vat_types_options( esc_html__( 'I don\'t use the ZW rate', 'ksef-for-flexible-invoices' ) )
				)
				->add_class( PluginSettings::KSEF_EXEMPT_VAT_RATE ),
			( new TextAreaField() )
				->set_name( PluginSettings::EXEMPTION )
				->set_placeholder( esc_html__( 'Art. 113 ust. 1...', 'ksef-for-flexible-invoices' ) )
				->set_label( esc_html__( 'Exemption', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Enter the default VAT exemption reason. This will be editable on the invoice edit page if the invoice includes the ZW rate selected here.', 'ksef-for-flexible-invoices' ) ),
			( new SelectField() )
				->set_name( PluginSettings::KSEF_NP_VAT_RATE )
				->set_label( esc_html__( 'Not subject to VAT rate', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Select your not subject to VAT rate (NP). Rates are pulled from: WooCommerce > Settings > Tax.', 'ksef-for-flexible-invoices' ) )
				->set_options(
					$this->vat_rates->get_vat_types_options( esc_html__( 'I don\'t use the NP rate', 'ksef-for-flexible-invoices' ) )
				)
				->add_class( PluginSettings::KSEF_NP_VAT_RATE ),
			( new SelectField() )
				->set_name( PluginSettings::DEFAULT_NP_RATE_TYPE )
				->set_label( esc_html__( 'Not subject to vat type', 'ksef-for-flexible-invoices' ) )
				->set_description( esc_html__( 'Select the default not subject to vat rate type. This will be editable on the invoice edit page if the invoice includes the NP rate selected here.', 'ksef-for-flexible-invoices' ) )
				->set_options(
					[
						'np I'  => esc_html__( 'NP I', 'ksef-for-flexible-invoices' ),
						'np II' => esc_html__( 'NP II', 'ksef-for-flexible-invoices' ),
					]
				)
				->add_class( PluginSettings::DEFAULT_NP_RATE_TYPE ),

			( new NoOnceField( GeneralSettingsMenu::NONCE_ACTION ) )
				->set_name( GeneralSettingsMenu::NONCE_NAME ),
			( new SubmitField() )
				->set_name( 'save' )
				->set_label( esc_html__( 'Save changes', 'ksef-for-flexible-invoices' ) )
				->add_class( 'button-primary' ),
		];

		$fields = array_merge( $form_part_1, $cross_border_sending_field, $form_part_2 );

		return $fields; //@phpstan-ignore return.type
	}

	/**
	 * @return string
	 */
	public static function get_tab_slug(): string {
		return 'ksef';
	}

	/**
	 * @return string
	 */
	public function get_tab_name(): string {
		return esc_html__( 'KSeF', 'ksef-for-flexible-invoices' );
	}
}
