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

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


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\{Html, Xlsx};
use PhpOffice\PhpSpreadsheet\Style\{Alignment, Border, Fill, Color, NumberFormat, Protection};
use PhpOffice\PhpSpreadsheet\Worksheet\{PageSetup, Worksheet};

class ServiceLifeJacketBulk extends \common\Models\DynamicModel
{
	CONST HEADERSTYLE = [
		'font' => [
			'bold' => true,
			'size' => 11,
			'name' => 'Arial',
		],
		'alignment' => [
			'horizontal' => Alignment::HORIZONTAL_CENTER,
			'vertical' => Alignment::VERTICAL_CENTER,
		],
		'borders' => [
			'outline' => [
				'borderStyle' => Border::BORDER_THIN,
				
			],
		],
		'fill' => [
			'fillType' => Fill::FILL_SOLID,
			'startColor' => [
				'argb' => Color::COLOR_WHITE,
			],
		],
		'color' => [
			'argb' => Color::COLOR_BLACK
		]
	];
	CONST CELLSTYLE = [
		'font' => [
			'size' => 8,
			'name' => 'Arial',
		],
		'alignment' => [
			'horizontal' => Alignment::HORIZONTAL_CENTER,
			'vertical' => Alignment::VERTICAL_CENTER,
		],
		'borders' => [
			'outline' => [
				'borderStyle' => Border::BORDER_THIN,
				'color' => [
					'argb' => 'FF0000000',
				],
			],
			'inside' => [
				'borderStyle' => Border::BORDER_THIN,
				'color' => [
					'argb' => 'FFFFFFFF'
				],
			],
		],
		'fill' => [
			'fillType' => Fill::FILL_SOLID,
			'startColor' => [
				'argb' => Color::COLOR_WHITE,
			],
		],
		'color' => [
			'argb' => Color::COLOR_BLACK
		]
		];
	public $filename = 'Service_Life_Jacket_bulk';
	public $viewpath = '@modules/forms/views/default/Service_Life_Jacket_bulk_view';

	public $pdf = '@modules/forms/views/default/Service_Life_Jacket_bulk_view';

