<?php

namespace app\components;

use Yii;

use app\components\BaseField;

class LookupField extends BaseField{
    public $plugin_options;
    public $document;

    public function __construct($structure, $document, $form_id = null){
        parent::__construct($structure, $document, $form_id);
        $this->plugin_options = [
            'minimumInputLength' => 3,
            'ajax' => [
                'url' => \yii\helpers\Url::to(['/forms/get-lookup-records', 'lookup_form_id' => $this->structure['form'], 'lookup_id_field' => $this->structure['referrence'], 'helper_field' => $this->structure['helper'] ?? '']),
                'dataType' => 'json',
                'data' => new \yii\web\JsExpression('function (params){ return {q:params.term}; }'),
            ],
            'escapeMarkup' => new \yii\web\JsExpression('function (markup) { return markup; }'),
            'templateResult' => new \yii\web\JsExpression('function (value) { return value.text; }'),
            'templateSelection' => new \yii\web\JsExpression('function (value) { return value.text; }'),
        ];
        $this->handleRules();
        if($this->js_script){
            Yii::$app->controller->getView()->registerJs($this->js_script);
        }

        // In case of adding child record, lookup namd & value will be passed to render function as parameters in URL
        if(isset($_GET['lookup_name']) && $_GET['lookup_name'] == $this->name && isset($_GET['lookup_value'])){
            $this->value = $_GET['lookup_value'];
            $this->is_disabled = true;
        }
    }

    public function handleRules(){
        
    }
}