<?php 
namespace modules\forms\models\sub;

use PhpOffice\PhpSpreadsheet\Calculation\Category;
use yii;
use common\models\{Model, DynamicModel};
use yii\helpers\{ArrayHelper, FileHelper};
use backend\models\{Categoriesbe, Attributesvalues};
use modules\custom\models\Assetsbe;

class ServiceLifeJacket extends DynamicModel
{
	public $form = 'ServiceLifeJacket';
	const type = 'ServiceLifeJacket';
	public $filename = 'Service_Life_Jacket';
	public $viewpath = '@modules/forms/views/default/Service_Life_Jacket_view';
	
	public function getActivity() {
		return \modules\activities\models\Activities::find()->where(['id' => $this->actid])->One();
	}
	
	public function getImages() {
		if($this->activity){
			$dir = Yii::getAlias('@documents').'/'.$this->activity?->jobno;
			return file_exists($dir) ? FileHelper::findFiles($dir, ['only' => [$this->certno.'*.json']]) : [];
		} else {
			return [];
		}
	}

	public function getActivityitem()
	{
		return \modules\activities\models\Activitiesitemsbe::find()
			->where(['id' => $this->actid])
			->andWhere(['not', ['status' => 'Deleted']])
			->One();
	}
	public function getProduct()
	{
		return \backend\models\Productsbe::find()->where(['id' => $this->type])->One();
	}

	public function CertnofromForms(){
		if (empty($this->certno) == true){
			$certno = new \yii\db\Expression("cast(json_value(`forms`.`data`, '$.certno') as INTEGER)");
			$form = \modules\forms\models\Forms::find()
			->select(["$certno as certno"])
			->where(['form' => $this->form])
			->orderby(['certno' => SORT_DESC])
			->limit(1)
			->asArray()
			->one();
			
			$result = empty($form['certno']) == false ? intval($form['certno']) + 1 : 2000;
		} else {
			$result = $this->certno;
		}
		return $result;
	}
	/**
	 * Constructor.
	 * @param array $attributes the attributes (name-value pairs, or names) being defined.
	 * @param array $config the configuration array to be applied to this object.
	 */
	public function __construct(array $attributes = [], $config = [])
	{
		parent::__construct($attributes, $config);
        $this->loadItems($this->items);
		return ;
	}
	

    public function loadItems($data){
        $items = [];
        if($data !== null){
            foreach($data as $key => $item){
                $serviceitem = new ServiceItem($item);
                $serviceitem->attributes = $item;
                $items[$key] = $serviceitem;
            }
        } 
        $this->items = $items;
    }
	

	


