<?php

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

class PaymentSettings extends \GriffinForms\Admin\Html\FormControls\Field\FieldSettings\Format
{
    protected $layout;
    protected $show_images;
    protected $show_descriptions;
    protected $show_prices;
    protected $allow_quantity_controls;
    protected $min_select;
    protected $max_select;
    protected $tax_mode;
    protected $tax_rate_type;
    protected $tax_rate_value;
    protected $tax_display_label;
    protected $tax_registration_label;
    protected $tax_registration_number;

    protected function setLayout()
    {
        $allowed = array('cards', 'list');
        $value = isset($this->value['layout']) ? sanitize_text_field($this->value['layout']) : 'cards';
        $this->layout = in_array($value, $allowed, true) ? $value : 'cards';
    }

    protected function setShowImages()
    {
        $this->show_images = isset($this->value['show_images']) ? (int) $this->value['show_images'] : 1;
    }

    protected function setShowDescriptions()
    {
        $this->show_descriptions = isset($this->value['show_descriptions']) ? (int) $this->value['show_descriptions'] : 1;
    }

    protected function setShowPrices()
    {
        $this->show_prices = isset($this->value['show_prices']) ? (int) $this->value['show_prices'] : 1;
    }

    protected function setAllowQuantityControls()
    {
        $this->allow_quantity_controls = isset($this->value['allow_quantity_controls'])
            ? (int) $this->value['allow_quantity_controls']
            : 1;
    }

    protected function setMinSelect()
    {
        $this->min_select = isset($this->value['min_select']) ? absint($this->value['min_select']) : 0;
    }

    protected function setMaxSelect()
    {
        $this->max_select = isset($this->value['max_select']) ? absint($this->value['max_select']) : 0;
    }

    protected function setTaxMode()
    {
        $allowed = array('inherit', 'custom');
        $value = isset($this->value['tax_mode']) ? sanitize_text_field($this->value['tax_mode']) : 'inherit';
        $this->tax_mode = in_array($value, $allowed, true) ? $value : 'inherit';
    }

    protected function setTaxRateType()
    {
        $allowed = array('percentage', 'fixed');
        $value = isset($this->value['tax_rate_type']) ? sanitize_text_field($this->value['tax_rate_type']) : 'percentage';
        $this->tax_rate_type = in_array($value, $allowed, true) ? $value : 'percentage';
    }

    protected function setTaxRateValue()
    {
        $raw = isset($this->value['tax_rate_value']) ? $this->value['tax_rate_value'] : '0';
        $this->tax_rate_value = is_numeric($raw) ? (float) $raw : 0;
    }

    protected function setTaxDisplayLabel()
    {
        $default = __('Tax', 'griffinforms-form-builder');
        $this->tax_display_label = isset($this->value['tax_display_label'])
            ? sanitize_text_field($this->value['tax_display_label'])
            : $default;
        if ($this->tax_display_label === '') {
            $this->tax_display_label = $default;
        }
    }

    protected function setTaxRegistrationLabel()
    {
        $this->tax_registration_label = isset($this->value['tax_registration_label'])
            ? sanitize_text_field($this->value['tax_registration_label'])
            : '';
    }

    protected function setTaxRegistrationNumber()
    {
        $this->tax_registration_number = isset($this->value['tax_registration_number'])
            ? sanitize_text_field($this->value['tax_registration_number'])
            : '';
    }

    public function html()
    {
        $this->setLayout();
        $this->setShowImages();
        $this->setShowDescriptions();
        $this->setShowPrices();
        $this->setAllowQuantityControls();
        $this->setMinSelect();
        $this->setMaxSelect();
        $this->setTaxMode();
        $this->setTaxRateType();
        $this->setTaxRateValue();
        $this->setTaxDisplayLabel();
        $this->setTaxRegistrationLabel();
        $this->setTaxRegistrationNumber();

        echo '<div class="griffinforms-payment-settings">';
        echo '<div class="row g-3">';
        echo '<div class="col-md-12">';
        $this->layoutSelect();
        echo '</div>';
        echo '<div class="col-md-12">';
        $this->allowQuantityToggle();
        echo '</div>';
        echo '<div class="col-md-12">';
        $this->showImagesToggle();
        echo '</div>';
        echo '<div class="col-md-12">';
        $this->showDescriptionsToggle();
        echo '</div>';
        echo '<div class="col-md-12">';
        $this->showPricesToggle();
        echo '</div>';
        echo '<div class="col-md-12">';
        $this->minSelectionInput();
        echo '</div>';
        echo '<div class="col-md-12">';
        $this->maxSelectionInput();
        echo '</div>';
        echo '<div class="col-md-12">';
        $this->taxOverridePanel();
        echo '</div>';
        echo '</div>';
        echo '</div>';
    }

