<?php

namespace Inspire_Labs\Alsendo_Connect;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Global_Settings
 */
class Global_Settings {


	/**
	 * Get API settings
	 */
	public function get_api_settings(): array {

		$ecolet = new Ecolet();

		$ecolet_services = array();

		if ( ! empty( $_POST['alsendo_connect_settings_general_global_api_type'] )
					&& 'ecolet' === sanitize_text_field( wp_unslash( $_POST['alsendo_connect_settings_general_global_api_type'] ) )
						&& ! empty( $_POST['save'] )
		) {

			$config = array(
				'connected' => false,
			);

				// check connection on settings page.
			$connection = $ecolet->check_connection_on_settings_save();
			if ( ! empty( $connection['error'] ) ) {

				$this->ecolet_clear_settings();

				( new Alerts() )->add_error(
					'Alsendo Connect: ' . esc_html__( 'probably wrong credentials', 'alsendo-connect' )
				);
				( new Alerts() )->add_error(
					esc_html__( 'Details:', 'alsendo-connect' ) . ' ' . esc_html( $connection['error'] )
				);

			} else {

				$config = array(
					'connected' => true,
				);

				// maybe refresh services.
				$ecolet_services = $ecolet->get_service_structure_ecolet();
			}

			wp_add_inline_script(
				'alsendo_connect_admin-js',
				'window.alsendo_ecolet_api = ' . wp_json_encode( $config ) . ';'
			);

		}

		return array(

			array(
				'id'                       => $this->get_setting_id( 'refresh_settings' ),
				'title'                    => '',
				'type'                     => 'checkbox',
				'label'                    => '',
				'default'                  => 'no',
				'visible_on_order_details' => false,
			),

			array(
				'title'       => esc_html__( 'Select API', 'alsendo-connect' ),
				'type'        => 'title',
				'description' => '',
				'id'          => 'alsendo_connect_api_settings',
			),

			array(
				'title'       => esc_html__( 'API', 'alsendo-connect' ),
				'id'          => $this->get_setting_id( 'global_api_type' ),
				'type'        => 'select',
				'description' => '',
				'default'     => 'none',
				'desc_tip'    => true,
				'options'     => array(
					'none'    => esc_html__( 'Select API', 'alsendo-connect' ),
					'apaczka' => esc_html__( 'Apaczka', 'alsendo-connect' ),
					'ecolet'  => esc_html__( 'Ecolet', 'alsendo-connect' ),
					'zaslat'  => esc_html__( 'Zaslat', 'alsendo-connect' ),
				),
			),

			array(
				'title'       => esc_html__( 'API type', 'alsendo-connect' ),
				'id'          => $this->get_setting_id( 'apaczka_api_type' ),
				'type'        => 'select',
				'description' => '',
				'default'     => 'prod',
				'desc_tip'    => true,
				'options'     => array(
					'stage' => esc_html__( 'Staging', 'alsendo-connect' ),
					'prod'  => esc_html__( 'Production', 'alsendo-connect' ),
				),
				'class'       => 'alsendo_connect_apaczka_setting',
			),

			array(
				'id'                       => 'alsendo_connect_settings_nonce',
				'title'                    => '',
				'type'                     => 'text',
				'label'                    => '',
				'default'                  => esc_attr( wp_create_nonce( 'alsendo_connect_nonce_param' ) ),
				'visible_on_order_details' => false,
			),

			array(
				'title'    => esc_html__( 'Apaczka App ID', 'alsendo-connect' ),
				'id'       => $this->get_setting_id( 'app_id' ),
				'css'      => '',
				'default'  => '',
				'type'     => 'text',
				'desc_tip' => false,
				'class'    => 'alsendo_connect_apaczka_setting',
			),

			array(

				'title'       => esc_html__( 'Apaczka App Secret', 'alsendo-connect' ),
				'id'          => $this->get_setting_id( 'app_secret' ),
				'type'        => 'password',
				'description' => esc_html__( 'Apaczka App Secret', 'alsendo-connect' ),
				'default'     => '',
				'desc_tip'    => true,
				'class'       => 'alsendo_connect_apaczka_setting',
			),

			array(
				'id'   => 'alsendo_connect_api_settings',
				'type' => 'sectionend',
			),

			array(
				'title'       => '',
				'type'        => 'title',
				'description' => '',
				'id'          => 'ecolet_api_settings',
			),

			array(
				'title'    => esc_html__( 'Ecolet panel e-mail', 'alsendo-connect' ),
				'id'       => $this->get_setting_id( 'ecolet_email' ),
				'css'      => '',
				'default'  => '',
				'type'     => 'email',
				'desc_tip' => false,
				'class'    => 'alsendo_connect_ecolet_setting',
			),

			array(
				'title'    => esc_html__( 'Ecolet panel password', 'alsendo-connect' ),
				'id'       => $this->get_setting_id( 'ecolet_password' ),
				'css'      => '',
				'default'  => '',
				'type'     => 'password',
				'desc_tip' => false,
				'class'    => 'alsendo_connect_ecolet_setting',
			),

			array(
				'title'    => esc_html__( 'Ecolet Client ID', 'alsendo-connect' ),
				'id'       => $this->get_setting_id( 'ecolet_client_id' ),
				'css'      => '',
				'default'  => '',
				'type'     => 'text',
				'desc_tip' => false,
				'class'    => 'alsendo_connect_ecolet_setting',
			),

			array(

				'title'       => esc_html__( 'Ecolet Client Secret', 'alsendo-connect' ),
				'id'          => $this->get_setting_id( 'ecolet_app_secret' ),
				'type'        => 'password',
				'description' => esc_html__( 'Ecolet Client Secret', 'alsendo-connect' ),
				'default'     => '',
				'desc_tip'    => true,
				'class'       => 'alsendo_connect_ecolet_setting',
			),

			array(
				'title'       => esc_html__( 'API type', 'alsendo-connect' ),
				'id'          => $this->get_setting_id( 'ecolet_api_type' ),
				'type'        => 'select',
				'description' => '',
				'default'     => 'prod',
				'desc_tip'    => true,
				'options'     => array(
					'stage' => esc_html__( 'Staging', 'alsendo-connect' ),
					'prod'  => esc_html__( 'Production', 'alsendo-connect' ),
				),
				'class'       => 'alsendo_connect_ecolet_setting',
			),

			array(
				'title'       => '',
				'id'          => 'ecolet_auth_button',
				'type'        => 'text',
				'description' => '',
				'default'     => '',
				'desc_tip'    => false,
				'class'       => '',
			),

			array(
				'id'   => 'ecolet_api_settings',
				'type' => 'sectionend',
			),

			array(
				'title'       => '',
				'type'        => 'title',
				'description' => '',
				'id'          => 'zaslat_api_settings',
			),

			array(
				'title'    => esc_html__( 'Zaslat API key', 'alsendo-connect' ),
				'id'       => $this->get_setting_id( 'zaslat_api_key' ),
				'css'      => '',
				'default'  => '',
				'type'     => 'text',
				'desc_tip' => false,
				'class'    => 'alsendo_connect_zaslat_setting',
			),

			array(
				'title'       => esc_html__( 'API type', 'alsendo-connect' ),
				'id'          => $this->get_setting_id( 'zaslat_api_type' ),
				'type'        => 'select',
				'description' => '',
				'default'     => 'prod',
				'desc_tip'    => true,
				'options'     => array(
					'stage' => esc_html__( 'Staging', 'alsendo-connect' ),
					'prod'  => esc_html__( 'Production', 'alsendo-connect' ),
				),
				'class'       => 'alsendo_connect_zaslat_setting',
			),

			array(
				'id'   => 'zaslat_api_settings',
				'type' => 'sectionend',
			),
		);
	}



