<?php

namespace GriffinForms\Admin\Html\FormControls\Field\FieldSettings;

class TermsConditionsSettings extends \GriffinForms\Admin\Html\FormControls\Field\FieldSettings\Format
{
    protected $checkbox_label = '';
    protected $anchor_text = '';
    protected $subtext = '';
    protected $link_type = 'page';
    protected $page_id = 0;
    protected $post_id = 0;
    protected $open_in_modal = 0;
    protected $accept_label = '';
    protected $decline_label = '';

    public function html()
    {
        $this->setCheckboxLabel();
        $this->setAnchorText();
        $this->setSubtext();
        $this->setLinkType();
        $this->setPageId();
        $this->setPostId();
        $this->setOpenInModal();
        $this->setAcceptLabel();
        $this->setDeclineLabel();

        echo '<div class="gf-terms-settings border rounded-3 bg-white shadow-sm p-4 my-3">';
        echo '<div class="d-flex flex-column gap-5">';
        $this->renderGeneralSection();
        $this->renderLinkSection();
        $this->renderModalSection();
        echo '</div>';
        echo '</div>';
    }

    private function renderGeneralSection()
    {
        echo '<section class="griffinforms-terms-section">';
        $this->renderSectionHeading(
            __('General content', 'griffinforms-form-builder'),
            __('Control the copy that appears alongside your consent checkbox.', 'griffinforms-form-builder')
        );
        echo '<div class="row g-4">';
        $this->checkboxLabelField();
        $this->anchorTextField();
        $this->subtextField();
        echo '</div>';
        echo '</section>';
    }

    private function renderLinkSection()
    {
        echo '<section class="griffinforms-terms-section">';
        $this->renderSectionHeading(
            __('Link source', 'griffinforms-form-builder'),
            __('Choose where the Terms and Conditions content should be loaded from.', 'griffinforms-form-builder')
        );
        echo '<div class="row g-4">';
        $this->linkTypeField();
        $this->pageSelectField();
        $this->postSelectField();
        echo '</div>';
        echo '</section>';
    }

    private function renderModalSection()
    {
        echo '<section class="griffinforms-terms-section">';
        $this->renderSectionHeading(
            __('Modal experience', 'griffinforms-form-builder'),
            __('Toggle the modal layout and fine-tune its button labels.', 'griffinforms-form-builder')
        );
        echo '<div class="row g-4">';
        $this->modalToggleField();
        echo '</div>';
        echo '<div class="row g-4 griffinforms-terms-button-row">';
        $this->acceptButtonField();
        $this->declineButtonField();
        echo '</div>';
        echo '</section>';
    }

    private function renderSectionHeading($title, $summary = '')
    {
        echo '<div class="d-flex flex-column gap-1 mb-3">';
        echo '<h3 class="h6 fw-semibold mb-0">' . esc_html($title) . '</h3>';
        if ($summary !== '') {
            echo '<p class="text-muted small mb-0">' . esc_html($summary) . '</p>';
        }
        echo '</div>';
    }

    protected function setCheckboxLabel()
    {
        if (is_array($this->value) && !empty($this->value['checkbox_label'])) {
            $this->checkbox_label = sanitize_text_field((string) $this->value['checkbox_label']);
        } else {
            $this->checkbox_label = $this->lang->getText('terms_checkbox_label', 'default');
        }
    }

    protected function setAnchorText()
    {
        if (is_array($this->value) && !empty($this->value['anchor_text'])) {
            $this->anchor_text = sanitize_text_field((string) $this->value['anchor_text']);
        } else {
            $this->anchor_text = $this->lang->getText('terms_anchor_text', 'default');
        }
    }

    protected function setSubtext()
    {
        if (is_array($this->value) && array_key_exists('subtext', $this->value)) {
            $this->subtext = sanitize_textarea_field((string) $this->value['subtext']);
            return;
        }

        $this->subtext = $this->lang->getText('terms_subtext', 'default');
    }

    protected function setLinkType()
    {
        $stored = '';
        if (is_array($this->value) && isset($this->value['link_type'])) {
            $stored = sanitize_key((string) $this->value['link_type']);
        }

        $this->link_type = in_array($stored, array('page', 'post'), true) ? $stored : 'page';
    }

    protected function setPageId()
    {
        if (is_array($this->value) && isset($this->value['page_id'])) {
            $this->page_id = absint($this->value['page_id']);
        }
    }

    protected function setPostId()
    {
        if (is_array($this->value) && isset($this->value['post_id'])) {
            $this->post_id = absint($this->value['post_id']);
        }
    }

