<?php

namespace GriffinForms\Admin\Html\Pages\Single;

class Field extends \GriffinForms\Admin\Html\Pages\Single\Format
{   
    protected $type = 'field';
    protected $secure;
    protected $field_type;
    protected $field_type_registered = true;
    protected $js_data;
    protected $js_object;

    protected function useSectionNavigation()
    {
        return $this->field_type_registered;
    }

    protected function getMinimumSectionNavCount()
    {
        if ($this->field_type === 'fileupload') {
            return 3;
        }

        return parent::getMinimumSectionNavCount();
    }

    protected function getSections()
    {
        $settings_file = $this->config->getRootPath() . 'admin/html/formcontrols/field/fieldsettings/' . $this->purgeString($this->field_type) . 'settings.php';

        return array(
            array(
                'id' => 'general',
                'label' => $this->lang->getText('general'),
                'callback' => 'renderGeneralSection',
            ),
            array(
                'id' => 'common',
                'label' => $this->lang->getText('common'),
                'callback' => 'renderCommonSection',
            ),
            array(
                'id' => 'field-specific',
                'label' => $this->lang->getText('field_specific'),
                'callback' => 'renderFieldSpecificSection',
                'enabled' => $this->field_type !== 'fileupload',
            ),
            array(
                'id' => 'iterations',
                'label' => $this->lang->getText('iterations'),
                'callback' => 'renderIterationsSection',
                'enabled' => !in_array($this->field_type, array('inputdate', 'inputtime', 'inputpassword', 'fileupload', 'termsconditions', 'payment', 'inputrating', 'signature', 'inputlikert', 'imageselection'), true),
            ),
            array(
                'id' => 'validations',
                'label' => $this->lang->getText('validations'),
                'callback' => 'renderValidationsSection',
                'enabled' => !in_array($this->field_type, array('fileupload', 'termsconditions', 'payment'), true),
            ),
            array(
                'id' => 'other-settings',
                'label' => $this->lang->getText('other_settings'),
                'callback' => 'renderOtherSettingsSection',
                'enabled' => !in_array($this->field_type, array('inputaddress', 'inputtime', 'inputpassword', 'termsconditions', 'inputrating', 'signature', 'inputrichtext', 'inputlikert', 'imageselection'), true) && file_exists($settings_file),
            ),
        );
    }
    
    protected function setFieldType()
    {
        if (isset($_GET['field-type']) and !empty($_GET['field-type'])) {
            $field_type = sanitize_text_field(wp_unslash($_GET['field-type']));

            if ($this->config->isRegisteredFieldType($field_type)) {
                $this->field_type = $field_type;
                $this->field_type_registered = true;
                $this->secure->setData(array('field_type' => $this->field_type));
                return;
            }

            $existing_field_type = '';
            if ($this->item_id > 0 && $this->sql->itemExists('field', $this->item_id)) {
                $existing_field_type = sanitize_key((string) $this->sql->getItemValue($this->item_id, 'field_type', 'field'));
            }

            if ($existing_field_type !== '' && $existing_field_type === sanitize_key($field_type)) {
                $this->field_type = $existing_field_type;
                $this->field_type_registered = false;
                $this->secure->setData(array('field_type' => $this->field_type));
                return;
            }

            $notice = new \GriffinForms\Admin\Html\Elements\AdminNotice;
            $notice->html(__('Invalid field type.', 'griffinforms-form-builder'));
            WP_die();
        } else {
            $notice = new \GriffinForms\Admin\Html\Elements\AdminNotice;
            $notice->html(__('Field type is missing.', 'griffinforms-form-builder'));
            WP_die();
        }
    }
    
    protected function setJsData()
    {
        $this->js_data = array(
            'item_type' => strtolower($this->meta), 
            'item_id' => $this->item_id,
            'form_id' => $this->form_id,
            'referer' => $this->referer,
            'field_type' => $this->field_type,
            'fields' => array()
        );

        $js_class = '\GriffinForms\Admin\Js\Local\\' . $this->meta;
        $this->js_object = new $js_class($this->js_data);
    }
    
