<?php

namespace modules\forms\models;

use Yii;
use yii\helpers\Json;
use console\jobs\Sync;
use modules\activities\models\Activities;
/**
 * This is the model class for table "dt_forms".
 *
 * @property string $id id
 * @property string $language language
 * @property string|null $created_by Created By
 * @property string|null $updated_by Updated By
 * @property string|null $deleted_by Deleted By
 * @property string|null $relatedid Related ID
 * @property string|null $centerid Center ID
 * @property int|null $created_at Created At
 * @property int|null $updated_at Updated At
 * @property int|null $deleted_at Deleted At
 * @property string|null $status Status
 * @property string|null $data formdata
 * @property string|null $for Form Name
 */
class Forms extends \common\models\Base
{
    public $dates = ['created_at', 'updated_at', 'deleted_at'];
	public $securefields = [];
    public $uniqueidentifiers = [];
    
    private $formns = '\\modules\\forms\\models\\';
    public $formclass = null;
    public $formname = null;
    public $subdata = [];
    public $title = null;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'forms';
    }

    /**
     * {@inheritdoc}
     */
    public function rules(): array
    {
        return [
            [['formclass'], 'string'],
            [['id', 'language'], 'required'],
            [['created_at', 'updated_at', 'deleted_at'], 'safe'],
            [['data'], 'safe'],
            [['id', 'created_by', 'updated_by', 'deleted_by', 'relatedid', 'centerid'], 'string', 'max' => 36],
            [['language'], 'string', 'max' => 10],
            [['status'], 'string', 'max' => 255],
            [['form', 'subclass'], 'string', 'max' => 15],
            ['language', 'default', 'value' => 'en'],
            ['id', 'default', 'value' => function($model){
                return Self::Tempid();
            }],
            [['id', 'language'], 'unique', 'targetAttribute' => ['id', 'language']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels(): array
    {
        $localAttributes = [
            'data' => 'Data',
            'form' => 'Form',
        ];
        return array_merge($localAttributes, parent::attributeLabels());
    }

    public function getWelder(){
        $data = $this->data;
        if( $this->form == 'dt130' || $this->form == 'dt142'){
            return is_object($data) ? $data->welders_name : null;	
        }elseif($this->form == 'dt213' || $this->form == 'wel233' || $this->form == 'dt192' || $this->form == 'dt129' || $this->form == 'dt128' || $this->form == 'dt123' || $this->form == 'dt125' || $this->form == 'dt126' ){
            $out = '';
            if(is_array($data->weldersname) == true) {
                $out = implode(',', $data->weldersname);
            }
            return is_object($data) && is_array($data->weldersname) == true ? $out : $data->weldersname;	
        }elseif($this->form == 'dt022' ){
            return is_object($data) ? $data->welder : null;	
        }elseif($this->form == 'dt035' ){
            return is_object($data) ? $data->employee : null;	
        }elseif($this->form == 'dt058' ){
            return is_object($data) ? ($data->emp1 ? $data->emp1->fullname : null) : null;	
        }elseif($this->form == 'dt122' ){
            return is_object($data) ? $data->insepectorid : null;	
        }elseif($this->form == 'dt135' ){
            return is_object($data) ? $data->operatorname : null;	
        }elseif($this->form == 'dt195' || $this->form == 'dt131' || $this->form == 'dt188' ){
            return is_object($data) ? $data->name : null;	
        }elseif($this->form == 'dt132' ){
            return is_object($data) ? $data->witnessname : null;	
        }elseif($this->form == 'dt194' ){
            return is_object($data) ? $data->assessorname1 : null;	
        }elseif($this->form == 'dt197' ){
            return is_object($data) ? $data->signprint : null;	
        }elseif($this->form == 'dt198' ){
            return is_object($data) ? $data->seniorwelder : null;	
        }elseif($this->form == 'dt203' ){
            return is_object($data) ? $data->inspectedbyname : null;	
        }elseif($this->form == 'dt204' ){
            return is_object($data) ? $data->icinspectorname : null;	
        }elseif($this->form == 'dt205' ){
            return is_object($data) ? $data->grindingsupervisorname : null;	
        }elseif($this->form == 'dt134' ){
            return is_object($data) ? ($data->driverl ? $data->driverl->fullname : null) : null;	
        }elseif($this->form == 'dt133' ){
            $out = '';
            if(is_array($data->detailsname) == true) {
                $out = implode(',', $data->detailsname);
            }
            return is_object($data) ? (is_array($data->detailsname) == true ? $out : $data->detailsname) : null;	
        }elseif($this->form == 'dt179' ){
            $out = '';
            if(is_array($data->rowname) == true) {
                foreach($data->rowname as $name){
                    empty($name) == false ? $out .= $name.'<br />' : false;
                }
            }
            return is_object($data) ? (is_array($data->rowname) == true ? $out : $data->rowname) : null;	
        
        }elseif($this->form == 'dt005' ){
            return is_object($data) ? ($data->driverl ? $data->driverl->fullname : null) : null;	
        } 
    
    }

    public function afterFind(){
        $form = $this->form;
        $data = $this->data;
        if(file_exists(Yii::getAlias('@modules/forms/models/'. ucwords($form) . '.php'))){
            $formClass = '\\modules\\forms\\models\\'. ucwords($form);
        } elseif(file_exists(Yii::getAlias('@frontend/models/forms/'. ucwords($form) . '.php'))){
            $formClass = '\\frontend\\models\\forms\\'. ucwords($form);
        }
        $class = !str_contains($formClass, '\\') ? $this->formns.$formClass : $formClass;
        if($class !== null && $data !== null){
            $formdata = new $class();
            $formdata->attributes = Json::decode(mb_convert_encoding($data, 'UTF-8', 'UTF-8'));
            $formdata->id = $this->id;
            $this->data = $formdata;
        }
        return parent::afterFind();
    }

    
    public function beforeSave($insert){
        $data = $this->data;
        $this->padno = $this->padno == null && is_object($data) && property_exists($data, 'padno') == true ? $data->padno : $this->padno;
        //$data->id = $data->id == null ? $this->id : $data->id;....////
        $this->data = is_object($data) || is_array($data) ? Json::encode($data) : $data;
        
        if ($this->createdby_name == null && is_object($this->createdby) == true) {
            $this->createdby_name = $this->createdby->fullname;
        } elseif ($this->createdby_name !== null && is_object($this->createdby) == true) {
            $this->createdby_name = $this->createdby_name;
        } else {
            $this->createdby_name = Yii::$app->user->isGuest == false ? Yii::$app->user->identity->fullname : 'System Console';
        }
        if ($this->updatedby_name == null && is_object($this->updatedby) == true) {
            $this->updatedby_name = $this->updatedby->fullname;
        } elseif ($this->updatedby_name !== null && is_object($this->updatedby) == true) {
            $this->updatedby_name = $this->updatedby_name;
        } else {
            $this->updatedby_name = Yii::$app->user->isGuest == false ? Yii::$app->user->identity->fullname : 'System Console';
        }
        return parent::beforeSave($insert);
    }

    public function afterSave($a, $changed){
        $data = $this->data;
        //yii::debug(Yii::$app->controller->action->id, 'action');
        //yii::debug(stripos(Yii::$app->controller->action->id, 'import'),'action');
        //Push to Sync Queue
        if(Yii::$app->name !== 'NGaugeApi' && Yii::$app->name !== 'app-console'){
            $this->data = json::decode($data, 1);
        }
        return parent::afterSave($a, $changed);
    }
    
    public function init(){
        if(Yii::$app->name !== 'app-console' && Yii::$app->request->get('relatedid') !== null){
            $this->relatedid = Yii::$app->request->get('relatedid');
        }
        if($this->formclass !== null){
            $class = !str_contains($this->formclass, '\\') ? $this->formns.$this->formclass : $this->formclass;
            $formdata = new $class(['actid' => $this->actid, 'id' => $this->id]);
            $this->data = $formdata;
        }
        return parent::init();
    }
    

    public function getActivity() {
		return $this->hasOne(Activities::class, ['id' => 'actid']);
    }
    

    public function getFormname(){
        $class = !str_contains($this->formclass, '\\') ? $this->formns.$this->formclass : $this->formclass;
        $model =  new $class();
        return $model->formname;
    }

}
