<?php

namespace modules\activities\models;

use Yii;
use yii\helpers\{Arrayhelper, Json};
use modules\custom\models\{Assetsbe};
use backend\models\{Lookuptablebe, Servicebaysbe};
use modules\custom\models\Products;
/**
 * This is the model class For table "activities_items".
 *
 * @property string $id
 * @property string $language
 * @property string $qrimage
 * @property string $status
 * @property string $created_by
 * @property string $updated_by
 * @property string $deleted_by
 * @property string $createdby_name
 * @property string $updatedby_name
 * @property string $deletedby_name
 * @property string $relatedid
 * @property string $product
 * @property string $serviceid
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $deleted_at
 * @property string $status
 * @property string $type
 * @property mixed $servicesheet
 */
class Activitiesitemsbe extends \common\models\Base
{
    public $dates = ['created_at', 'updated_at', 'deleted_at'];
    public $uniqueidentifiers = ['product', 'locationid'];
    public $securefields = [];
    public $service;
    public $arrived;

    const STATUS = [null, '','Finished', 'Warehouse','CONDEMNED ', 'Booked', 'Arrived', 'Awaiting Service', 'Service in Progress', 'Complete', 'Awaiting Authorisation', 'Active', 'Quote Needed'];
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'activities_items';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return array_merge(parent::rules(), [
            [['id', 'language', 'created_by', 'updated_by', 'deleted_by', 'relatedid', 'product', 'productname', 'serviceid', 'status', 'notes', 'type', 'assetid', 'locationid', 'serial', 'qrimage', 'certno', 'certdata', 'typea'], 'string'],
            [['created_at', 'updated_at', 'deleted_at', 'servicetype', 'addons'], 'safe'],
            ['id', 'default', 'value' => parent::Tempid()],
            [['imported'], 'boolean'],
            [['service', 'arrived'], 'boolean'],
            [['id'], 'unique'],            
            ['servicetype', 'required', 'when' => function ($model) {
                if (str_contains(Yii::$app->controller->action->id, 'bookservice') && Yii::$app->request->isPost) {
                return (empty($this->servicetype) && empty($this->service)) ? false : true;
                }
            }, 
                
            ],
        ]);
    }
    public function validateArray($attribute, $params)
    {
        if (!in_array(true, $this->$attribute)) {
            $this->addError($attribute, 'At least one Option must be selected.');
        }
    }
	public function checkService($attribute, $params)
    {
        if ($this->service == true && empty($this->servicetype)) {	
            $this->addError($attribute, 'At least one Option must be selected.');
			return false;
        }
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        $local = [
            'relatedid' => yii::t('app', 'Relatedid'),
            'product' => yii::t('app', 'Product'),
            'productl.product_name' => yii::t('app', 'Product Name'),
            'serviceid' => yii::t('app', 'Serviceid'),
            'status' => yii::t('app', 'Status'),
            'type' => yii::t('app', 'Type'),
            'certno' => yii::t('app', 'Certificate Number'),
            'certdata' => yii::t('app', 'Certificate'),
            'productname' => yii::t('app', 'Product Name'),
            'servicetype' => yii::t('app', 'Service Type'),
        ];
        return array_merge(parent::attributelabels(),$local);
    }

    public function getServicesheet()
    {
        if (str_contains($this->type, 'boat')) {
            return null;
        }
        $form = $this->type == 'lifejacket' && count($this->siblings) > 0 && (strtotime(str_replace('/', '-', $this->created_at)) > strtotime('2024-09-17 18:00')) ? 'ServiceLifeJacketBulk' : $this->realtypes('new');
        $class = "\\modules\\forms\\models\\sub\\$form";
        return $class::findOne(['relatedid' => str_contains($form, 'Bulk') ? $this->relatedid : $this->id, 'status' => 'Active']);        
    }

    public function getProductl()
    {
        return $this->hasOne(Products::class, ['id' => 'product']);
    }
    public function getParts()
    {
        $productid = $this->product;
        $data = lookuptablebe::find()
            ->where(['sourceid' => $productid])
            ->andWhere(['related' => 'Parts'])
            ->joinwith(['products'])
            ->all();
        return $data;
    }
    
    public function getSiblings() {
        return self::find()
            ->where(['relatedid' => $this->relatedid])
            ->andWhere(['type' => $this->type])
            ->andWhere(['not', ['status' => 'Deleted']])
            ->andWhere(['not', ['id' => $this->id]])
            ->all();
    }

    public function getAsset() {
        return $this->hasOne(\modules\custom\models\Assetsbe::class, ['id' => 'assetid']);
    }

    public function getActivity()
    {
        return $this->hasOne(\modules\activities\models\Activities::class, ['id' => 'relatedid']);
    }
    public function getClient()
    {
        return $this->hasOne(\backend\models\User::class, ['id' => 'clientid'])
        ->via('activity');
    }
    public function getLocationl()
    {
        return $this->hasOne(Servicebaysbe::class, ['id' => 'locationid']);
    }

    public function beforeSave($insert)
    {
        if ($this->locationid !== $this->getOldAttribute('locationid')) {
            $oa = $this->getOldAttribute('locationid');
            if ($oa && $this->locationid !== $oa) {
                $sb = Servicebaysbe::find()->where(['id' => $oa])->one();
                $sb->occupied = false;
                $sb->relatedid = null;
                $sb->save();
                if ($this->locationid !== '' && $this->locationid !== null) {
                    $sbn = Servicebaysbe::find()->where(['id' => $this->locationid])->one();
                    $sbn->occupied = true;
                    $sbn->relatedid = $this->id;
                    $sbn->save();
                }
            } elseif (strlen($this->locationid) > 0) {
                $sbn = Servicebaysbe::find()->where(['id' => $this->locationid])->one();
                $sbn->occupied = true;
                $sbn->relatedid = $this->id;
                $sbn->save();
            }
            if (yii::$app->cache->exists('site_rack')) {
                yii::$app->cache->delete('site_rack');
            }
        }
        if (!empty($this->serial) && empty(trim($this->assetid))) {
            $asset = \modules\custom\models\Assetsbe::findorCreate(
                [
                    'email' => $this->activity?->email, 
                    'serial' => $this->serial, 
                    'model' => !empty($this->typea) ? $this->typea : null, 
                    'status' => 'Active', 
                    'productid' => $this->product,
                    'clientid' => $this->activity?->clientid, 
                    'date_of_purchase' => null, 
                    'type' => $this->type,
                    ]
                );
                $this->assetid = $asset->id;
            }
        $this->assetid = trim($this->assetid);
        empty($this->qrimage) ? $this->qrimage = self::Qr(base64_encode(json_encode(['type' => 'Service', 'id' => $this->id]))) : false;
        $this->servicetype = json_encode($this->servicetype);
        $this->addons = $this->addons !== 0 ? json_encode($this->addons) : null;
        return parent::beforeSave($insert);
    }


    public function afterFind() {
        parent::afterfind();
        $this->assetid = !empty(trim($this->assetid)) ? $this->assetid : null;
        $this->servicetype = json_decode($this->servicetype);
        $this->addons = json_decode($this->addons);
        return;
    }
    /**
     * AfterSave function
     *
     * @param  [type] $insert method
     * @param  [type] $atts   attributes
     * @return to Parent default \common\base\model;
     */
    public function afterSave($insert, $atts)
    {
        $servicesheet = $this->servicesheet;
        if ($servicesheet && isset($atts['status']) && $this->status == 'Complete') {
        }
        if ($servicesheet && isset($atts['status']) && $this->status == 'Deleted') {   
            $servicesheet->status = 'Deleted';
            $servicesheet->save();
        }
        return parent::afterSave($insert, $atts);
    }


    public function checkandCreate() {
         $mod = [];
        $id = $this->id;
        if (!($servicesheet = $this->servicesheet) && Yii::$app->request->isPost) {
            if ($this->type == 'liferaft') {
                $this->createServicesheet();
            } elseif (in_array($this->type, ['lifejacket', 'lifejacketbulk'])) {
                $siblings = self::find()
                    ->where(['relatedid' => $this->relatedid])
                    ->andWhere(['type' => ['lifejacket', 'lifejacketbulk']])
                    ->andWhere(['not', ['id' => $this->id]])
                    ->andWhere(['status' => Activitiesitemsbe::STATUS]);
                if ($siblings->count() == 0) {
                    $this->createServicesheet();
                } else {
                    $this->type = 'lifejacketbulk';
                \modules\forms\models\sub\ServiceLifeJacketBulk::checkandcreate($this, $siblings);
                    $this->updateAttributes(['type' => 'lifejacketbulk']);
                }
            }
        }
    }

    public function freelocations($id) {
        $locationsa = ArrayHelper::map(
            Servicebaysbe::find()
                ->select([
                    'id', 
                    'name', 
                    'location'])
                ->where(
                    [
                        'or', 
                        ['=', 'relatedid', $id], 
                        ['is', 'occupied', null], 
                        ['!=', 'occupied', 1]
                    ]
                )
                ->andwhere(['in', 'location', ['LR', 'F']])
                ->orderby('sequence')
                ->all(),
                'id', 
                'name', 
                'location'
            );
        $locationsb = ArrayHelper::map(
            Servicebaysbe::find()
            ->select([
                'id', 
                'name', 
                'location'])
            ->andwhere(['not',['in', 'location', ['LR', 'F']]])
            ->orderby('sequence')    
            ->all(),
            'id', 
            'name', 
            'location'
        );
        $locations = array_merge($locationsa, $locationsb);
        arsort($locations);
        return $locations;
    }

    /**
     * updates form with Serial Number, and details.
     *
     * @return void
     */
    public function updateForm() {
        if ($servicesheet = $this->servicesheet) {
            $form  = $servicesheet->data;
            $form->serial_number = $form->serial_number !== $this->serial || empty($form->serial_number) ? $this->serial : $form->serial_number; 
            //$form->date_of_service = $form->date_of_service !== $this->serial || empty($form->date_of_service) ? $this->serial : $form->date_of_service; 
            //$form->jobno = $form->jobno !== $this->activity->jobno ? $this->activity->jobno : $form->jobno; 
            $servicesheet->data = $form;
            $servicesheet->save();
        }
    }
	
	public function createServicesheet() {
		$id = $this->id;
		$formtype = $this->realtypes('new');

        $form = new \modules\forms\models\Forms([
            'id' => self::tempid(), 
            'language' => 'en', 
            'form' => $formtype, 
            'formclass' => $formtype, 
            'relatedid' => $this->id
        ]);
        $activity = $this->activity;
		global $formModel;
        $formModel = $form;
		$form->relatedid = $this->id;
        $product = $this->productl;
        $model = $form->data;
        $model->ownerid = $activity?->clientid;
        $model->productid = $this->product;
        $model->serial_number = $this->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($this->serial) == false) {
            $asset = $this->asset;
            $model->assetid = $this->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->mobile = $agentl->mobileno;
                $model->phone = $agentl->phoneno;
                $model->agent = $activity->agentname;

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



    public function realtypes(string $type = 'new') : string {
        return match($this->type) {
            'lifejacketbulk' => 'ServiceLifeJacketBulk',
            'lifejacket' => 'ServiceLifeJacket',
            'liferaft' => 'ServiceLifeRaft',
            'lifeboat' => 'ServiceLifeBoat',
            default => null,
        };
    }

    public function getTurnaround() {
        $asset = $this->asset;
        $out = '';
        if (is_object($asset)) {
            $keys = [];
            foreach($asset->deliveryservices as $key => $product) {
                $keys[$product->id] = $product->product_name;
            }
            foreach($asset->services as $key => $product) {
                $keys[$product->id] = $product->product_name;
            }
            $this->servicetype = $servicetype = $this->servicetype;
            if (is_array($servicetype)) {
                foreach($servicetype as $k => $val) {
                    $out .= in_array($val, array_keys($keys)) ? $keys[$val] .PHP_EOL: 'Standard Service' .PHP_EOL;
                }
            } elseif (is_array($keys) && array_key_exists(str_replace('"','', $servicetype), $keys)) {
				$out .=  $keys[str_replace('"','', $servicetype)] .PHP_EOL;
            } else {
                $out .=  $servicetype . ' Standard Service' .PHP_EOL;
            }
            
        } else {
            $out .= 'Standard Service (No Asset)' .PHP_EOL;
        }
        return $out;
    }
    public function delete(){
        $servicesheet = $this->servicesheet;
        if ($servicesheet && str_contains(get_class($servicesheet), 'Bulk')){
            $servicesheet->deleteForm($this->id);
        } 
        parent::delete();
    }
}
