<?php

namespace KaliForms\Inc\Backend;

if (!defined('ABSPATH')) {
	exit;
}

class Modula_Integration
{
	/**
	 * Plugin slug
	 *
	 * @var string
	 */
	protected $slug = 'kaliforms-pro';
	/**
	 * Parent plugin slug
	 *
	 * @var string
	 */
	protected $parent_slug = 'kaliforms';
	public function __construct()
	{
		add_filter($this->parent_slug . '_meta_save_fields', [$this, 'add_meta_fields']);
		add_filter($this->parent_slug . '_jsvars_object', [$this, 'add_values_to_vars'], 999);
		add_filter($this->parent_slug . '_form_options', [$this, 'alter_form_options'], 999);
		add_action($this->parent_slug . '_after_form_process_action', [$this, 'create_or_update_gallery']);
	}

	public function add_meta_fields($meta)
	{
		$meta->add_fields(
			['id' => 'modula_integration', 'sanitize' => 'KaliForms\Inc\Backend\Sanitizers::sanitize_boolean'],
			['id' => 'modula_defaults_id', 'sanitize' => 'absint'],
			['id' => 'modula_gallery_name', 'sanitize' => 'sanitize_text_field'],
			['id' => 'modula_action', 'sanitize' => 'sanitize_text_field'],
			['id' => 'modula_gallery', 'sanitize' => 'absint']
		);

		return $meta;
	}

	public function get_options($id)
	{
		$modulaIntegration = get_post_meta($id, $this->parent_slug . '_modula_integration', true);
		$modulaDefaultsId  = get_post_meta($id, $this->parent_slug . '_modula_defaults_id', true);
		$modulaGalleryName = get_post_meta($id, $this->parent_slug . '_modula_gallery_name', true);
		$modulaAction = get_post_meta($id, $this->parent_slug . '_modula_action', true);
		$modulaGallery = get_post_meta($id, $this->parent_slug . '_modula_gallery', true);

		$data = [];
		$data['modulaInstalled'] = class_exists('Modula_CPT_Fields_Helper') ? true : false;
		$data['modulaIntegration'] = $modulaIntegration || false;
		$data['modulaDefaultsId']  = $modulaDefaultsId;
		$data['modulaDefaultsInstalled'] = defined('MODULA_DEFAULTS_VERSION') ? true : false;
		$data['modulaDefaults'] = $this->get_modula_defaults();
		$data['modulaGalleries'] = $this->get_modula_galleries();
		$data['modulaGalleryName'] = $modulaGalleryName;
		$data['modulaAction'] = $modulaAction;
		$data['modulaGallery'] = $modulaGallery;

		return $data;
	}

	public function alter_form_options($options)
	{
		return array_merge($options, $this->get_options($options['formId']));
	}

	public function add_values_to_vars($jsvars)
	{
		return array_merge($jsvars, $this->get_options($jsvars['formId']));
	}

	public function get_modula_galleries()
	{
		$modula_galleries = get_posts([
			'post_type'   => 'modula-gallery',
			'numberposts' => -1,
			'orderby'     => 'date',
			'order'       => 'ASC',
		]);

		$options = [];
		if ($modula_galleries) {
			foreach ($modula_galleries as $gallery) {
				$options[] = array(
					'id'    => absint($gallery->ID),
					'title' => ($gallery->post_title && '' != $gallery->post_title) ? esc_html($gallery->post_title) : esc_html__('Gallery ID ', 'kaliforms') . $gallery->ID,
				);
			}
		}

		return $options;
	}

	public function get_modula_defaults()
	{
		if (!defined('MODULA_DEFAULTS_VERSION')) return [];

		$modula_defaults = get_posts([
			'post_type'   => 'modula-defaults',
			'numberposts' => -1,
			'orderby'     => 'date',
			'order'       => 'ASC',
		]);

		$options = [];
		if ($modula_defaults) {
			foreach ($modula_defaults as $default) {
				$options[] = array(
					'id'    => absint($default->ID),
					'title' => ($default->post_title && '' != $default->post_title) ? esc_html($default->post_title) : esc_html__('Default ID ', 'kaliforms') . $default->ID,
				);
			}
		}

		return $options;
	}

	public function add_defaults_to_gallery($galleryId, $defaultId)
	{
		if (!class_exists('Modula_CPT_Fields_Helper')) {
			return;
		}

		$presetSettings  = wp_parse_args(get_post_meta(absint($defaultId), 'modula-settings', true), \Modula_CPT_Fields_Helper::get_defaults());
		$gallerySettings = get_post_meta(absint($galleryId), 'modula-settings', true);

		update_post_meta(absint($galleryId), 'modula-settings', wp_parse_args($presetSettings, $gallerySettings));

		$sorting = get_post_meta(absint($galleryId), 'modulaSorting', true);
		update_post_meta(absint($galleryId), 'modulaSorting', $sorting);
	}

	public function create_or_update_gallery($args)
	{
		$data = $args['data'];
		$placeholders = $args['placeholders'];
		$formId = $data['formId'];

		$options = $this->get_options($formId);
		if (empty($options) || !isset($options)) {
			return;
		};

		if ($options['modulaIntegration'] !== true) {
			return;
		}

		$fields = get_post_meta($formId, $this->parent_slug . '_field_components', true);
		if ($fields === null || $fields === '' && $fields !== null) {
			return false;
		}
		$uplodFields = [];
		$fields = json_decode($fields);
		foreach ($fields as $field) {
			if ($field->id === 'fileUpload') {
				$uplodFields[] = $field;
			}

			continue;
		}

		if ($options['modulaAction'] === 'new') {
			return $this->create_gallery($options, $data, $placeholders, $uplodFields);
		}

		if ($options['modulaAction'] === 'existing') {
			return $this->update_gallery($options, $data, $uplodFields);
		}

		return false;
	}

	public function create_gallery($options, $data, $placeholders, $uplodFields)
	{
		$postName = isset($options['modulaGalleryName']) && !empty($options['modulaGalleryName'])
			? strtr($options['modulaGalleryName'], $placeholders)
			: __('Form Entry Gallery', 'kaliforms');

		$postData = [
			'post_title'   => $postName,
			'post_type'    => 'modula-gallery',
			'post_status'  => 'draft',
		];

		$newPostId = wp_insert_post($postData);

		if (is_wp_error($newPostId)) {
			throw new \Exception($newPostId->get_error_message());
		}

		if ($options['modulaDefaultsId'] !== 0) {
			$this->add_defaults_to_gallery($newPostId, $options['modulaDefaultsId']);
		}

		$galleryImages = [];
		foreach ($uplodFields as $field) {
			$name = $field->properties->name;
			$image = $data[$name];
			if ($image === null || $image === '') {
				continue;
			}

			$image = explode(',', $image);
			foreach ($image as $id) {
				$galleryImages[] = [
					'id' => absint($id),
				];
			}
		}

		update_post_meta($newPostId, 'modula-images', $galleryImages);
	}

	public function update_gallery($options, $data, $uplodFields)
	{
		$galleryImages = [];
		$meta = get_post_meta($options['modulaGallery'], 'modula-images', true);
		if (is_array($meta) && !empty($meta)) {
			foreach ($meta as $image) {
				$galleryImages[] = $image;
			}
		}

		foreach ($uplodFields as $field) {
			$name = $field->properties->name;
			$image = $data[$name];
			if ($image === null || $image === '') {
				continue;
			}

			$image = explode(',', $image);
			foreach ($image as $id) {
				$galleryImages[] = [
					'id' => absint($id),
				];
			}
		}

		update_post_meta($options['modulaGallery'], 'modula-images', $galleryImages);
	}
}
