<?php
namespace modules\custom\widgets;

use yii;
use yii\helpers\{ArrayHelper, Html,Json};
use yii\widgets\InputWidget;
use backend\models\Productsbe;

/**
 * TinyMCE renders a tinyMCE js plugin for WYSIWYG editing.
 */
class ServiceInput extends InputWidget
{
    //Callback function
    public $productid;
    public $assetid;
    public $name = 'ServiceInput';
    public $model;
    public $form;

    public function run()
    {
        $form = $this->form;
        $model = $this->model;
        $output = '';
        if(!empty($this->productid)){
            $assetS = $this->services;
            $assetDS = $this->deliveryServices;
            if(count($assetDS) > 0){
                $output .= $form->field($model, "[$model->id]servicetype")->radioList(ArrayHelper::map($assetDS, 'id', 'product_name'),[
                    'item' => function ($index, $label, $name, $checked, $value) use ($model){
                        return Html::radio($name, is_array($model->servicetype) ? in_array($value, $model->servicetype) : ($value == $model->servicetype ? true : false), ['value' => $value, 'label' => '<rad></rad> '.$label, 'unselect' => null]).'<br/>';
                    },
                    'unselect' => 0,
                ])->label(count($assetS) > 0 ? 'Services' : false);
            }
            if(count($assetS) > 0){
                $output .= $form->field($model, "[$model->id]addons")->checkboxList(ArrayHelper::map($assetS, 'id', 'product_name'), [ 
                    'item' => function ($index, $label, $name, $checked, $value) use ($model){
                        return Html::checkbox($name, is_array($model->addons) ? in_array($value, $model->addons) : ($value == $model->addons ? true : false), ['value' => $value, 'label' => '<chk></chk> '.$label, 'unselect' => null]).'<br/>';
                    },
                    'unselect' => 0,
                ])->label(count($assetDS) > 0 ? 'Addons' : false);
            }
        } else {
            $output = 'No Asset Defined';
        }
        return $output;
    }

    /**
     * Registers Twitter TypeAhead Bootstrap plugin and the related events
     */
    protected function registerClientScript()
    {


    }

    public function getServices() {
		return Productsbe::find()->where(['id' => 'sourceid'])
			->select(['products.id', 'products.product_name'])	
			->where(['product_type' => 'Service', 'products.status' => 'Active'])	
			->andwhere(['lookuptable.relatedid' => $this->productid])
			->andwhere(['not', ['stock_group' => 'Delivery']])
			->joinWith(['lookup'])
			->all();
	}
	public function getDeliveryServices() {
		return Productsbe::find()->where(['id' => 'sourceid'])
		->select(['products.id', 'products.product_name'])	
			->where(['product_type' => 'Service', 'products.status' => 'Active', 'stock_group' => 'Delivery'])	
			->andwhere(['lookuptable.relatedid' => $this->productid])
			->joinWith(['lookup'])
			->all();
	}
}
