<?php
namespace KaliForms\Inc\Frontend\FormFields;

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

/**
 * Class Date_Time_Picker
 *
 * @package Inc\Frontend\FormFields;
 */
class Date_Time_Picker extends Form_Field
{
    protected $parent_slug = 'kaliforms';
    /**
     * Class constructor
     */
    public function __construct()
    {
        $this->id = 'dateTimePicker';
    }
    /**
     * Localization for the calendar
     *
     * @return void
     */
    public function locale_load()
    {
        $language = get_locale();
        $language = explode('_', $language);
        if ($language[0] === 'en') {
            return;
        }
        wp_enqueue_script(
            'kaliforms-pro-datepicker-locale',
            KALIFORMS_PRO_URL . 'assets/datepicker-locale/index.min.js',
            [],
            KALIFORMS_PRO_VERSION
        );

        wp_localize_script('kaliforms-pro-datepicker-locale', 'FlatPickrSelectedLanguage', ['lang' => $language[0]]);
    }
    /**
     * Render function
     *
     * @return void
     */
    public function render($item, $form_info)
    {
        $this->locale_load();

        $item['kali-form-type'] = $item['type'];
        $item['type']           = 'date';

        if (isset($item['inlineCalendar']) && $item['inlineCalendar']) {
            $item['inline'] = true;
        }
        if (!isset($item['minDateDependencyOffset'])) {
            $item['minDateDependencyOffset'] = 0;
        }
        if (isset($item['disabledDates'])) {
            $item['disabledDates'] = explode(',', $item['disabledDates']);
            wp_localize_script(
                'kaliforms-pro',
                'KaliFormsDisabledDates' . $item['grid_id'],
                ['global' => $item['disabledDates']]
            );
        }

        if (isset($item['disabledPreviousSavedDates']) && $item['disabledPreviousSavedDates']) {
            $item['disabledDates'] = isset($item['coDependancyField'])
            && $item['coDependancyField'] !== ''
            && $item['coDependancyField'] !== 'kf-select-field'
            ? $this->_get_codependent_saved_dates($item, $form_info)
            : array_filter(['global' => array_merge($item['disabledDates'], $this->_get_previous_saved_dates($item, $form_info))]);
            wp_localize_script(
                'kaliforms-pro',
                'KaliFormsDisabledDates' . $item['grid_id'],
                $item['disabledDates']
            );
        }

        $attributes = $this->generate_attribute_string($item);

        $offset = isset($item['offset']) && $item['offset'] > 0 ? 'offset-md-' . absint($item['offset']) : '';
        $div    = '<div class="col-12 col-md-' . absint($item['col']) . ' ' . $offset . '">';
        $div .= $this->generate_label($item, $form_info);
        $div .= '<div class="kaliforms-date-time-picker-container">';
        if (!isset($item['inline'])) {
            $div .= '<div class="flatpickr">';
        }
        $div .= '<input' . $attributes . ' class="kaliforms-date-time-picker" data-input/>';
        if (!isset($item['inline'])) {
            $div .= '<a class="input-button" title="toggle" data-toggle><span class="kaliforms-date-picker-icon" data="' . KALIFORMS_PRO_URL . '/assets/img/date_range-24px.svg"></span></a>';
            $div .= '<a class="input-button" title="clear" data-clear><span class="kaliforms-date-picker-delete-icon" data="' . KALIFORMS_PRO_URL . '/assets/img/delete.svg"></span></a>';
            $div .= '</div>';
        }
        $div .= !empty($item['description']) ? '<small>' . esc_html($item['description']) . '</small>' : '';
        $div .= '</div>';
        $div .= '</div>';

        return $div;
    }

    /**
     * Returns the previous saved dates (for this form id and this specific field id)
     *
     * @return void
     */
    public function _get_previous_saved_dates($item, $form_info)
    {
        $args = [
            'post_type'      => 'kaliforms_submitted',
            'posts_per_page' => -1,
            'meta_key'       => 'formId',
            'meta_query'     => [
                [
                    'key'     => 'formId',
                    'value'   => $form_info['form_id'],
                    'compare' => '=',
                ],
            ],
        ];

        $query = new \WP_Query($args);
        wp_reset_postdata();

        $dates = [];
        foreach ($query->posts as $post) {
            $dates[] = get_post_meta($post->ID, $item['name'], true);
        }

        return $dates;
    }

    /**
     * Get codependet saved fields
     *
     * @param [type] $item
     * @param [type] $form_info
     * @return void
     */
    public function _get_codependent_saved_dates($item, $form_info)
    {
        $available_choices = [];
        $disabled_dates    = [];
        $fields            = json_decode(get_post_meta($form_info['form_id'], $this->parent_slug . '_field_components', true), false, 512, JSON_HEX_QUOT);
        $codependancy_name = '';
        foreach ($fields as $field) {
            if ($field->internalId === $item['coDependancyField']) {
                $codependancy_name = $field->properties->name;
                $available_choices = $field->properties->choices;
                break;
            }
        }

        foreach ($available_choices as $choice) {
            $args = [
                'post_type'      => 'kaliforms_submitted',
                'posts_per_page' => -1,
                'meta_key'       => 'formId',
                'meta_query'     => [
                    'relation' => 'AND',
                    [
                        'key'   => 'formId',
                        'value' => $form_info['form_id'],
                    ],
                    [
                        'key'   => $codependancy_name,
                        'value' => $choice->value,
                    ],
                ],
            ];

            $query = new \WP_Query($args);
            wp_reset_postdata();

            $dates = [];
            foreach ($query->posts as $post) {
                $dates[] = get_post_meta($post->ID, $item['name'], true);
            };

            $disabled_dates[$choice->value] = $dates;
        }

        $disabled_dates['global'] = array_filter($item['disabledDates']);
        return $disabled_dates;
    }
}