    protected function setOpenInModal()
    {
        if (is_array($this->value) && isset($this->value['open_in_modal'])) {
            $this->open_in_modal = (int) $this->value['open_in_modal'] === 1 ? 1 : 0;
        }
    }

    protected function setAcceptLabel()
    {
        if (is_array($this->value) && isset($this->value['accept_label']) && $this->value['accept_label'] !== '') {
            $this->accept_label = sanitize_text_field((string) $this->value['accept_label']);
        } else {
            $this->accept_label = $this->lang->getText('terms_accept_label', 'default');
        }
    }

    protected function setDeclineLabel()
    {
        if (is_array($this->value) && isset($this->value['decline_label']) && $this->value['decline_label'] !== '') {
            $this->decline_label = sanitize_text_field((string) $this->value['decline_label']);
        } else {
            $this->decline_label = $this->lang->getText('terms_decline_label', 'default');
        }
    }

    protected function checkboxLabelField()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputText('terms_checkbox_label', $this->checkbox_label);
        $label = $this->lang->getText('terms_checkbox_label', 'label');
        $description = $this->lang->getText('terms_checkbox_label', 'description');

        echo '<div class="griffinforms-terms-field col-12 col-lg-6">';
        echo '<div class="griffinforms-terms-field-card h-100 p-3 d-flex flex-column gap-2">';
        echo '<label class="form-label fw-semibold mb-0" for="' . esc_attr($field->elementId()) . '">' . esc_html($label) . '</label>';
        $field->html();
        echo '<div class="form-text">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function anchorTextField()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputText('terms_anchor_text', $this->anchor_text);
        $label = $this->lang->getText('terms_anchor_text', 'label');
        $description = $this->lang->getText('terms_anchor_text', 'description');

        echo '<div class="griffinforms-terms-field col-12 col-lg-6">';
        echo '<div class="griffinforms-terms-field-card h-100 p-3 d-flex flex-column gap-2">';
        echo '<label class="form-label fw-semibold mb-0" for="' . esc_attr($field->elementId()) . '">' . esc_html($label) . '</label>';
        $field->html();
        echo '<div class="form-text">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function subtextField()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\TextArea('terms_subtext', $this->subtext);
        $label = $this->lang->getText('terms_subtext', 'label');
        $description = $this->lang->getText('terms_subtext', 'description');