	/**
	 * Creates Zaslat sender settings configuration from address book.
	 *
	 * Generates a settings array with address ID dropdown options formatted
	 * with contact details (name, street, city, zip, country) for sender
	 * selection in the Zaslat shipping configuration.
	 *
	 * @param array $address_book Array of addresses with contact and location data.
	 * @return array Settings configuration array with formatted address options.
	 */
	public function get_zaslat_sender_settings( $address_book ) {

		$address_id_options = array();

		foreach ( $address_book as $key => $val ) {

			$address = $key . ' (';
			if ( ! empty( $val['firstname'] ) ) {
				$address .= esc_html( $val['firstname'] );
			}
			if ( ! empty( $val['surname'] ) ) {
				$address .= ' ' . esc_html( $val['surname'] );
			}
			if ( ! empty( $val['street'] ) ) {
				$address .= ', ' . esc_html( $val['street'] );
			}
			if ( ! empty( $val['city'] ) ) {
				$address .= ', ' . esc_html( $val['city'] );
			}
			if ( ! empty( $val['zip'] ) ) {
				$address .= ' ' . esc_html( $val['zip'] );
			}
			if ( ! empty( $val['country'] ) ) {
				$address .= ', ' . esc_html( $val['country'] );
			}

			$address .= ')';

			$address_id_options[ $key ] = $address;

		}

		return array(
			array(
				'title'       => esc_html__( 'Sender details', 'alsendo-connect' ),
				'id'          => 'sender_details',
				'type'        => 'title',
				'description' => '',
			),
			array(
				'title'       => esc_html__( 'Address ID', 'alsendo-connect' ),
				'id'          => $this->get_setting_id( 'zaslat_address_id' ),
				'type'        => 'select',
				'description' => '',
				'default'     => '',
				'desc_tip'    => true,
				'options'     => $address_id_options,
			),
			array(
				'id'   => 'sender_details',
				'type' => 'sectionend',
			),
		);
	}