    protected function headingSubtext()
    {
        $text = $this->config->getFriendlyName($this->field_type);

        if ($this->item->getProp('is_reusable')) {
            $text .= ' / ' . $this->lang->getText('reusable_field');
        }

        return $text;
    }

    public function itemOptions()
    {
        if (!$this->field_type_registered) {
            $this->renderUnavailableFieldTypeNotice();
            return;
        }

        $field_options = $this->field_type . 'Options';
        $this->commonOptions();
        $this->$field_options();
        $this->fieldIterations();
        $this->fieldValidations();
        $this->otherSettings();
    }   

    protected function renderUnavailableFieldTypeNotice()
    {
        $extension    = $this->config->getFieldExtension($this->field_type);
        $ext_name     = isset($extension['name']) && $extension['name'] !== ''
            ? $extension['name']
            : __('an add-on', 'griffinforms-form-builder');
        $purchase_url = isset($extension['buy_url']) ? esc_url($extension['buy_url']) : '';
        $badge_url    = isset($extension['badge_url']) ? esc_url($extension['badge_url']) : '';
        $badge        = new \GriffinForms\Admin\Html\Elements\ExtensionBadge($ext_name, $badge_url);

        echo '<div class="container border-bottom griffinforms-item-options w-75 mt-3 pt-3">';
        echo '<div class="alert alert-warning">';
        echo '<div class="mb-2">';
        $badge->html();
        echo '</div>';
        echo sprintf(
            /* translators: %s: extension name */
            esc_html__('This field requires %s, which is not currently active. Activate the add-on to edit this field.', 'griffinforms-form-builder'),
            '<strong>' . esc_html($ext_name) . '</strong>'
        );
        if ($purchase_url !== '') {
            echo ' <a href="' . $purchase_url . '" target="_blank" rel="noopener noreferrer">'
                . esc_html__('Learn more', 'griffinforms-form-builder') . '</a>';
        }
        echo '</div>';
        echo '</div>';
    }

    protected function renderGeneralSection()
    {
        $this->getOption('name');
        $this->getOption('heading');
        $this->getOption('description');
    }

    protected function renderCommonSection()
    {
        $this->getOption('is_required');
        $this->getOption('is_readonly');
        $this->getOption('is_disabled');
        $this->getOption('is_hidden');
        $this->getOption('is_reusable');
    }

    protected function renderFieldSpecificSection()
    {
        $field_options = $this->field_type . 'Options';
        if (method_exists($this, $field_options)) {
            $this->$field_options();
        }
    }

    protected function renderIterationsSection()
    {
        if (in_array($this->field_type, array('inputdate', 'inputtime', 'inputpassword', 'fileupload', 'termsconditions', 'payment', 'inputrating', 'signature', 'inputlikert', 'imageselection'), true)) {
            return;
        }
        $this->getOption('iterations');
    }

    protected function renderValidationsSection()
    {
        $this->getOption('validations');
    }

    protected function renderOtherSettingsSection()
    {
        $this->getOption('field_settings');
    }
    
    protected function fieldIterations()
    {
        if (in_array($this->field_type, array('inputdate', 'inputtime', 'inputpassword', 'fileupload', 'termsconditions', 'payment', 'inputrating', 'signature', 'inputlikert', 'imageselection'), true)) {
            return;
        }
        
        echo '<div class="container border-bottom griffinforms-item-options w-75 mt-3 pt-3">';
        $this->optionsHeader('iterations');
        $this->getOption('iterations');
        echo '</div>';
    }    
    
