<?php

namespace app\components;

use Yii;

use app\components\BaseField;

class SelectField extends BaseField{
    public $form_id;
    public $form_version;
    public $items;
    public $selected;
    public $multiple;
    public $prompt;
    public $document;

    public function __construct($structure, $document, $form_id = null, $form_version = null){
        parent::__construct($structure, $document, $form_id);
        $this->form_id = $form_id;
        $this->form_version = $form_version;
        $this->multiple = $structure['multiple'];
        $this->prompt = $structure['prompt'] ?? '';
        $this->items[] = [
            'value' => '',
            'label' => $this->prompt,
        ];
        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['isReadOnly']) && $this->structure['isReadOnly']){
            self::$model->{$this->name} = $this->selected;
            $this->is_disabled = true;
        }
        if(isset($this->structure['relatedListCheckbox']) && $this->structure['relatedListCheckbox']){
            // The list must be empty because it's related to another list,
            // but if the parent list has selected item, this list must be filled according to parent's selected item
            $parent_list_name = $this->structure['relatedListFieldName'];
            $parent_field = Yii::$app->mongodb->createCommand()->aggregate('formsVersions', [
                [
                    '$match' => [
                        'formId' => Utilities::getIdAsObject($this->form_id),
                        'status' => 'Active'
                    ],
                ],
                [
                    '$project' => [
                        'fields' => 1
                    ],
                ],
                [
                    '$unwind' => '$fields',
                ],
                [
                    '$match' => [
                        'fields.name' => $parent_list_name
                    ]
                ]
            ]);
            if(isset($parent_field[0])){
                $parent_field_items = $parent_field[0]['fields']['values'];
                $parent_field_selected_value = null;
                foreach($parent_field_items as $parent_field_item){
                    if(isset($parent_field_item['selected'])){
                        $parent_field_selected_value = $parent_field_item['value'];
                        
                        break;
                    }
                }
                if($parent_field_selected_value){
                    // Loop through list items and keep only the items which its parent is parent_field_selected_value
                    $_items = [];
                    $_items[] = [
                        'value' => '',
                        'label' => $this->prompt ?? '',
                    ];
                    foreach($this->structure['values'] as $item){
                        if($item['parent'] == $parent_field_selected_value){
                            $_items[] = [
                                'value' => $item['value'],
                                'label' => $item['label'],
                            ];
                        }
                    }
                    $this->items = $_items;
                }
                else{
                    $this->items = [];
                }

                $this->js_script .= "
                    $('[name=\"DynamicModel[" . $parent_list_name . "]\"]').change(function(){
                        var value = $(this).val();
                        $.ajax({
                            url: '" . \yii\helpers\Url::base(true) . "/forms/get-child-data-from-parent-list?form_id=" . $this->form_id . "&version_number=" . $this->form_version . "&name=" . $this->name . "&value=' + value,
                            method: 'GET',
                            success: function(response){
                                var items = JSON.parse(response);
                                $('[name=\"DynamicModel[" . $this->name . "]\"]').empty();
                                $('[name=\"DynamicModel[" . $this->name . "]\"]').append('<option value>" . $this->prompt . "</option>');
                                $.each(items, function(index, value){
                                    $('[name=\"DynamicModel[" . $this->name . "]\"]').append('<option value=' + value.value + '>' + value.label + '</option>');
                                });
                            },
                            error: function(errors){
                                alert(errors);
                            }
                        });
                    });
                ";
            }
        }
    }
}