	public static function localattributes(){
		return [
			'id' => [
				'rules' => [
					['string'],
					['default', 'value'=> \common\models\Base::Tempid()]
				],
				'label' => Yii::t('app', 'Id'),
				'input' => false,
			],
			'status' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Status'),
				'input' => false,
			],
			'created_at' => [
				'rules' => [
					['integer']
				],
				'label' => Yii::t('app', 'Created At'),
				'input' => false,
			],
			'relatedid' => [
				'rules' => [
					['safe']
				],
				'label' => Yii::t('app', 'Activity Item Id'),
				'input' => false,
			],
			'actid' => [
				'rules' => [
					['safe']
				],
				'label' => Yii::t('app', 'Activity Item Id'),
				'input' => false,
			],
			'items' => [
				'rules' => [
					['safe']
				],
				'label' => Yii::t('app', 'Addititional Items'),
				'input' => false,
			],
			'client_fullname' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Client Name'),
				'input' => 'default',
			],
			'client_address' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Client Address'),
				'input' => 'default',
			],
			'name' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Name'),
				'input' => 'default',
			],
			'phone' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Phone No'),
				'input' => 'default',
			],
			'mobile' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Mobile No'),
				'input' => 'default',
			],
			'email' => [
				'rules' => [
					['string'],
                    ['email'],
				],
				'label' => Yii::t('app', 'Email Address'),
                'input' => [
					'input' => 'textInput',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['type' => 'email', ],
					'width' => 'col-md-3',
				],
			],
			'ownerid' => [
				'rules' => [
					['safe']
				],
				'label' => Yii::t('app', 'Owner ID'),
				'input' => 'default',
			],
			'assetid' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Assetid'),
				'input' => 'default',
			],
			'agent' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Chandler / Agent'),
				'input' => 'default',
			],
			'type' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'LifeJacket Type'),
                'input' => [
					'input' => 'dropdownList',
					'fieldlist' =>  Yii::$app->request->isConsoleRequest == false && Yii::$app->request->get('form') == 'ServiceLifeJacket' ? Yii::$app->cache->getorset('jacket-type', function() {
                        return ArrayHelper::map(\backend\models\Productsbe::find()
                        ->select(['products.id', 'products.language', 'products.product_name'])
                        ->where(['categories.name' => 'Life Jackets'])
                        ->orderby(['product_name' => SORT_ASC])
                        ->joinwith('categories')
                        ->asArray()
                        ->all(),
                        'id', 'product_name') ;
                    }, 3600) : [], 
					'options' => ['prompt' => 'Please Select', 'class' => 'custom-select'],
					'width' => 'col-12 col-md-6',
				],
			],
			'ljtypea' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'LifeJacket Type'),
				'input' => 'default',
			],
			'productid' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Product ID'),
				'input' => 'default',
			],
			'productname' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'product Name'),
				'input' => 'default',
			],
			'solas' => [
				'rules' => [
					['boolean']
				],
				'label' => Yii::t('app', 'Solas'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false],
					'width' => 'col-md-1',
				],
			],
			'serial_number' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Serial Number'),
                'input' => [
					'input' => 'textInput',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => [],
					'width' => 'col-md-5',
				],
			],
			'date_of_manufacturer' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Date of Manufacturer'),
				 'input' => [
					'input' => 'textInput',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => [],
					'width' => 'col-md-3',
				],
			],
			'date_of_service' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Date of Service'),
				'input' => 'default',
			],
			'date_of_next_service' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Date of Next Service'),
				'input' => 'default',
			],
			'cylindersize' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Clyinder Size'),
				'input' => 'default',
			],
			'grossweight' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Gross Weight'),
				'input' => 'default',
			],
			'actualweight' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Actual Weight'),
				'input' => 'default',
			],
			'manufacturedate' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Manufacture Date'),
				'input' => [
					'input' => 'widget',
					'fieldclass' => \kartik\date\DatePicker::class,
					'fieldlist' => null,
					'options' => ['type' => 1, 'options' => ['autocomplete' => 'n'], 'pluginOptions' => ['convertFormat' => true, 'format' => 'dd/mm/yyyy']],
					'width' => 'col-md-3',
				],
			],
			'cylindersize_b' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => 'default',
			],
			'grossweight_b' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => 'default',
			],
			'actualweight_b' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => 'default',
			],
			'manufacturedate_b' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => [
					'input' => 'widget',
					'fieldclass' => \kartik\date\DatePicker::class,
					'fieldlist' => null,
					'options' => ['type' => 1, 'options' => ['autocomplete' => 'n'], 'pluginOptions' => ['convertFormat' => true, 'format' => 'dd/mm/yyyy']],
					'width' => 'col-md-3',
				],
			],
			'pressuretest' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Pressure Test'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-3',
				],
			],
			'pressuretest_start' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Start Time'),
				'input' => [
					'input' => 'widget',
					'fieldclass' => \kartik\time\TimePicker::class,
					'fieldlist' => null,
					'options' => ['options' => ['autocomplete' => 'n'], 'pluginOptions' => ['convertFormat' => true, 'format' => 'H:i']],
					'width' => 'col-md-3',
				],
			],
			'pressuretest_finish' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Finish Time'),
				'input' => [
					'input' => 'widget',
					'fieldclass' => \kartik\time\TimePicker::class,
					'fieldlist' => null,
					'options' => ['options' => ['autocomplete' => 'n'], 'pluginOptions' => ['convertFormat' => true, 'format' => 'H:i']],
					'width' => 'col-md-3',
				],
			],
			'pressuretest2' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-3',
				],
			],
			'pressuretest_starttime2' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => [
					'input' => 'widget',
					'fieldclass' => \kartik\time\TimePicker::class,
					'fieldlist' => null,
					'options' => ['options' => ['autocomplete' => 'n'], 'pluginOptions' => ['convertFormat' => true, 'format' => 'H:i']],
					'width' => 'col-md-3',
				],
			],
			'pressuretest_starttemp2' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Start Temp'),
				'input' => 'default'
			],
			'pressuretest_finishtime2' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Finish Time'),
				'input' => [
					'input' => 'widget',
					'fieldclass' => \kartik\time\TimePicker::class,
					'fieldlist' => null,
					'options' => ['options' => ['autocomplete' => 'n'], 'pluginOptions' => ['convertFormat' => true, 'format' => 'H:i']],
					'width' => 'col-md-3',
				],
			],
			'pressuretest_finishtemp2' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Finish Temp'),
				'input' => 'default',
			],
			'pressuretest3' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-3',
				],
			],
			'pressuretest_starttime3' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => [
					'input' => 'widget',
					'fieldclass' => \kartik\time\TimePicker::class,
					'fieldlist' => null,
					'options' => ['options' => ['autocomplete' => 'n'], 'pluginOptions' => ['convertFormat' => true, 'format' => 'H:i']],
					'width' => 'col-md-3',
				],
			],
			'pressuretest_starttemp3' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => 'default'
			],
			'pressuretest_finishtime3' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => [
					'input' => 'widget',
					'fieldclass' => \kartik\time\TimePicker::class,
					'fieldlist' => null,
					'options' => ['options' => ['autocomplete' => 'n'], 'pluginOptions' => ['convertFormat' => true, 'format' => 'H:i']],
					'width' => 'col-md-3',
				],
			],
			'pressuretest_finishtemp3' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => 'default'
			],
			'pressuretest4' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Size'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-3',
				],
			],
			'solast1' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', '1: Visual inspection of external webbing'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'solast2' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', '2: Visual inspection of cover fabric'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'solast3' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', '3: Visual inspection of bladder fabric'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'solast4' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', '4: Inflation system'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'allchecks' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', 'All checks'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification1' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', 'Visual Inspection of Exterior Webbing'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification2' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', 'Visual inspection of cover and lung integrity'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification3' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', 'Pressure test lung, inflate until firm and leave for 12 hours'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification4' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', 'Remove and check the gas cyclinder for weight, seal integrity & corrosion damage'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification5' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', ''),
				'input' => false,
			],
			'verification6' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', 'Remove and replace auto firing cartridge (auto model)'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification7' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', 'Check firing head operation, seal & lever arm retaining clips'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification8' => [
				'rules' => [
					['boolean'],
					['default', 'value' => 1],
				],
				'label' => Yii::t('app', 'Check harness belt fittings & sewing integrity'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification9' => [
				'rules' => [
					['boolean']
				],
				'label' => Yii::t('app', 'Check standard belt fittings & sewing integrity'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification10' => [
				'rules' => [
					['boolean']
				],
				'label' => Yii::t('app', 'Repack and fold lung & cover'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification11' => [
				'rules' => [
					['boolean']
				],
				'label' => Yii::t('app', ''),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'verification12' => [
				'rules' => [
					['boolean']
				],
				'label' => Yii::t('app', ''),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false, ],
					'width' => 'col-md-12',
				],
			],
			'technician' => [
				'rules' => [
					['safe']
				],
				'label' => Yii::t('app', "By Service Technician",),
				'input' => [
					'input' => 'dropdownList',
					'fieldlist' => Yii::$app->request->isConsoleRequest == false && Yii::$app->request->get('form') == 'ServiceLifeJacket' ? Yii::$app->cache->getorset('raft-techs', function() {
                        return ArrayHelper::map(\backend\models\User::find()->where(['like', 'groups', 'Servicing'])->orderby(['username' => SORT_ASC])->all(), 'id', 'fullname');
                    }, 3600) : [], 
					'options' => ['prompt' => 'Please Select'],
					'width' => 'col-12 col-md-6',
				],
			],
			'tested' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', "Status",),
				'input' => [
					'input' => 'dropdownList',
					'fieldlist' => ['passed' => 'PASSED', 'failed' => 'FAILED'], 
					'options' => ['prompt' =>'Please Select'],
					'width' => 'col-12 col-md-6',
				],
			],
			'remarks' => [
				'rules' => [
					['string']
				],
				'label' => null,
				'input' => [
					'input' => 'widget',
					'fieldclass' => \common\widgets\TinyMce::class, 
					'fieldlist' => false, 
					'options' => ['height' => '100px'],
					'width' => 'col-12',
				],
			],

			'certno' => [
				'rules' => [
					['integer']
				],
				'label' => Yii::t('app', 'Certificate No'),
				'input' => [
					'input' => 'textInput',
					'fieldlist' => false, 
					'options' => ['type' => 'number', 'readonly' => true],
					'width' => 'col-12 col-md-3',
				],
			],
			'invoiceno' => [
				'rules' => [
					['integer']
				],
				'label' => Yii::t('app', 'Invoice Number'),
				'input' => [
					'input' => 'textInput',
					'fieldlist' => false, 
					'options' => ['type' => 'number'],
					'width' => 'col-12 col-md-3',
				],
			],
			'signature' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Signature'),
				'input' => [
					'input' => 'widget',
					'fieldclass' => \common\widgets\SignatureInput::class,
					'fieldlist' => false, 
					'options' => [],
					'width' => 'col-12 col-md-3',
				],
			],

		];
	}

	public function updateAsset(){
		$asset = Assetsbe::Find()->where(['id' => $this->assetid])->one();
		if($asset){
			$data = $asset->data;
			$data->last_service = $this->date_of_service;
			$data->next_service = $this->date_of_next_service;
			$data->last_service_id = $this->id;
			$asset->data  = $data;
			$asset->save();
		}
	}

	public function PreProcess()
	{
		if (yii::$app->controller->id !== 'asset' && empty($this->assetid) == false && empty($this->serial_number) == false && empty($this->productid) == false) {
			$asset = \modules\custom\models\Assetsbe::findbyserial($this->serial_number, $this->productid);
			if(!$asset && $this->activityitem?->id !== null){	
				$asset = \modules\custom\models\Assetsbe::create($this->activityitem->id);
			}
			$this->assetid = $asset?->id;
		}
		$this->date_of_manufacturer = is_int($this->date_of_manufacturer) ? date('d/m/Y', $this->date_of_manufacturer) : $this->date_of_manufacturer;
		empty($this->certno) == true ? $this->certno = $this->CertnofromForms() : false;
		empty($this->assetid) == false && yii::$app->controller->id == 'forms' ? $this->updateAsset() : false;
		$this->processItems(yii::$app->request->post());
	}

	public function ProcessItems($post){
		$items = $this->items;
		if(array_key_exists('ServiceItem', $post) == true){
			$postData = $post['ServiceItem'];
			$pageIds = [];
			foreach($postData as $key => $data){
				$pageIds[] = $data['id'];
			}
			$itemsb = [];
			foreach($items as $key => $item){
				$itemsa[$item->id] = $item;
			}
			$x = 0;
			$results = [];
			foreach($postData as $key => $data){
				if(in_array($data['id'], $pageIds) == true && $data['id'] !== ''){
					$item = $itemsa[$data['id']];
					$item->attributes = $data;
					$results[] = $item->validate();
					$itemsb[$x] = $item;
				}elseif($data['id'] == ''){
					$item = new ServiceItem();
					$item->attributes = $data;
					$results[] = $item->validate();
					$itemsb[$x] = $item;
				}
				$x++;
			}
			$this->items = $itemsb;
			return \in_array(false, $results) ? false : true;
		} else {
			$this->items = [];
			return true;
		}
	}
	public function ProcessItemsBulk($data){		
		$postData = $data['items'];
		$items = [];
		$x = 0;
		$results = [];
		foreach($postData as $key => $data){
			$item = new ServiceItem();
			$item->attributes = $data;
			$results[] = $item->validate();
			$items[$x] = $item;
			$x++;
		}
		$this->items = $items;
		return \in_array(false, $results) ? false : true;
	}
    /**
     * Finds self
     */
    public static function find(){
        return \my\models\Forms::find()
		->onCondition(['form' => 'ServiceLifeJacket']);        
    }

	public static function createServicesheet($actitem){
		$model = new self();
		$model->loadDefaultValues();
		$activity = $actitem->activity;
        $product = $actitem->productl;
		$model->relatedid = $actitem->id;
        $model->actid = $actitem->relatedid;
        $model->ownerid = $activity?->clientid;
        $model->productid = $actitem->product;
        $model->serial_number = $actitem->serial;
        property_exists($model, 'size') ? $model->size = $product?->data->custom->size : false;
        property_exists($model, 'packed') ? $model->packed = $product?->data->custom->packed : false;
        if(empty($actitem->serial) == false){
            $asset = $actitem->asset;
            $model->assetid = $actitem->assetid;
            $model->date_of_manufacturer =  is_object($asset) && empty($asset->dom) == false ? $asset->dom : null;
        }
        if(empty($client = $activity?->client) == false){
            $model->mobile =$client->adv->mobileno;
            $model->phone = $client->adv->phoneno;
            $model->email = $client->email;
        }elseif (empty($activity->agentname) == false) {
            $agentl = $activity->agentl;
            if(property_exists($agentl, 'adv')){
                $model->email = $agentl->email;
                $model->mobile = $agentl->adv->mobileno;
                $model->phone = $agentl->adv->phoneno;
                $model->agent = $agentl->fullname;
            } else {
                $model->email = $agentl->email;
                $model->phone = $agentl->addressl?->telephone;
                $model->agent = $activity->agentname;

            }
        }
        $model->client_fullname = $activity?->clientname;
        $model->email = $activity?->email;
        $relatedparts = \modules\custom\models\Products::getPrimeparts($actitem->product);
        
        if(\is_array($relatedparts) && count($relatedparts) > 0){
            $items = [];
            foreach($relatedparts as $key => $part){
                $item = new \modules\forms\models\sub\ServiceItem();
                $item->id = \common\models\Base::Tempid();
                $item->type = $part['product_name'];
                $item->typeid = $part['id'];
                $item->qty = empty($part['pack_qty']) == false ?$part['pack_qty'] : 1;
                $items[$item->id] = $item;
            }
        } else {
            $items = $model->items;
        }
        $model->items = $items;
        return $model->save();
	}

	/**
     * Finds self
     */
    public static function findOne($options) {
       
		$model = \modules\forms\models\Forms::find()
			->onCondition(['form' => static::type])
			->andonCondition($options)
			->one();    
		if(!$model){
			return false;
		} else {
			$data = $model->data;
			$dataModel = new Self();
			//$dataModel->id = $dataModel->id == null ? $model->id : self::tempid();
			$dataModel->attributes = json_decode($data,1);
			$dataModel->loadItems($dataModel->items);
			return $dataModel;
		}
    }

	public function afterValidate(){
		
		return parent::afterValidate();
	}

	public function save(){
	//	$this->id = empty($this->id) ? (Yii::$app->controller->id == 'forms' ? $_GET['id'] : \common\models\Base::tempid()) : $this->id;
		$formModel = \modules\forms\models\Forms::find()
			->onCondition(['form' => $this->form])
			->andonCondition(['id' => $this->id])
			->one();
		if($formModel){
			Yii::$app->request->isConsoleRequest == false && $this->hasMethod('PreProcess') ? $this->PreProcess(Yii::$app->request->post()) : false;
			Yii::$app->request->isConsoleRequest == false && $this->hasMethod('PostProcess') ? $this->PostProcess(Yii::$app->request->post()) : false;
		} else {
			$formModel = new \modules\forms\models\Forms([
				'id' => $this->id, 
				'language' => 'en', 
				'form' => $this->form, 
				'formclass' => $this->className(), 
				'relatedid' => $this->relatedid,
				'status' => 'Active',
			]);
		}
		
		if($this->validateModel()){
			$formModel->data = $this->attributes;
			return $formModel->save();
		}
		return false;
	}

	public function Pdf(){
		return \common\models\Base::generatePdf($this->id, null, \yii\helpers\Url::to(["/forms/pdfview", 'id' => $this->id, 'form' => 'ServiceLifeJacket']), $this->id.'.pdf', true);
	}
	public function loadDefaultValues(){
		$this->id = \common\models\Base::Tempid();
		$this->allchecks = true;
		$this->verification1 = true;
		$this->verification2 = true;
		$this->verification3 = true;
		$this->verification4 = true;
		$this->verification5 = true;
		$this->verification6 = true;
		$this->verification7 = true;
		$this->verification8 = true;
		$this->verification9 = true;
		$this->verification10 = true;
		$this->verification11 = true;
		$this->verification12 = true;
		$this->solast1 = true;
		$this->solast2 = true;
		$this->solast3 = true;
		$this->solast4 = true;
	}
}
