<?php

namespace GriffinForms\Frontend\Html\Forms\Fields;

final class InputRadio extends \GriffinForms\Frontend\Html\Forms\Fields\Format
{   
    protected function formControl($iteration = 0)
    {   
        $disabled = $this->disabledAttr();
        $html = '<div class="griffinforms-optiongroups-container d-flex justify-content-start mt-1 mb-3">';
        $i = 0;

        $readonly = ($this->isReadonly()) ? ' disabled' : '';

        foreach ($this->field_options as $option_group) {
            if (!is_array($option_group)) {return;}
            $html .= '<div class="griffinforms-optiongroup-container d-col me-3">';
            
            foreach ($option_group as $text => $value) {
                
                $id = $this->html_ids['formcontrol'] . '_' . $iteration . '_' . $i++;
                $name = $this->html_ids['formcontrol'] . '_' . $iteration;
                
                $html .= '<div class="form-check mb-1">';
                
                $html .= '<input class="griffinforms-frontend-radio-input ' . esc_attr($this->html_ids['formcontrol']) . '-radio align-middle me-2"';
                $html .= ' type="radio" value="' . esc_attr($value) . '"';
                $html .= ' id="' . esc_attr($id) . '"';
                $html .= ' name="' . esc_attr($name) . '"';
                $html .= $this->checkedAttr($value);
                $html .= $disabled;
                $html .= $readonly;
                $html .= '>';
                
                $html .= '<label class="form-check-label" for="' . esc_attr($id) . '" data-gf-element="checkbox-label">';
                $html .= esc_html($text);
                $html .= '</label>';
                
                $html .= '</div>';
            }
            $html .= '</div>';
        }
        
        $html .= '</div>';
        $html .= '<input class="' . $this->html_ids['formcontrol'] . '" type="hidden"';
        $html .= ' data-gf-formpage="' . absint($this->data['formpage']) . '">';
        return $html;
    }
    
    protected function checkedAttr($value)
    {
        if ($value === $this->value) {
            return ' checked="checked"';
        }
        return '';
    }
    
    protected function disabledAttr()
    {
        if ($this->isDisabled()) {
            return ' disabled';
        }
        return '';
    }
    
    protected function subItemJs()
    {
        echo '
            const cbClass = ".' . esc_attr($this->html_ids['formcontrol']) . '-radio' . '";
            
            $(cbClass).each(inputValues);
            $(document).on("change", cbClass, inputValues);
            
            function inputValues() {
                const container = $(this).closest(".griffinforms-formcontrol-container");
                
                // Check if the container and form control exist before proceeding
                if (container.length === 0) {
                    console.error("Container not found");
                    return;
                }

                const formControlElement = container.children(formControl);
                if (formControlElement.length === 0) {
                    console.error("Form control element not found");
                    return;
                }

                // Debugging: Ensure cbClass is correctly selecting checkboxes
                const checkboxes = container.find(cbClass);
                if (checkboxes.length === 0) {
                    console.error("No checkboxes found with the selector: ", cbClass);
                    return;
                }

                checkboxes.each(function() {
                    const checkbox = $(this); // Cache current checkbox for reuse

                    if (checkbox.is(":checked")) {
                        formControlElement.val(checkbox.val());
                        if (typeof triggerFieldChanged === "function") {
                            triggerFieldChanged({ element: this, reason: "option_changed" });
                        }
                        return false; // Exit the loop after the first checked item is found
                    }
                });
            }
        ';
    }
    
    protected function setErrors()
    {
        $this->errors = array(
            'required',
            'unique'
        );
    }
    
    protected function requiredJs($error)
    {
        echo '
            $(actionBtn).hover(function(){
                $(formControl).each(checkRequired);
            });
            
            $(cbClass).click(function(){
                $(formControl).each(checkRequired);
            });
            
            function checkRequired() {
                let val = $(this).val();
                if(val === "") {
                    addAlert($(this), "' . esc_js($error) . '");
                } else {
                    removeAlert($(this), "' . esc_js($error) . '");
                }
            }
        ';
    }
}