    protected function fieldValidations()
    {
        if (in_array($this->field_type, array('fileupload', 'termsconditions', 'payment'), true)) {
            return;
        }
        $class = 'griffinforms-field-validations-' . $this->field_type;
        echo '<div class="container border-bottom griffinforms-item-options w-75 mt-3 pt-3 ' . esc_attr($class) . '">';
        $this->optionsHeader('validations');
        $this->getOption('validations');
        echo '</div>';
        
    }
    protected function commonOptions()
    {
        echo '<div class="container border-bottom griffinforms-item-options w-75 mt-3 pt-3">';
        $this->optionsHeader('common');
        $this->getOption('is_required');
        $this->getOption('is_readonly');
        $this->getOption('is_disabled');
        $this->getOption('is_hidden');
        $this->getOption('is_reusable');
        echo '</div>';
        
    }
    
    protected function inputTextOptions()
    {
        $this->getOption('default_value');
        $this->getOption('placeholder');
        $this->getOption('autocomplete');
    }    
    
    protected function inputNumberOptions()
    {
        $this->getOption('default_value');
        $this->getOption('placeholder');
        $this->getOption('autocomplete');
    }    
    
    protected function inputEmailOptions()
    {
        $this->getOption('default_value');
        $this->getOption('placeholder');
        $this->getOption('autocomplete');
    }    

    protected function inputPasswordOptions()
    {
        $this->getOption('placeholder');
        $this->getOption('autocomplete');
        $this->getOption('field_settings');
    }    
    
    protected function inputPhoneOptions()
    {
        $this->getOption('default_value');
        $this->getOption('placeholder');
        $this->getOption('autocomplete');
    }    

    protected function inputAddressOptions()
    {
        $this->getOption('field_settings', true);
    }
    
    protected function inputUrlOptions()
    {
        $this->getOption('default_value');
        $this->getOption('placeholder');
        $this->getOption('autocomplete');
    }    
    
    protected function inputDateOptions()
    {
        $this->getOption('default_value');
    }

    protected function inputTimeOptions()
    {
        $this->getOption('default_value');
        $this->getOption('field_settings');
    }

    protected function selectFieldOptions()
    {
        $this->getOption('default_value');
        $this->getOption('field_options');
    }    

    protected function paymentOptions()
    {
        $this->getOption('field_options');
    }

    protected function inputrichtextOptions()
    {
        $this->prop = 'field_settings';
        $this->value = $this->item->getProp('field_settings');
        $this->fields[] = 'field_settings';
        $this->fieldSettings();
    }

    protected function inputlikertOptions()
    {
        $this->prop = 'field_settings';
        $this->value = $this->item->getProp('field_settings');
        $this->fields[] = 'field_settings';
        $this->fieldSettings();
    }

    protected function signatureOptions()
    {
        $this->prop = 'field_settings';
        $this->value = $this->item->getProp('field_settings');
        $this->fields[] = 'field_settings';
        $this->fieldSettings();
    }

    protected function inputratingOptions()
    {
        $this->prop = 'field_settings';
        $this->value = $this->item->getProp('field_settings');
        $this->fields[] = 'field_settings';
        $this->fieldSettings();
    }

    protected function imageselectionOptions()
    {
        $this->prop = 'field_settings';
        $this->value = $this->item->getProp('field_settings');
        $this->fields[] = 'field_settings';
        $this->fieldSettings();
    }
    
    protected function inputRadioOptions()
    {
        $this->getOption('default_value');
        $this->getOption('field_options', true);
    }    
    
    protected function inputCheckboxOptions()
    {
        $this->getOption('default_value');
        $this->getOption('field_options', true);
    }

    protected function termsConditionsOptions()
    {
        $this->getOption('field_settings', true);
    }
    
    protected function textAreaOptions()
    {
        $this->getOption('default_value');
    }
    
    protected function fileUploadOptions()
    {
    }

    protected function formStyle()
    {
        $data = array('item_type' => 'formstyle');
        $field = new \GriffinForms\Admin\Html\FormControls\Form\SelectItem($this->prop, $this->value, $data);
        $field->html();
    }
    
