<?php

namespace Inspire_Labs\Alsendo_Connect;

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

/**
 * Gateway_Settings_Templates_Helper
 */
class Gateway_Settings_Templates_Helper {


	/**
	 * Init
	 */
	public function init() {
	}

	/**
	 * Get ajax action name
	 *
	 * @return string
	 */
	private function get_ajax_action_name(): string {
		return 'wp_ajax_' . Plugin::APP_PREFIX . 'get_template';
	}

	/**
	 * Get template option id
	 *
	 * @return string
	 */
	private function get_template_option_id(): string {
		return Plugin::APP_PREFIX . 'gateway_opts_templates';
	}

	/**
	 * Get all templates JSON
	 *
	 * @return false|string
	 */
	public function get_all_templates_json() {
		$package_templates_arr = array();

		$legacy = get_option( $this->get_template_option_id() );
		if ( is_array( $legacy ) && ! empty( $legacy ) ) {
			$package_templates_arr = $legacy;
		}

		if ( class_exists( Shipment_Template_Manager::class ) ) {
			$new_templates = $this->build_templates_from_new_manager();
			foreach ( $new_templates as $slug => $tpl ) {
				$package_templates_arr[ $slug ] = $tpl;
			}
		}

		return wp_json_encode( $package_templates_arr );
	}

	/**
	 * Build templates array from new Shipment_Template_Manager in the old format.
	 *
	 * @return array
	 */
	private function build_templates_from_new_manager(): array {
		$manager   = Shipment_Template_Manager::get_instance();
		$templates = $manager->get_data();

		if ( empty( $templates ) ) {
			return array();
		}

		$prefix = 'alsendo_connect_settings_general_';

		$global_options = array(
			$prefix . 'declared_content_auto'      => get_option( $prefix . 'declared_content_auto', '' ),
			$prefix . 'set_order_status_completed' => get_option( $prefix . 'set_order_status_completed', '' ),
			$prefix . 'pickup_hour_from'           => get_option( $prefix . 'pickup_hour_from', '' ),
			$prefix . 'pickup_hour_to'             => get_option( $prefix . 'pickup_hour_to', '' ),
			$prefix . 'dispath_point_inpost'       => get_option( $prefix . 'dispath_point_inpost', '' ),
			$prefix . 'dispath_point_kurier48'     => get_option( $prefix . 'dispath_point_kurier48', '' ),
			$prefix . 'dispath_point_ups'          => get_option( $prefix . 'dispath_point_ups', '' ),
			$prefix . 'dispath_point_dpd'          => get_option( $prefix . 'dispath_point_dpd', '' ),
			$prefix . 'dispath_point_dhl'          => get_option( $prefix . 'dispath_point_dhl', '' ),
			$prefix . 'dispath_point_cargus'       => get_option( $prefix . 'dispath_point_cargus', '' ),
			$prefix . 'dispath_point_fan_courier'  => get_option( $prefix . 'dispath_point_fan_courier', '' ),
			$prefix . 'dispath_point_gls'          => get_option( $prefix . 'dispath_point_gls', '' ),
			$prefix . 'dispath_point_sameday'      => get_option( $prefix . 'dispath_point_sameday', '' ),
		);

		$result = array();

		foreach ( $templates as $template ) {
			$slug = ! empty( $template['template_slug'] )
				? $template['template_slug']
				: sanitize_title( $template['name'] ?? '' );

			if ( empty( $slug ) ) {
				continue;
			}

			$options = array(
				$prefix . 'shipping_method'     => $template['shipping_method'] ?? '',
				$prefix . 'parcel_type'         => $template['parcel_type'] ?? '',
				$prefix . 'is_nstd'             => $template['is_nstd'] ?? 'no',
				$prefix . 'package_length'      => $template['package_length'] ?? '',
				$prefix . 'package_width'       => $template['package_width'] ?? '',
				$prefix . 'package_height'      => $template['package_height'] ?? '',
				$prefix . 'package_weight'      => $template['package_weight'] ?? '',
				$prefix . 'package_contents'    => $template['package_contents'] ?? '',
				$prefix . 'custom_text_content' => $template['custom_text_content'] ?? '',
				$prefix . 'declared_content'    => $template['declared_content'] ?? '',
			);

			$options = array_merge( $options, $global_options );

			if ( ! empty( $template['pickup_hour_from'] ) ) {
				$options[ $prefix . 'pickup_hour_from' ] = $template['pickup_hour_from'];
			}
			if ( ! empty( $template['pickup_hour_to'] ) ) {
				$options[ $prefix . 'pickup_hour_to' ] = $template['pickup_hour_to'];
			}

			$result[ $slug ] = array(
				'name'    => $template['name'] ?? '',
				'options' => $options,
				'additional_parcels' => ! empty( $template['additional_parcels'] ) && is_array( $template['additional_parcels'] )
					? array_values( $template['additional_parcels'] )
					: array(),
			);
		}

		return $result;
	}