    protected function layoutSelect()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\SelectField('layout', $this->layout);
        $field->selectOptions(array(
            'cards'   => __('Card layout', 'griffinforms-form-builder'),
            'list'    => __('Stacked list', 'griffinforms-form-builder'),
        ));
        $field_id = $field->elementId();
        echo '<label for="' . esc_attr($field_id) . '">' . esc_html__('Display style', 'griffinforms-form-builder') . '</label>';
        $field->html();
        echo '<div class="form-text small text-secondary">';
        esc_html_e('Controls the overall layout users will see on the front-end.', 'griffinforms-form-builder');
        echo '</div>';
    }

    protected function showImagesToggle()
    {
        $toggle = new \GriffinForms\Admin\Html\FormControls\ToggleCheckBox(
            'show_images',
            $this->show_images,
            array('label' => __('Show product images', 'griffinforms-form-builder'))
        );
        $toggle->html();
    }

    protected function showDescriptionsToggle()
    {
        $toggle = new \GriffinForms\Admin\Html\FormControls\ToggleCheckBox(
            'show_descriptions',
            $this->show_descriptions,
            array('label' => __('Show descriptions', 'griffinforms-form-builder'))
        );
        $toggle->html();
    }

    protected function showPricesToggle()
    {
        $toggle = new \GriffinForms\Admin\Html\FormControls\ToggleCheckBox(
            'show_prices',
            $this->show_prices,
            array('label' => __('Show price labels', 'griffinforms-form-builder'))
        );
        $toggle->html();
    }

    protected function allowQuantityToggle()
    {
        $toggle = new \GriffinForms\Admin\Html\FormControls\ToggleCheckBox(
            'allow_quantity_controls',
            $this->allow_quantity_controls,
            array('label' => __('Enable quantity controls when supported', 'griffinforms-form-builder'))
        );
        $toggle->html();
        echo '<div class="form-text small text-secondary">';
        esc_html_e('When enabled, products that allow quantity adjustments will display a numeric stepper to buyers.', 'griffinforms-form-builder');
        echo '</div>';
    }

    protected function minSelectionInput()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputNumber('min_select', $this->min_select);
        $field->setAttr('min', 0);
        $field_id = $field->elementId();
        echo '<label for="' . esc_attr($field_id) . '">' . esc_html__('Minimum products required', 'griffinforms-form-builder') . '</label>';
        $field->html();
        echo '<div class="form-text small text-secondary">';
        esc_html_e('Set to 0 to keep the selection optional. Applies across all visible products.', 'griffinforms-form-builder');
        echo '</div>';
    }

    protected function maxSelectionInput()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputNumber('max_select', $this->max_select);
        $field->setAttr('min', 0);
        $field_id = $field->elementId();
        echo '<label for="' . esc_attr($field_id) . '">' . esc_html__('Maximum products selectable', 'griffinforms-form-builder') . '</label>';
        $field->html();
        echo '<div class="form-text small text-secondary">';
        esc_html_e('Leave 0 for no upper limit. Users will not be allowed to select more than this number.', 'griffinforms-form-builder');
        echo '</div>';
    }

    protected function taxOverridePanel()
    {
        echo '<div class="griffinforms-payment-tax border rounded p-3 mt-3">';
        echo '<h4 class="h6 mb-3">' . esc_html__('Tax Options', 'griffinforms-form-builder') . '</h4>';
        $mode_field = new \GriffinForms\Admin\Html\FormControls\SelectField('tax_mode', $this->tax_mode);
        $mode_field->selectOptions(array(
            'inherit' => __('Use global tax settings (Payments → Settings)', 'griffinforms-form-builder'),
            'custom'  => __('Apply custom tax to this payment field only', 'griffinforms-form-builder'),
        ));
        $mode_id = $mode_field->elementId();
        echo '<label for="' . esc_attr($mode_id) . '">' . esc_html__('Tax behavior', 'griffinforms-form-builder') . '</label>';
        $mode_field->html();
        echo '<div class="form-text small text-secondary">';
        esc_html_e('Inherit keeps this payment field in sync with the global tax option. Switch to custom to override the rate, label, and registration details for this form only.', 'griffinforms-form-builder');
        echo '</div>';

        $custom_wrapper_id = 'griffinforms-payment-tax-custom';
        $custom_style = $this->tax_mode === 'custom' ? '' : 'style="display:none;"';
        echo '<div id="' . esc_attr($custom_wrapper_id) . '" class="mt-3" ' . $custom_style . '>';

        $type_field = new \GriffinForms\Admin\Html\FormControls\SelectField('tax_rate_type', $this->tax_rate_type);
        $type_field->selectOptions(array(
            'percentage' => __('Percentage (%)', 'griffinforms-form-builder'),
            'fixed'      => __('Fixed amount', 'griffinforms-form-builder'),
        ));
        $type_id = $type_field->elementId();
        echo '<div class="row g-3">';
        echo '<div class="col-md-12">';
        echo '<label for="' . esc_attr($type_id) . '">' . esc_html__('Rate type', 'griffinforms-form-builder') . '</label>';
        $type_field->html();
        echo '</div>';

        $value_field = new \GriffinForms\Admin\Html\FormControls\InputNumber('tax_rate_value', $this->tax_rate_value);
        $value_field->setAttr('min', 0);
        $value_field->setAttr('step', '0.01');
        $value_id = $value_field->elementId();
        echo '<div class="col-md-12">';
        echo '<label for="' . esc_attr($value_id) . '">' . esc_html__('Rate value', 'griffinforms-form-builder') . '</label>';
        $value_field->html();
        echo '<div class="form-text small text-secondary">';
        esc_html_e('If you select percentage, enter values like 5 or 7.5. Fixed amounts follow your form currency.', 'griffinforms-form-builder');
        echo '</div>';
        echo '</div>';

        $label_field = new \GriffinForms\Admin\Html\FormControls\InputText('tax_display_label', $this->tax_display_label);
        $label_id = $label_field->elementId();
        echo '<div class="col-md-12">';
        echo '<label for="' . esc_attr($label_id) . '">' . esc_html__('Display label', 'griffinforms-form-builder') . '</label>';
        $label_field->html();
        echo '</div>';
        echo '<div class="col-md-12">';
        $reg_label_field = new \GriffinForms\Admin\Html\FormControls\InputText('tax_registration_label', $this->tax_registration_label);
        $reg_label_id = $reg_label_field->elementId();
        echo '<label for="' . esc_attr($reg_label_id) . '">' . esc_html__('Registration label (optional)', 'griffinforms-form-builder') . '</label>';
        $reg_label_field->html();
        echo '<div class="form-text small text-secondary">';
        esc_html_e('Example: VAT Number, GSTIN, Business ID.', 'griffinforms-form-builder');
        echo '</div>';
        echo '</div>';
        echo '<div class="col-md-12">';
        $reg_number_field = new \GriffinForms\Admin\Html\FormControls\InputText('tax_registration_number', $this->tax_registration_number);
        $reg_number_id = $reg_number_field->elementId();
        echo '<label for="' . esc_attr($reg_number_id) . '">' . esc_html__('Registration number (optional)', 'griffinforms-form-builder') . '</label>';
        $reg_number_field->html();
        echo '<div class="form-text small text-secondary">';
        esc_html_e('If provided, it appears near the tax row on the cart summary and review page.', 'griffinforms-form-builder');
        echo '</div>';
        echo '</div>';
        echo '</div>'; // row
        echo '</div>'; // custom wrapper

        echo '</div>'; // panel

        ?>
        <script>
        jQuery(function($){
            const modeSelect = $('#<?php echo esc_js($mode_id); ?>');
            const customWrapper = $('#<?php echo esc_js($custom_wrapper_id); ?>');
            function toggleTaxFields(){
                if (modeSelect.val() === 'custom') {
                    customWrapper.slideDown('fast');
                } else {
                    customWrapper.slideUp('fast');
                }
            }
            modeSelect.on('change', toggleTaxFields);
            toggleTaxFields();
        });
        </script>
        <?php
    }
}