    protected function isRequired()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\ToggleCheckbox($this->prop, $this->value);
        $field->html();
    }    
    
    protected function isReadonly()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\ToggleCheckbox($this->prop, $this->value);
        $field->html();
    }    
    
    protected function isDisabled()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\ToggleCheckbox($this->prop, $this->value);
        $field->html();
    }    
    
    protected function isHidden()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\ToggleCheckbox($this->prop, $this->value);
        $field->html();
    }

    protected function isReusable()
    {
        if ($this->item->getProp('is_reusable')) {
            echo '<input class="me-2" type="checkbox" checked disabled>';
            echo '<span class="text-secondary small">';
            echo '<em>' . esc_html($this->lang->getText('this_is_reusable_field')) . '</em>';
            echo '</span>';
            return;
        }

        $field = new \GriffinForms\Admin\Html\FormControls\ToggleCheckbox($this->prop, $this->value);
        $field->html();
    }    
    
    protected function defaultValue()
    {
        $data = array('field_type' => $this->field_type);
        $field = new \GriffinForms\Admin\Html\FormControls\Field\DefaultValue($this->prop, $this->value, $data);
        $field->html();
    }
    
    protected function placeHolder()
    {
        $field = $this->inputText();
        $field->html();
    }
    
    protected function autoComplete()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\ToggleCheckbox($this->prop, $this->value);
        $field->html();
    }     
    
    protected function iterations()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\Field\Iterations($this->prop, $this->value);
        $field->html();
    }     
    
    protected function validations()
    {
        $data = array('field_type' => $this->field_type);
        $field = new \GriffinForms\Admin\Html\FormControls\Field\Validations($this->prop, $this->value, $data);
        $field->html();
    }
    
    protected function fieldOptions()
    {
        $data = array('field_type' => $this->field_type);
        $field = new \GriffinForms\Admin\Html\FormControls\Field\FieldOptions($this->prop, $this->value, $data);
        $field->html();
    }

    protected function otherSettings()
    {
        if (in_array($this->field_type, array('inputaddress', 'inputtime', 'inputpassword', 'termsconditions', 'inputrating', 'imageselection'), true)) {
            return;
        }

        $settings_file = $this->config->getRootPath() . 'admin/html/formcontrols/field/fieldsettings/' . $this->purgeString($this->field_type) . 'settings.php';

        if (!file_exists($settings_file)) {
            return;
        };

        echo '<div class="container border-bottom griffinforms-item-options w-75 mt-3 pt-3">';
        $this->optionsHeader('other_settings');
        $this->getOption('field_settings');
        echo '</div>';
    }

    protected function fieldSettings()
    {
        $settings_class = '\GriffinForms\Admin\Html\FormControls\Field\FieldSettings\\' . $this->purgeString($this->field_type) . 'Settings';
        $field_settings = new $settings_class($this->prop, $this->value);
        $field_settings->html();
    }

    /**
     * Render the back button for field editor with fallback to list page if no referer is available.
     * Icon changes based on whether the referer is the form layout editor.
     */
    /**
     * Render the back button for field editor with fallback to list page if no referer is available.
     * Icon and label change based on whether the referer is the form layout editor.
     */
    protected function backToListBtn()
    {
        $referer = wp_get_referer();
        $link = $referer ? $referer : admin_url('admin.php?page=griffinforms-fields');

        $from_layout_editor = $referer && strpos($referer, 'page=griffinforms-app') !== false;
        $icon = $from_layout_editor ? 'back' : 'list';
        $label = $from_layout_editor
            ? $this->lang->getText('Back to form builder')
            : $this->lang->getText('Back to fields');

        $this->buttons->bsBtn([
            'class' => 'gf-back-to-fields-btn gf-btn-light me-2',
            'label' => $label,
            'link'  => $link,
            'icon'  => $icon
        ]);
    }
}