	/**
	 *  Get sender settings
	 */
	public function get_sender_settings(): array {

		$sender_settings = array();

		$api_type = alsendo_connect()->get_main_settings_api();

		$sender_settings[] = array(
			'id'   => 'sender_details',
			'type' => 'sectionend',
		);

		return $sender_settings;
	}

	/**
	 * Get parcel settings
	 *
	 * @param mixed $services $services.
	 *
	 * @return array
	 */
	public function get_parcel_settings( $services = null ): array {

		$settings = array();

		$api_type = alsendo_connect()->get_main_settings_api();

		$options_hours = array();
		for ( $h = 9; $h < 20; $h++ ) {
			$options_hours[ $h . ':00' ] = $h . ':00';
			if ( $h < 19 ) {
				$options_hours[ $h . ':30' ] = $h . ':30';
			}
		}

		// dispatch point inputs.
		$dispatch_point_inpost = array(
			'id'                       => $this->get_setting_id( 'dispath_point_inpost' ),
			'title'                    => esc_html__(
				'Default dispatch point (InPost)',
				'alsendo-connect'
			),
			'type'                     => 'text',
			'description'              => '',
			'default'                  => '',
			'desc_tip'                 => true,
			'visible_on_order_details' => true,
		);

		$dispatch_point_kurier48 = array(
			'id'                       => $this->get_setting_id( 'dispath_point_kurier48' ),
			'title'                    => esc_html__(
				'Default dispatch point (Kurier48)',
				'alsendo-connect'
			),
			'type'                     => 'text',
			'description'              => '',
			'default'                  => '',
			'desc_tip'                 => true,
			'visible_on_order_details' => true,
		);

		$dispatch_point_ups = array(
			'id'                       => $this->get_setting_id( 'dispath_point_ups' ),
			'title'                    => esc_html__(
				'Default dispatch point (UPS)',
				'alsendo-connect'
			),
			'type'                     => 'text',
			'description'              => '',
			'default'                  => '',
			'desc_tip'                 => true,
			'visible_on_order_details' => true,
		);

		$dispatch_point_dpd = array(
			'id'                       => $this->get_setting_id( 'dispath_point_dpd' ),
			'title'                    => esc_html__(
				'Default dispatch point DPD',
				'alsendo-connect'
			),
			'type'                     => 'text',
			'description'              => '',
			'default'                  => '',
			'desc_tip'                 => true,
			'visible_on_order_details' => true,
		);

		$dispatch_point_dhl = array(
			'id'                       => $this->get_setting_id( 'dispath_point_dhl' ),
			'title'                    => esc_html__(
				'Default dispatch point DHL',
				'alsendo-connect'
			),
			'type'                     => 'text',
			'description'              => '',
			'default'                  => '',
			'desc_tip'                 => true,
			'visible_on_order_details' => true,
		);

		$dispatch_point_cargus = array(
			'id'                       => $this->get_setting_id( 'dispath_point_cargus' ),
			'title'                    => esc_html__(
				'Default dispatch point Cargus',
				'alsendo-connect'
			),
			'type'                     => 'text',
			'description'              => '',
			'default'                  => '',
			'desc_tip'                 => true,
			'visible_on_order_details' => true,
		);

		$dispatch_point_fan_courier = array(
			'id'                       => $this->get_setting_id( 'dispath_point_fan_courier' ),
			'title'                    => esc_html__(
				'Default dispatch point Fan Couirier',
				'alsendo-connect'
			),
			'type'                     => 'text',
			'description'              => '',
			'default'                  => '',
			'desc_tip'                 => true,
			'visible_on_order_details' => true,
		);

		$dispatch_point_gls = array(
			'id'                       => $this->get_setting_id( 'dispath_point_gls' ),
			'title'                    => esc_html__(
				'Default dispatch point GLS',
				'alsendo-connect'
			),
			'type'                     => 'text',
			'description'              => '',
			'default'                  => '',
			'desc_tip'                 => true,
			'visible_on_order_details' => true,
		);

		$dispatch_point_sameday = array(
			'id'                       => $this->get_setting_id( 'dispath_point_sameday' ),
			'title'                    => esc_html__(
				'Default dispatch point Sameday',
				'alsendo-connect'
			),
			'type'                     => 'text',
			'description'              => '',
			'default'                  => '',
			'desc_tip'                 => true,
			'visible_on_order_details' => true,
		);

		$settings[] = array(
			'title'       => esc_html__(
				'Default shipping settings',
				'alsendo-connect'
			),
			'type'        => 'title',
			'id'          => 'default_shipping_settings',

			'description' => '',
		);

		if ( 'ecolet' === $api_type ) {
			$settings[] = array(
				'id'                       => $this->get_setting_id( 'ecolet_checkout_additional_fields' ),
				'title'                    => esc_html__( 'Set additional fields on checkout for address', 'alsendo-connect' ),
				'type'                     => 'checkbox',
				'label'                    => '',
				'default'                  => 'no',
				'visible_on_order_details' => false,
			);

			$settings[] = array(
				'id'                       => $this->get_setting_id( 'ecolet_day_to_send' ),
				'title'                    => esc_html__( 'Allow same-day pickup (send today) - for bulk Shipment creation only', 'alsendo-connect' ),
				'type'                     => 'checkbox',
				'label'                    => '',

				'default'                  => 'no',
				'desc_tip'                 => esc_html__(
					'When enabled: pickup date defaults to today. If the carrier rejects same-day pickup, it will automatically retry with tomorrow. When disabled: pickup date defaults to tomorrow (next business day).',
					'alsendo-connect'
				),
				'visible_on_order_details' => false,
			);
		}

		if ( 'apaczka' === $api_type || 'ecolet' === $api_type ) {

			$settings[] = array(
				'id'                       => $this->get_setting_id( 'declared_content_auto' ),
				'title'                    => esc_html__(
					'Automatically complete the "Declaration of value" with the value of the order',
					'alsendo-connect'
				),
				'type'                     => 'checkbox',
				'label'                    => '',
				'default'                  => 'yes',
				'visible_on_order_details' => true,
			);

			$settings[] = array(
				'id'                       => $this->get_setting_id( 'set_order_status_completed' ),
				'title'                    => esc_html__(
					'Change order status to Completed after shipment created?',
					'alsendo-connect'
				),
				'type'                     => 'checkbox',
				'label'                    => '',
				'default'                  => 'yes',
				'visible_on_order_details' => true,
				'custom_attributes'        => array(
					'checked' => 'checked',
				),
			);

			$settings[] = array(
				'id'                       => $this->get_setting_id( 'map_debug_mode' ),
				'title'                    => esc_html__( 'An alternative way to show the map button', 'alsendo-connect' ),
				'type'                     => 'checkbox',
				'label'                    => '',
				'default'                  => 'no',
				'visible_on_order_details' => false,
			);
		}

		if ( 'apaczka' === $api_type ) {
			$settings[] = $dispatch_point_inpost;
			$settings[] = $dispatch_point_kurier48;
			$settings[] = $dispatch_point_ups;
			$settings[] = $dispatch_point_dpd;
			$settings[] = $dispatch_point_dhl;
		}

		if ( 'ecolet' === $api_type ) {
			$settings[] = $dispatch_point_dpd;
			$settings[] = $dispatch_point_cargus;
			$settings[] = $dispatch_point_fan_courier;
			$settings[] = $dispatch_point_gls;
			$settings[] = $dispatch_point_sameday;
		}

		$settings[] = array(
			'id'   => 'default_shipping_settings',
			'type' => 'sectionend',
		);

		return $settings;
	}




