<?php

if (class_exists('GF_Field')) {
	class OrderBrochureList extends GF_Field_Select
	{
		public $type = 'order_brochures_list';

		// public function __construct()
		// {
		// 	parent::__construct();
		// 	$this->buildChoices();
		// }

		private function buildChoices()
		{
			$brochures_query = new WP_Query(array(
				'post_type' => 'brochures',
				'posts_per_page' => -1,
				'post_status' => 'publish',
				'order' => 'ASC',
				'orderby' => 'title',
				'meta_key'      => 'brochure_pdf',
				'meta_value' => false,
				'meta_compare' => '!=',
				'post__not_in' => [4431, 4436, 11404, 11411, 1582, 4294, 3353, 4297]
			));
			$choices = [];

			$sortedBrochuresPosts = sort_posts_per_thematiques_priority($brochures_query);

			foreach ($sortedBrochuresPosts->posts as $key => $post) {
				array_push($choices, ['text' => $post->post_title, 'slug' => $post->post_name, 'ID' =>  $post->ID]);
			}
			$this->choices = $choices;
		}

		public function get_form_editor_field_title()
		{
			return esc_attr__('Listes des brochures disponibles à la commande', 'homegrade-theme__texte-fonctionnel');
		}
		public function get_form_editor_button()
		{
			return [
				'group' => 'advanced_fields',
				'text'  => $this->get_form_editor_field_title(),
			];
		}
		public function get_form_editor_field_icon()
		{
			return 'dashicons-list-view';
		}
		public function get_form_editor_field_settings()
		{
			return [
				'label_setting',
				'choices_setting',
				'description_setting',
				'rules_setting',
				'error_message_setting',
				'css_class_setting',
				'conditional_logic_field_setting'
			];
		}

		// public $choices = [
		// 	['text' => 'Publication 1'],
		// 	['text' => 'Publication 2'],
		// 	['text' => 'Publication 3'],
		// ];

		public function is_value_submission_array()
		{
			return true;
		}

		public function get_field_input($form, $value = '', $entry = null)
		{
			$this->buildChoices();
			$form_id         = $form['id'];
			$id = $this->id;

			ob_start();
			include 'template-field-order-brochures.php';
			$table = ob_get_clean();


			return $table;
		}

		private function translateValueArray($value)
		{
			$this->buildChoices();

			$table_value = [];
			$counter = 0;

			foreach ($this->choices as $brochure) {
				// $isEmpty = empty($value[$counter]) && empty($value[$counter + 1]);

				// if ($isEmpty) {
				// 	$counter += 4;
				// 	continue;
				// }

				$currentUserLanguage = apply_filters('wpml_current_language', null);

				$ID_FR = apply_filters('wpml_object_id', $brochure['ID'], 'brochures', false, 'fr') ?? 0;
				$ID_NL = apply_filters('wpml_object_id', $brochure['ID'], 'brochures', false, 'nl') ?? 0;


				$table_value[$brochure['text']]['quantity_fr'] = $value[$counter] ?? 0;
				$table_value[$brochure['text']]['quantity_nl'] = $value[$counter + 1] ?? 0;

				$table_value[$brochure['text']]['id_fr'] = 	$ID_FR;
				$table_value[$brochure['text']]['id_nl'] = 	$ID_NL;
				$counter += 4;
			}
			return $table_value;
		}

		public function get_value_save_entry($value, $form, $input_name, $lead_id, $lead)
		{

			if (empty($value)) {
				$value = '';
			} else {
				$table_value = $this->translateValueArray($value);
				$value = serialize($table_value);
			}

			return $value;
		}


		private function PrettyListBrochureOrder($value)
		{
			$brochureOrderPreviewHtml = '<ul>';

			foreach ($value as $brochure => $quantities) {

				$brochureOrderAmount = null;


				if ($quantities["quantity_fr"]) {
					$brochureOrderAmount .= '<li>' . __("Quantité FR: ", "homegrade-theme__texte-fonctionnel") . '<span class="brochure_quantity">' . $quantities["quantity_fr"]  . '</span></li>';
				}
				if ($quantities["quantity_nl"]) {
					$brochureOrderAmount .= '<li>' . __("Quantité NL: ", "homegrade-theme__texte-fonctionnel") . '<span class="brochure_quantity">' .   $quantities["quantity_nl"] . '</span></li>';
				}

				if (!$brochureOrderAmount) continue;


				if (!empty($brochureOrderAmount)) {
					$brochureOrderPreviewHtml .= '<li><h3>' . $brochure . '</h3><ul class="days">' . $brochureOrderAmount . '</ul></li>';
				}
			}
			$brochureOrderPreviewHtml .= '</ul>';
			return $brochureOrderPreviewHtml;
		}


		public function get_value_entry_list($value, $entry, $field_id, $columns, $form)
		{
			return __('Enter details to see delivery details', 'homegrade-theme__texte-fonctionnel');
		}

		public function get_value_entry_detail($value, $currency = '', $use_text = false, $format = 'html', $media = 'screen')
		{
			$value = maybe_unserialize($value);
			if (empty($value)) {
				return;
			}
			$str = $this->PrettyListBrochureOrder($value);
			return $str;
		}

		public function get_value_merge_tag($value, $input_id, $entry, $form, $modifier, $raw_value, $url_encode, $esc_html, $format, $nl2br)
		{
			return $this->PrettyListBrochureOrder($value);
		}
	}
	GF_Fields::register(new OrderBrochureList());
}