	/**
	 * Get all templates list
	 *
	 * @return array|null
	 */
	public function get_all_templates_list(): ?array {
		$return = array();

		$legacy = get_option( $this->get_template_option_id() );
		if ( is_array( $legacy ) ) {
			foreach ( $legacy as $k => $template ) {
				$return[ $k ] = $template['name'];
			}
		}

		if ( class_exists( Shipment_Template_Manager::class ) ) {
			$new_data = Shipment_Template_Manager::get_instance()->get_data();
			foreach ( $new_data as $template ) {
				$slug = ! empty( $template['template_slug'] )
					? $template['template_slug']
					: sanitize_title( $template['name'] ?? '' );
				if ( ! empty( $slug ) && ! empty( $template['name'] ) ) {
					$return[ $slug ] = $template['name'];
				}
			}
		}

		return $return;
	}

	/**
	 * Create template
	 *
	 * @param array  $options $options.
	 * @param string $name $name.
	 *
	 * @return void
	 */
	public function create( array $options, string $name ) {

		$option_id = $this->get_template_option_id();
		$templates = get_option( $option_id );
		$slug      = sanitize_title( $name );

		if ( ! is_array( $templates ) ) {
			$templates = array();
		}

		if ( ! empty( $name ) && ! isset( $templates[ $slug ] ) ) {
			$templates[ sanitize_title( $name ) ] = array(
				'name'    => $name,
				'options' => $options,
			);
			update_option( $option_id, $templates );
		}
	}


	/**
	 * Update template
	 *
	 * @param array  $options $options.
	 * @param string $slug $slug.
	 *
	 * @return void
	 */
	public function update_template( array $options, string $slug ) {
		$option_id = $this->get_template_option_id();
		$templates = get_option( $option_id );

		if ( ! is_array( $templates ) ) {
			return;
		}

		if ( ! isset( $templates[ $slug ] ) ) {
			return;
		}

		$template_name = $templates[ $slug ]['name'];

		if ( ! empty( $template_name ) && ! empty( $options ) ) {
			$templates[ $slug ] = array(
				'name'    => $template_name,
				'options' => $options,
			);
			update_option( $option_id, $templates );
		}
	}

	/**
	 * Get all templates
	 *
	 * @return array|null
	 */
	public function get_all_templates(): ?array {

		$package_templates_arr = array();

		$legacy = get_option( $this->get_template_option_id() );
		if ( is_array( $legacy ) && ! empty( $legacy ) ) {
			$package_templates_arr = $legacy;
		}

		if ( class_exists( Shipment_Template_Manager::class ) ) {
			$new_templates = $this->build_templates_from_new_manager();
			foreach ( $new_templates as $slug => $tpl ) {
				$package_templates_arr[ $slug ] = $tpl;
			}
		}

		return ! empty( $package_templates_arr ) ? $package_templates_arr : null;
	}

	/**
	 * Get template name by template slug
	 *
	 * @param string $slug $slug.
	 *
	 * @return string|null
	 */
	public function get_template_name_by_template_slug( string $slug ): ?string {
		$all = $this->get_all_templates_list();
		if ( isset( $all[ $slug ] ) ) {
			return $all[ $slug ];
		}

		return null;
	}

	/**
	 * Rename template
	 *
	 * @param string $old_slug $old_slug.
	 * @param string $new_name $new_name.
	 *
	 * @return bool
	 */
	public function rename_template( $old_slug, $new_name ): ?string {
		$new_slug = sanitize_title( $new_name );

		if ( empty( $new_slug ) ) {
			return null;
		}

		if ( $new_slug === $old_slug ) {
			return null;
		}

		$all_templates = $this->get_all_templates();

		if ( empty( $all_templates ) ) {
			return null;
		}

		if ( key_exists( $new_slug, $all_templates ) ) {
			return null;
		}

		if ( ! key_exists( $old_slug, $all_templates ) ) {
			return null;
		}

		$template_data = $all_templates[ $old_slug ];
		unset( $all_templates[ $old_slug ] );
		$template_data['name']      = $new_name;
		$all_templates[ $new_slug ] = $template_data;

		update_option( $this->get_template_option_id(), $all_templates, false );

		return $new_slug;
	}

	/**
	 * Get by name
	 *
	 * @param string $name $name.
	 *
	 * @return array|null
	 */
	public function get_by_name( string $name ): ?array {
		$templates = get_option( $this->get_template_option_id() );
		$slug      = sanitize_title( $name );

		if ( ! is_array( $templates ) && isset( $templates[ $slug ] ) ) {
			return $templates[ $slug ];
		}

		return null;
	}


	/**
	 * Remove by slug
	 *
	 * @param string $slug $slug.
	 *
	 * @return void
	 */
	public function remove_by_slug( string $slug ) {
		$option_id = $this->get_template_option_id();
		$templates = get_option( $option_id );

		if ( is_array( $templates ) && isset( $templates[ $slug ] ) ) {
			unset( $templates[ $slug ] );
			update_option( $option_id, $templates );
		}
	}

	/**
	 * Remove by name
	 *
	 * @param string $name $name.
	 *
	 * @return void
	 */
	public function remove_by_name( string $name ) {
		$option_id = $this->get_template_option_id();
		$templates = get_option( $option_id );
		$slug      = sanitize_title( $name );

		if ( ! is_array( $templates ) && isset( $templates[ $slug ] ) ) {
			unset( $templates[ $slug ] );
			update_option( $option_id, $templates );
		}
	}
}
