<?php

namespace app\components;

use Yii;

use app\components\BaseField;

class CheckboxGroupField extends BaseField{
    public $form_id;
    public $form_version;
    public $items;
    public $selected;
    public $separator;
    public $document;

    public function __construct($structure, $document, $form_id = null){
        parent::__construct($structure, $document, $form_id);
        $this->separator = isset($structure['inline']) && $structure['inline'] ? ' ' : '<br>';
        foreach($this->structure['values'] as $item){
            if($item['status'] == 'Active'){
                $this->items[] = [
                    'value' => $item['value'],
                    'label' => $item['label'],
                ];
                if(isset($item['selected'])){
                    $this->selected = $item['value'];
                }
            }
        }
        $this->handleRules();
        if($this->js_script){
            Yii::$app->controller->getView()->registerJs($this->js_script);
        }
    }

    public function handleRules(){
        if(isset($this->structure['checkboxMinValue'])){
            $min_count = $this->structure['checkboxMinValue'];
            $max_count = $this->structure['checkboxMaxValue'];
            $message = 'You have to selecte at least ' . $min_count . ' option' . ($min_count == 1 ? '' : '(s)') . ' and at most ' . $max_count . ' options.';
            $this->field->template = "{label}\n<p>" . (isset($this->structure['description']) ? $this->structure['description'] : '') .'<p><b>Attention: </b>' . $message . '</p>' . "</p>\n{input}\n{hint}\n{error}";
            $this->js_script .= "
                $('input[name=\"DynamicModel[" . $this->name . "][]\"]').change(function(){
                    var selectedValue = $(this).val();
                    var checkedOptions = $('input[name=\"DynamicModel[" . $this->name . "][]\"]:checked').length;
                    if(checkedOptions < " . json_encode($min_count) . "){
                        alert('" . $message . "');
                    }
                    if(checkedOptions > " . json_encode($max_count) . "){
                        $('input[name=\"DynamicModel[" . $this->name . "][]\"][value=\"' + selectedValue + '\"]').prop('checked', false);
                        $('input[name=\"DynamicModel[" . $this->name . "][]\"]').trigger('change');     // Trigger change event in order to hide/show other fields if there is show-if rule related to checked option
                        alert('" . $message . "');
                    }
                });
            ";
        }
        if(isset($this->structure['isReadOnly']) && $this->structure['isReadOnly']){
            self::$model->{$this->name} = $this->selected;
            $this->is_disabled = true;
        }
    }
}