	/**
	 * Get setting id
	 *
	 * @param string $key $key.
	 *
	 * @return string
	 */
	public function get_setting_id( $key ): string {
		return Plugin::APP_PREFIX . '_settings_general_' . $key;
	}


	/**
	 * Get current sender config
	 *
	 * @return array
	 */
	public function get_current_sender_config(): array {
		$sender_config = array();

		$settings       = $this->get_sender_settings();
		$detect_section = Plugin::APP_PREFIX . '_settings_general_sender_';

		foreach ( $settings as $setting ) {
			if ( ! isset( $setting['id'] ) ) {
				continue;
			}
			if ( strpos( $setting['id'], $detect_section ) === 0 ) {
				$sender_config[ str_replace(
					$this->get_setting_id( 'sender_' ),
					'',
					$setting['id']
				) ] = get_option( $setting['id'] );
			}
		}

		return $sender_config;
	}

	/**
	 * Get current sender template name
	 *
	 * @return string
	 */
	public function get_current_sender_template_name(): string {
		$current_sender_template_name = get_option(
			$this->get_setting_id( 'select_sender_template' )
		);

		return ! empty( $current_sender_template_name )
			? $current_sender_template_name : '';
	}

	/**
	 * Get current parcel template name
	 *
	 * @return string
	 */
	public function get_current_parcel_template_name(): string {
		$current_parcel_template_name = get_option(
			$this->get_setting_id( 'select_package_template' )
		);

		return ! empty( $current_parcel_template_name )
			? $current_parcel_template_name : '';
	}