        echo '<div class="griffinforms-terms-field col-12">';
        echo '<div class="griffinforms-terms-field-card p-3 d-flex flex-column gap-2">';
        echo '<label class="form-label fw-semibold mb-0" for="' . esc_attr($field->elementId()) . '">' . esc_html($label) . '</label>';
        $field->html();
        echo '<div class="form-text">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function linkTypeField()
    {
        $label = $this->lang->getText('terms_link_type', 'label');
        $description = $this->lang->getText('terms_link_type', 'description');
        $options = array(
            'page' => __('WordPress Page', 'griffinforms-form-builder'),
            'post' => __('Blog Post', 'griffinforms-form-builder')
        );

        $field = new \GriffinForms\Admin\Html\FormControls\SelectField('terms_link_type', $this->link_type);
        $field->selectOptions($options);

        echo '<div class="griffinforms-terms-field col-12 col-lg-6">';
        echo '<div class="griffinforms-terms-field-card h-100 p-3 d-flex flex-column gap-2">';
        echo '<label class="form-label fw-semibold mb-0" for="' . esc_attr($field->elementId()) . '">' . esc_html($label) . '</label>';
        $field->html();
        echo '<div class="form-text">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function pageSelectField()
    {
        $options = $this->getPageOptions();
        $label = $this->lang->getText('terms_page_select', 'label');
        $description = $this->lang->getText('terms_page_select', 'description');

        $field = new \GriffinForms\Admin\Html\FormControls\SelectField('terms_page_id', $this->page_id);
        $field->selectOptions($options);

        echo '<div class="griffinforms-terms-field griffinforms-terms-page-select col-12 col-lg-6">';
        echo '<div class="griffinforms-terms-field-card h-100 p-3 d-flex flex-column gap-2">';
        echo '<label class="form-label fw-semibold mb-0" for="' . esc_attr($field->elementId()) . '">' . esc_html($label) . '</label>';
        $field->html();
        echo '<div class="form-text">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function postSelectField()
    {
        $options = $this->getPostOptions();
        $label = $this->lang->getText('terms_post_select', 'label');
        $description = $this->lang->getText('terms_post_select', 'description');

        $field = new \GriffinForms\Admin\Html\FormControls\SelectField('terms_post_id', $this->post_id);
        $field->selectOptions($options);

        echo '<div class="griffinforms-terms-field griffinforms-terms-post-select col-12 col-lg-6">';
        echo '<div class="griffinforms-terms-field-card h-100 p-3 d-flex flex-column gap-2">';
        echo '<label class="form-label fw-semibold mb-0" for="' . esc_attr($field->elementId()) . '">' . esc_html($label) . '</label>';
        $field->html();
        echo '<div class="form-text">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function modalToggleField()
    {
        $label = $this->lang->getText('terms_open_modal', 'label');
        $description = $this->lang->getText('terms_open_modal', 'description');
        $field = new \GriffinForms\Admin\Html\FormControls\ToggleCheckbox('terms_open_in_modal', $this->open_in_modal);

        echo '<div class="griffinforms-terms-field col-12 mb-3">';
        echo '<div class="griffinforms-terms-field-card h-100 p-3 d-flex flex-column gap-2">';
        echo '<div class="d-flex align-items-center gap-2">';
        $field->html();
        echo '<label class="align-middle mb-0" for="' . esc_attr($field->elementId()) . '">' . esc_html($label) . '</label>';
        echo '</div>';
        echo '<div class="form-text">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function acceptButtonField()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputText('terms_accept_label', $this->accept_label);
        $label = $this->lang->getText('terms_accept_label', 'label');
        $description = $this->lang->getText('terms_accept_label', 'description');

        echo '<div class="griffinforms-terms-field griffinforms-terms-button-labels col-12 col-lg-6">';
        echo '<div class="griffinforms-terms-field-card h-100 p-3 d-flex flex-column gap-2">';
        echo '<label class="form-label fw-semibold mb-0" for="' . esc_attr($field->elementId()) . '">' . esc_html($label) . '</label>';
        $field->html();
        echo '<div class="form-text">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function declineButtonField()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputText('terms_decline_label', $this->decline_label);
        $label = $this->lang->getText('terms_decline_label', 'label');
        $description = $this->lang->getText('terms_decline_label', 'description');

        echo '<div class="griffinforms-terms-field griffinforms-terms-button-labels col-12 col-lg-6">';
        echo '<div class="griffinforms-terms-field-card h-100 p-3 d-flex flex-column gap-2">';
        echo '<label class="form-label fw-semibold mb-0" for="' . esc_attr($field->elementId()) . '">' . esc_html($label) . '</label>';
        $field->html();
        echo '<div class="form-text">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function fieldJs()
    {
        ob_start();
        ?>
        jQuery(function($) {
            const linkTypeField = $('#griffinforms-termslinktype-selectfield');
            const pageSelectWrap = $('.griffinforms-terms-page-select');
            const postSelectWrap = $('.griffinforms-terms-post-select');
            const modalToggle = $('#griffinforms-termsopeninmodal-togglecheckbox');
            const buttonLabelsWrap = $('.griffinforms-terms-button-labels');

            function toggleSourceFields() {
                const current = linkTypeField.val();
                if (current === 'post') {
                    pageSelectWrap.hide();
                    postSelectWrap.show();
                } else {
                    pageSelectWrap.show();
                    postSelectWrap.hide();
                }
            }

            function toggleModalFields() {
                if (modalToggle.is(':checked')) {
                    buttonLabelsWrap.show();
                } else {
                    buttonLabelsWrap.hide();
                }
            }

            linkTypeField.on('change', toggleSourceFields);
            modalToggle.on('change', toggleModalFields);

            toggleSourceFields();
            toggleModalFields();
        });
        <?php
        $js = ob_get_clean();
        wp_add_inline_script('griffinforms-global-js', $js);
    }

    private function getPageOptions()
    {
        $options = array(
            0 => __('Select a page', 'griffinforms-form-builder')
        );

        $pages = get_pages(array(
            'sort_column' => 'post_title',
            'sort_order'  => 'ASC',
        ));

        if (is_array($pages)) {
            foreach ($pages as $page) {
                $options[$page->ID] = $page->post_title;
            }
        }

        return $options;
    }

    private function getPostOptions()
    {
        $options = array(
            0 => __('Select a post', 'griffinforms-form-builder')
        );

        $posts = get_posts(array(
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'orderby'        => 'title',
            'order'          => 'ASC',
            'posts_per_page' => 100,
        ));

        if (is_array($posts)) {
            foreach ($posts as $post) {
                $options[$post->ID] = $post->post_title;
            }
        }

        return $options;
    }
}
