<?php

namespace GriffinForms\Admin\Html\Elements\Submission;

class InputCheckBox extends \GriffinForms\Admin\Html\Elements\Submission\Format
{
    protected $field_options;

    protected function setFieldOptions()
    {
        $this->field_options = $this->field->getProp('field_options');
    }

    protected function setFieldValue()
    {
        if (is_string($this->field_value)) {
            $decoded = json_decode($this->field_value, true);
            $this->field_value = is_array($decoded) ? $decoded : [];
        }

        if (!is_array($this->field_value)) {
            $this->field_value = [];
        }

        // Flatten the value in case it's a nested array
        $flat_values = [];
        array_walk_recursive($this->field_value, function ($v) use (&$flat_values) {
            $flat_values[] = $v;
        });

        $this->field_value = $flat_values;
    }

    public function getHtml()
    {
        if (!is_array($this->field_options)) {
            return;
        }

        echo '<div class="d-flex my-2">';
        foreach ($this->field_options as $option_group) {
            $this->getOptionGroupHtml($option_group);
        }

        echo '</div>';
    }

    protected function getOptionGroupHtml($option_group)
    {
        echo '<div class="flex-column me-3">';
        
        foreach ($option_group as $option => $value) {
            echo '<div class="d-flex mb-1">';
            $this->cbIcon($value);
            $this->cbLabel($option);
            echo '</div>';
        }

        echo '</div>';
    }

    protected function cbIcon($value)
    {
        if (in_array($value, $this->field_value)) {
            echo '<span class="me-1 text-primary">';
            $this->mIcon('check_box');
        } else {
            echo '<span class="me-1">';
            $this->mIcon('check_box_outline_blank');
        }
        
        echo '</span>';
    }

    protected function cbLabel($option) 
    {
        echo '<span class="">';
        echo esc_html($option);
        echo '</span>';
    }
}