	public function get_debug_settings() {

		$api_type = alsendo_connect()->get_main_settings_api();
		if ( 'ecolet' === $api_type ) {
			$help_title = esc_html__( 'Support Ecolet:', 'alsendo-connect' );
			$help_url   = 'https://ecolet.ro/contact/';
		} elseif ( 'zaslat' === $api_type ) {
			$help_title = esc_html__( 'Support Zaslat:', 'alsendo-connect' );
			$help_url   = 'https://www.zaslat.cz/kontakt';
		} else {
			$help_title = esc_html__( 'Support Apaczka:', 'alsendo-connect' );
			$help_url   = 'https://panel.apaczka.pl/formularz-kontaktowy';
		}

		$global_settings_integration = new Global_Settings_Integration();

		return array(

			array(
				'title'       => '',
				'type'        => 'title',
				'id'          => 'debug_settings',
				'description' => '',
			),

			$global_settings_integration->get_manage_package_templates_btn(),

			array(
				'id'                       => 'help_settings',
				'visible_on_order_details' => false,
				'title'                    => esc_html__( 'Help', 'alsendo-connect' ),
				'type'                     => 'title',
				'desc'                     => '<b id="alsendo-connect-help-title">' . esc_html( $help_title ) . '</b><br>'
							. '<b>' . esc_html__( 'In case of questions/problems related to the plugin, please contact us via the ', 'alsendo-connect' ) . '</b>'
							. '<a href="' . esc_html( $help_url ) . '" target="_blank">'
							. esc_html__( 'Contact form', 'alsendo-connect' ) . '</a><br>'
							. esc_html__( 'Probably you can find some logs ', 'alsendo-connect' )
							. '<a href=" ' . esc_url( alsendo_connect()->get_woocommerce_logs_section_url() ) . ' " target="_blank">'
							. esc_html__( 'here', 'alsendo-connect' ) . '</a><br>',
			),

			array(
				'id'   => 'debug_settings',
				'type' => 'sectionend',
			),
		);
	}


	/**
	 * Clears all Ecolet API-related settings and cached data.
	 *
	 * Removes stored API tokens, service structure cache, timestamps, and error flags
	 * from WordPress options. Used for resetting Ecolet integration state.
	 *
	 * @return void
	 */
	public function ecolet_clear_settings() {
		delete_option( 'alsendo_ecolet_api_returned_error' );
		delete_option( 'alsendo_connect_ecolet_service_structure' );
		delete_option( 'alsendo_connect_ecolet_service_structure_timestamp' );
		delete_option( 'alsendo_connect_ecolet_token' );
		delete_option( 'alsendo_connect_ecolet_refresh_token' );
	}
}