	const type = 'ServiceLifeJacketBulk';
	public $form = 'ServiceLifeJacketBulk';

	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->relatedid])
			->andWhere(['not', ['in', 'status', ['Deleted' , null]]])
			->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);  
		
		return ;
	}
        
		

    public function loadSubForms() {
        $items = [];
		$act = $this->activity;

		$ids = [];
		if (($subforms = $this->subforms)) {
			foreach($subforms as $key => $form) {
				$sform = new ServiceLifeJacket();
				$sform->attributes = $form;
				if (($activityitem = $sform->activityitem)?->status !== 'Deleted' || empty($activityitem?->status)) {
					$sform->hasMethod('loadItems') ? $sform->loadItems($sform->items) : false;
					$items[$sform->id] = $sform;
					$ids[] = $sform->actid;
				}
			}
        } else {
            $items = [new ServiceLifeJacket()];
			
        }
		if (($actitems = $act?->activitiesitems)) {
			foreach($actitems as $actitem) {
				if (!in_array($actitem->id, $ids) && $actitem->status !== 'Deleted' && in_array($actitem->type, ['lifejacket', 'lifejacketbulk'])) {
					
					$id = \common\models\Base::tempid();
					$sform = new ServiceLifeJacket(['id' => $id]);
					$sform->type = $actitem->product;
					$sform->productid = $actitem->product;
					$sform->serial_number = $actitem->serial;
					$sform->assetid = $actitem->assetid;
					$sform->actid = $actitem->id;
					$items[$id] = $sform;
				}
			}
		}
        $this->subforms = $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'],
					['default', 'value' => 'Active']
				],
				'label' => Yii::t('app', 'Status'),
				'input' => false,
			],
			'relatedid' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Id'),
				'input' => false,
			],
			'actid' => [
				'rules' => [
					['string']
				],
				'label' => Yii::t('app', 'Id'),
				'input' => false,
			],
			'subformscount' => [
				'rules' => [
					['integer']
				],
				'label' => Yii::t('app', 'No of Forms'),
				'input' => false,
			],
			'subforms' => [
				'rules' => [
					['safe']
				],
				'label' => Yii::t('app', 'Addititional Items'),
				'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' => [
					['string']
				],
				'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' => 'textInput',
					'fieldlist' => null,
					'options' => ['prompt' => 'Please Select', 'class' => 'custom-select'],
					'width' => 'd-inline',
				],
			],
			'allchecks' => [
				'rules' => [
					['boolean']
				],
				'label' => Yii::t('app', 'All Checks'),
				'input' => [
					'input' => 'checkbox',
					'fieldclass' => null,
					'fieldlist' => null,
					'options' => ['label' => false],
					'width' => 'col-md-1',
				],
			],
			'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',
			],
			'verification1' => [
				'rules' => [
					['boolean']
				],
				'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']
				],
				'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']
				],
				'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']
				],
				'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']
				],
				'label' => Yii::t('app', ''),
				'input' => false,
			],
			'verification6' => [
				'rules' => [
					['boolean']
				],
				'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']
				],
				'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']
				],
				'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' => 'textInput',
					'fieldlist' => null,
					'options' => ['prompt' => 'Please Select'],
					'width' => 'col-12 col-md-6',
				],
			],

			'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 PreProcess()
	{
		empty($this->certno) == true ? $this->certno = $this->CertnofromForms() : false;
		
	}
	public function PostProcess()
	{
		foreach($this->subforms as $key => $model) {
			$actitem = $model->activityitem;
			if ($actitem && !str_contains(Yii::$app->request->url, 'activities')) {
				$model->serial_number !== $actitem->serial ? $actitem->serial = $model->serial_number : false;
				$model->type !== $actitem->product ? $actitem->product = $model->type : false;
				//$model->assetid !== $actitem->assetid ? $actitem->assetid = $model->assetid : false;
				$actitem->save();
			}
			$this->status == 'Complete' ? $model->updateAsset() : false;
		}
	}

	/**
     * 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->loadSubForms();
			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',
			]);
		}
		$subforms = $this->subforms;
		if (Yii::$app->request->isConsoleRequest == false && $subforms && yii\base\Model::loadMultiple($subforms, Yii::$app->request->post()) && yii\base\Model::ValidateMultiple($subforms)) {
			foreach($subforms as $subform) {
				if (array_key_exists('ServiceItem', Yii::$app->request->post()) &&  array_key_exists($subform->id, Yii::$app->request->post('ServiceItem'))) {
					$data = Yii::$app->request->post('ServiceItem')[$subform->id];
					$subform->ProcessItemsBulk($data);
				} else {
					$subform->items = [];
				};
				if (!empty($this->date_of_service) || !empty($this->date_of_next_service) ) {
					$subform->date_of_service !== $this->date_of_service ? $subform->date_of_service = $this->date_of_service: false;
					$subform->date_of_next_service !== $this->date_of_next_service ? $subform->date_of_next_service = $this->date_of_next_service: false;
				}
				$this->subforms[$subform->id] = $subform;
			}
		}
			
		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' => 'ServiceLifeJacketBulk']), $this->certno.'.pdf', true);
	}



	public static function checkandcreate(string $relatedid, array $data) : bool
	{
		$form = self::findOne(['relatedid' => $relatedid, 'status' => 'Active']);
		if (!$form) {
			$form = $dataModel = new \modules\forms\models\sub\ServiceLifeJacketBulk();
			$dataModel->relatedid = $relatedid;
			$dataModel->actid = $relatedid;
		} else {
			$dataModel = $form;
		}

		$forms = $dataModel->subforms;
		$actids = is_array($forms) ? array_column($forms, 'actid') : [];
		
		foreach($data as $key => $act) {
			if (!in_array($key, $actids)) {
				$model = new \modules\forms\models\sub\ServiceLifeJacket();
				$model->loadDefaultValues();
				$model->actid = $key;
				$model->relatedid = $relatedid;
				$model->type = $act['productid'];
				$model->productid = $act['productid'];
				$model->serial_number = $act['serial'];
				if (empty($act['serial']) == false) {
					$model->assetid = $act['assetid'];
					//$model->date_of_manufacturer =  is_object($asset) && empty($asset->dom) == false ? $asset->dom : null;
				}
				$relatedparts = \modules\custom\models\Products::getPrimeparts($act['productid']);
				
				if (\is_array($relatedparts) && count($relatedparts) > 0) {
					$items = [];
					foreach($relatedparts as $key => $part) {
						$sitem = new \modules\forms\models\sub\ServiceItem();
						
						$sitem->type = $part['product_name'];
						$sitem->typeid = $part['id'];
						$sitem->qty = empty($part['pack_qty']) == false ?$part['pack_qty'] : 1;
						$items[] = $sitem;
					}
				} else {
					$items = $model->items;
				}
				$model->items = $items;
				$forms[$model->id]  = $model;
			} else {
				foreach($forms as $subform) {
					if ($subform->actid == $act['actid']) {
						array_key_exists('product', $act) && empty($subform->type) ? $subform->type = $act['product'] : false;
						array_key_exists('serial', $act) && empty($subform->serial_number) ? $subform->serial_number = $act['serial'] : false;
					}
					$forms[$subform->id]  = $subform;

				}
			}
		}
        $dataModel->subforms = $forms;
		return $dataModel->save();
	}

	public function deleteForm($id){
		$forms = [];
		foreach ($this->subforms as $key => $subform) {
			if ($id !== $subform['actid']){
				$forms[$key] = $subform;
			}
		}
		$this->subforms = $forms;
		$this->save();
	}
}
