<?php

namespace Inspire_Labs\Alsendo_Connect;

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

/**
 * Sender_Settings_Templates_Helper
 */
class Sender_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 . 'sender_opts_templates';
	}

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

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

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

		return wp_json_encode( $sender_templates_arr );
	}

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

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

		$prefix = 'alsendo_connect_settings_general_sender_';

		$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 . 'is_residential'      => $template['is_residential'] ?? '0',
				$prefix . 'country'             => $template['country'] ?? '',
				$prefix . 'company_name'        => $template['company_name'] ?? '',
				$prefix . 'first_name'          => $template['first_name'] ?? '',
				$prefix . 'last_name'           => $template['last_name'] ?? '',
				$prefix . 'street'              => $template['street'] ?? '',
				$prefix . 'building_number'     => $template['building_number'] ?? '',
				$prefix . 'block'               => $template['block'] ?? '',
				$prefix . 'entrance'            => $template['entrance'] ?? '',
				$prefix . 'floor'               => $template['floor'] ?? '',
				$prefix . 'apartment_number'    => $template['apartment_number'] ?? '',
				$prefix . 'postal_code'         => $template['postal_code'] ?? '',
				$prefix . 'province'            => $template['province'] ?? '',
				$prefix . 'city'                => $template['city'] ?? '',
				$prefix . 'contact_person'      => $template['contact_person'] ?? '',
				$prefix . 'phone'               => $template['phone'] ?? '',
				$prefix . 'email'               => $template['email'] ?? '',
				$prefix . 'bank_account_number' => $template['bank_account_number'] ?? '',
			);

			$result[ $slug ] = array(
				'name'    => $template['name'] ?? '',
				'options' => $options,
			);
		}

		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( Sender_Template_Manager::class ) ) {
			$new_data = Sender_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;
	}

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

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

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

		return ! empty( $sender_templates_arr ) ? $sender_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;
	}

	/**
	 * Create
	 *
	 * @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 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 );
		}
	}
}
