<?php

namespace modules\activities\models;

use Yii;
use yii\helpers\{Html, Json};
use backend\models\{Address,Mailqueue,User};
use modules\activities\models\{Activitiesitemsbe};

/**
 * This is the model class For table "activities".
 *
 * @property string $id
 * @property string $client_id
 * @property string $status
 * @property integer $type_id
 * @property integer $status_id
 * @property integer $start
 * @property integer $finish
 * @property integer $due
 * @property integer $department
 * @property string $title
 * @property string $description
 * @property string $location
 */
class Activities extends \common\models\Base
{
    public $dates = [];
    public $securefields = [];
    public $uniqueidentifiers = [];
    public $attendees;
    public $products;
    public $clients = [];
    public $service = [];
    public $addons = [];
    public $unknownclientname; //Boolean
    public $items;
    public $deliveryaddress;
    public $collectionaddress;
    public $agent;
    /**
     * @inheritdoc
     */

    const SCENARIO_GRIDUPDATE = 'grid_update';
    const SCENARIO_BOOKSERVICE = 'book_service';

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios[self::SCENARIO_BOOKSERVICE] = ['id', 'duetime', 'status', 'description', 'type', 'relatedid', 'service', 'deliveryaddress', 'collectionaddress'];
        $scenarios[self::SCENARIO_GRIDUPDATE] = ['arrived', 'duetime', 'returned', 'status'];
        return $scenarios;
    }

    public static function tableName()
    {
        return 'activities';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['relatedid', 'title', 'description', 'location', 'assetid', 'imp_agentname', 'imp_clientname', 'imp_data', 'agentname', 'agentid', 'agent_contact', 'agent_contact_email', 'clientname', 'transportmethod', 'invoicedin'], 'string'],
            [['status', 'type', 'department', 'engineer', 'clientpo', 'clientref','collectionref','returnref', 'notes', 'list', 'deliveryaddress', 'collectionaddress', 'paymentstatus'], 'string'],
            [['bay', 'urgency', 'creditno', 'invoiceno', 'jobno'], 'integer'],
            [['created_at', 'updated_at', 'deleted_at', 'items', 'fulladdresses'], 'safe'],
            [['collectiondate'], 'safe'],
            [['service'], 'safe'],
            [['return_date'], 'safe'],
            [['return_transportmethod'], 'string'],
            [['addons'], 'safe'],
            [['clientid'], 'string'],
            [['imported','unknownclientname', 'agent'], 'boolean'],
            [['email'], 'email'],
            //[['department'],'required'],
            [['invoicedin'], 'default', 'value' => 'Cin7'],
            [['starttime', 'finishtime', 'duetime', 'arrived', 'returned', 'attendees', 'products', 'clients'], 'safe'],
            [['assetid', 'engineer', 'department', 'relatedid', 'agentid'], 'default', 'value' => null],
            ['id', 'default', 'value' => self::Tempid()],
            ['clientid', 'default', 'value' => null],
            ['jobno', 'default', 'value' => function() {
                return self::find()->select('jobno')->orderby(['jobno' => SORT_DESC])->one()['jobno'] + 1;
            }],

        ];
    }

    public function validateArray($attribute, $params)
    {
        if (!in_array(true, $this->$attribute)) {
            $this->addError($attribute, 'At least one Option must be selected.');
        }
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => yii::t('app', 'ID'),
            'relatedid' => yii::t('app', 'Client'),
            'type' => yii::t('app', 'Type'),
            'status' => yii::t('app', 'Status'),
            'starttime' => yii::t('app', 'Start'),
            'finishtime' => yii::t('app', 'Finish'),
            'duetime' => yii::t('app', 'Due'),
            'department' => yii::t('app', 'Department'),
            'title' => yii::t('app', 'Title'),
            'description' => yii::t('app', 'Description'),
            'location' => yii::t('app', 'Location'),
            'bay' => yii::t('app', 'Bay'),
            'creditno' => yii::t('app', 'Credit Number'),
            'invoiceno' => yii::t('app', 'Invoice Number'),
            'jobno' => yii::t('app', 'Job Number'),
            'agentname' => yii::t('app', 'Agent Name'),
            'agentid' => yii::t('app', 'Agent Id'),
            'clientname' => yii::t('app', 'Client Name'),
            'transportmethod' => yii::t('app', 'Transport Method'),
            'clientpo' => yii::t('app', 'Client Purchase Order Number'),
            'clientref' => yii::t('app', 'Client Reference Number'),
            'collectionref' => yii::t('app', 'Collection Tracking Number'),
            'collectiondate' => yii::t('app', 'Collection Date'),
            'returnref' => yii::t('app', 'Return Tracking Number'),
            'notes' => yii::t('app', 'Notes'),
            'fasttrack' => Yii::t('app', 'Fasttrack'),
            'list' => Yii::t('app', 'List'),
            'collectionaddress' => Yii::t('app', 'Collection Address'),
            'deliveryaddress' => Yii::t('app', 'Return Address'),
            'items' => Yii::t('app', 'Service Items'),
            'paymentstatus' => Yii::t('app', 'Payment Status'),
        ];
    }

    public function getAccount()
    {
        return $this->hasOne(\backend\models\Accountsbe::class, ['id' => 'relatedid']);
    }
    public function getClient()
    {

        if (($result = $this->hasOne(\backend\models\User::class, ['id' => 'clientid']))) {
            return $result;
        } else {
            return $this->hasOne(\backend\models\User::class, ['id' => 'relatedid']);
        }
    }
    public function getAgentl()
    {
        if (strtotime(str_replace('/','-',$this->created_at) < strtotime('2024-09-18'))) {
            return $this->hasOne(\backend\models\User::class, ['id' => 'agentid']);
        } else {
            return $this->hasOne(\backend\models\Accounts::class, ['id' => 'agentid']);
        }
    }
    public function getAgentfullname() {
        if (strtotime(str_replace('/','-',$this->created_at) < strtotime('2024-09-18'))) {
            return !empty($this->agentid)
            ? $this->agentl->adv->firstname.' '.$this->agentl->adv->lastname
            : $this->agentname;
        } else {
            return !empty($this->agentid)
            ? $this->agentl?->name
            : $this->agentname;
        }
    }


    /**
     * GetClientsl function
     *
     * @return user account array;
     */
    public function getClientsl()
    {
        return $this->hasMany(
            \backend\models\User::class, 
            [
                'id' => 'relatedid'
            ]
        )
            ->via('lookup');
    }

    public function getClientsladv()
    {
        return $this->hasOne(\common\models\User::class, ['id' => 'id']);
    }

    public function getClientadv()
    {
        return $this->hasOne(\common\models\User::class, ['id' => 'relatedid']);
    }
    public function getEmailQueue()
    {
        return $this->hasMany(\backend\models\Mailqueue::class, ['relatedid' => 'id']);
    }

    public function getAgentadv()
    {
        return $this->hasOne(\common\models\User::class, ['id' => 'agentid']);
    }
    public function getDepartmentl()
    {
        return $this->hasOne(\backend\models\Attributesvalues::class, ['id' => 'department']);
    }
    public function getEmployeel()
    {
        return $this->hasOne(\common\models\User::class, ['id' => 'engineer']);
    }
    public function getAsset()
    {
        return $this->hasOne(\backend\models\Assetsbe::class, ['id' => 'assetid'])
        //->where(['relatedto' => 'Asset'])
        ;

    }
    public function getAttendeesl()
    {
        return $this->hasMany(\backend\models\User::class, ['id' => 'relatedid'])
            ->via('lookup');
    }
    public function getProductsl()
    {
        return $this->hasMany(\backend\models\Productsbe::class, ['id' => 'relatedid'])
            ->via('lookup');
    }




    public function getSurvies()
    {
        return $this->hasMany(\backend\models\Surveybe::class, ['id' => 'relatedid'])
            ->via('lookup')
        //->onCondition(['related' => 'Activity'])
        ;

    }
    public function getAllactivitiesitems()
    {
        return $this->hasMany(Activitiesitemsbe::class, ['relatedid' => 'id']);
    }
    public function getActivitiesitems()
    {
        $tempid = Yii::$app->session->get('acttempid');
        if (Yii::$app->controller->action->id !== 'create' || Yii::$app->controller->id !== 'activities') {
            return $this->hasMany(Activitiesitemsbe::class, ['relatedid' => 'id'])
                ->onCondition(['in', 'activities_items.status', Activitiesitemsbe::STATUS]);
        } elseif (Yii::$app->controller->id == 'activities' && Yii::$app->controller->action->id == 'create') {
            return Activitiesitemsbe::find()
                ->where(['relatedid' => "$tempid"])
                ->onCondition(['in', 'activities_items.status', Activitiesitemsbe::STATUS])
                ->orderby(['activities_items.created_at' => SORT_ASC])
                ->all();
        }
    }



    
    public function beforeSave($insert)
    {
        $this->collectiondate = $this->collectiondate && !is_int($this->collectiondate) ? strtotime(str_replace('/', '-', $this->collectiondate)) : $this->collectiondate;
        $this->starttime = isset($this->starttime) && !is_int($this->starttime) ? strtotime(str_replace('/', '-', $this->starttime)) : $this->starttime;
        $this->finishtime = isset($this->finishtime) && !is_int($this->finishtime) ? strtotime(str_replace('/', '-', $this->finishtime)) : $this->finishtime;
        $this->duetime = isset($this->duetime) && !is_int($this->duetime) ? strtotime(str_replace('/', '-', $this->duetime)) : $this->duetime;
        $this->arrived = isset($this->arrived) && !is_int($this->arrived) ? strtotime(str_replace('/', '-', $this->arrived)) : $this->arrived;
        $this->returned = isset($this->returned) && !is_int($this->returned) ? strtotime(str_replace('/', '-', $this->returned)) : $this->returned;
        $this->status = isset($this->returned) && $this->returned > 1 ? 'Complete' : $this->status;
        $this->fasttrack = (isset($this->type) && $this->type == 'Fasttrack Service') ? true : false; 
        
        if (!empty($this->clientid)) {
            $this->clientname = empty($this->clientname) ?  $this->client?->fullname : $this->clientname;
            $this->email = empty($this->email) ? $this->client?->email : $this->email;
        }
            
        $this->agentname = $this->agentid !== null ? $this->agentfullname : null;
        $this->list = $this->buildList($this->activitiesitems);
        if (array_key_exists('Address', Yii::$app->request->post())) {
            $this->processAddresses(Yii::$app->request->post('Address'));
        } else {
            $this->processAddresses();
        }
        
        
        return parent::beforeSave($insert);
    }

    public function processAddresses(array $addresses = []) {
        if (is_object($this->fulladdresses)) {
            $this->fulladdresses = json_decode($this->fulladdresses, 1);
        }
        if ($addresses) {
            foreach ($this->fulladdresses as $type => $address) {
                $address->attributes = ($addresses[$type]);
                if ($address->id === 'new' && $address->saveaddress == true) {
                    $naddress = \backend\models\Addressbe()->findOne(['address1' => $address1, 'postcode' => [$address->postcode, str_replace(' ', '', $address->postcode)], 'relatedid' => $this->clientid]);
                    if (!$naddress) {
                        $naddress = new \backend\models\Addressbe();
                        $naddress->attributes = $address->attributes;
                        $aid = $naddress->id = \backend\models\Addressbe::Tempid();
                        $naddress->relatedid = $this->clientid;
                        $naddress->save();
                        $address->id = $aid;
                    } else {
                        $address->id = $naddress->id;
                        $address->loadAddress($address->id);
                    }
                } else {
                    $address->loadAddress($address->id);
                }
            }
        }
        $this->fulladdresses = is_array($this->fulladdresses) || \is_object($this->fulladdresses) ? json::encode($this->fulladdresses) : $this->fulladdresses; 
    }

    public function buildList($activitiesitems) {
        $counts = $this->counts;
        $out = '';
        
        $counts['bike'] > 0 ? $out .= $counts['bike'] .' - '. Html::tag('span', '', ['class' => 'fa fa-bike serviceadd text-dark', 'data-value' => 'lifejacket']). '<br/>' : null;
        $counts['lifejacket'] > 0 ? $out .= $counts['lifejacket'] .' - '. Html::tag('span', '<svg class="icon icon-MSCLife-jacket"><use xlink:href="/NGauge/css/symbol-defs.svg#icon-MSCLife-jacket"></use></svg>', ['class' => 'serviceadd text-dark', 'data-value' => 'lifejacket']). '<br/>' : null;
        $counts['liferaft'] > 0 ? $out .=  $counts['liferaft'] .' - '.Html::tag('span', '<svg class="icon icon-MSCLife-raft"><use xlink:href="/NGauge/css/symbol-defs.svg#icon-MSCLife-raft"></use></svg>', ['class' => 'serviceadd text-dark', 'data-value' => 'liferaft' ]).'<br/>' : null;
        $counts['lifeboat'] > 0 ? $out .= $counts['lifeboat'] .' - '.Html::tag('span','', ['class' => 'fa fa-ship serviceadd text-dark', 'data-value' => 'lifeboat']). '<br/>' : null;
        $count = $counts['bike'] + $counts['lifejacket']+ $counts['liferaft'] + $counts['lifeboat'];
        return $count > 0 ? '<p> '.\yii\helpers\Html::tag('span', '', ['class' => 'fa fa-plus expand', 'data-id' => $this->id]) . ' - ' . $count . ' </p> ' . $out : '';
    }

    public function getCounts() {
        $activitiesitems = $this->activitiesitems;
        $count = count($activitiesitems);
		$counts = [
            'bike' => 0,
            'lifejacket' => 0,
            'lifejacketbulk' => 0,
            'liferaft' => 0,
            'lifeboat' => 0,
        ];
        if (is_array($activitiesitems) == true && $count > 0)  {
            foreach ($activitiesitems as $actitem) {
                if (isset($counts[$actitem->type])) {
                    $counts[$actitem->type]++;
                }
            }
        }

        return $counts;
    }

    public function afterSave($insert, $changed)
    {
        $actitems = $this->activitiesitems;
        foreach ($actitems as $key => $actitem) {
            if (($servicesheet = $actitem->servicesheet)) {
                if (isset($servicesheet->subforms)) {
                    $subforms = $servicesheet->subforms;
                    foreach ($subforms as $key => $subform) {
                        if (isset($changed['status']) && $this->status == 'Complete') {
                            $subform->status = 'Complete';
                        }
                        $subforms[$key] = $subform;
                    }
                    $servicesheet->subforms = $subforms;
                }
                if (array_key_exists('invoiceno', $changed)) {
                    $servicesheet->invoiceno = $this->invoiceno;
                }
                if (isset($changed['status']) && $this->status == 'Complete') {
                    $servicesheet->status = 'Complete';
                }
                $servicesheet->save();
                
            }
            if (isset($changed['status']) && $this->status == 'Complete') {
                $actitem->updateAttributes(['status' => 'Complete']);
            }
            if (isset($changed['status']) && $changed['status'] == 'Service in Progress') {
                $actitem->updateAttributes(['status' => 'Service in Progress']);
            }
        }
        $path = Yii::getAlias('@documents').'/'.$this->jobno.'/';
        !file_exists($path) ? \yii\helpers\FileHelper::createDirectory($path) : false;
        
        self::SendUpdateMail();
        return parent::afterSave($insert, $changed);
    }

    public function __construct($attributes = [], $config = [])
    {
        parent::__construct($attributes, $config);
        $this->loadJson();
    }

    public function loadJson() {
        
        $data = is_array($this->fulladdresses) == false ? json::decode($this->fulladdresses, 1) : $this->fulladdresses;
        if (is_array($data) == true) {
            $addresses = [];
            foreach ($data as $key => $address) {
                $fulladdresses = new Address(['type' => $address['type']]);
                $fulladdresses->attributes = $address;
                $addresses[$address['type']] = $fulladdresses;
            } 
            $this->fulladdresses = $addresses;
        } else {
            $this->fulladdresses = [
                'billing' => new Address(['type' => 'billing']),
                'collection' => new Address(['type' => 'collection']), 
                'return' => new Address(['type' => 'return']),
            ];
        }
    }

    public function afterFind()
    {
        if (yii::$app->controller->id == 'Activities' && yii::$app->controller->action->id == 'update') {
            $this->clients = $this->clientsl;
        }
        $this->loadJson();
                
        $this->collectiondate = $this->collectiondate > 1 && is_int($this->collectiondate) ? date('d/m/Y', $this->collectiondate) : null;
        $this->arrived = isset($this->arrived) && is_int($this->arrived) ? date('d/m/Y', $this->arrived) : null;
        $this->returned = isset($this->returned) && is_int($this->returned) ? date('d/m/Y', $this->returned) : null;
        $this->duetime = isset($this->duetime) && $this->duetime > 0 ? date('d/m/Y', $this->duetime) : null;
        
        if (!in_array(yii::$app->controller->action->id, ['additem', 'update', 'create', 'updateagents', 'updatefield', 'delete', 'saveallacts', 'serviceupdate', 'arrived', 'addtoservice', 'remduplicates'])) {
            $urgency = \backend\models\Attributesvalues::formarraytt('urgency');
            !empty($this->urgency) && array_key_exists($this->urgency, $urgency) ? $this->urgency = $urgency[$this->urgency] : false;
        }
        return parent::afterFind();
    }

    public function SendUpdateMail() {
        $subject = match (true) {
            $this->type == 'Service' && $this->status == 'Booked' && $this->transportmethod == 'Seago Van' => 'Collection Arranged',
            $this->type == 'Service' && $this->status == 'Booked' && in_array($this->transportmethod, ['TNT', 'DX Freight']) => 'Collection Arranged',
            $this->type == 'Service' && $this->status == 'Arrived' && in_array($this->transportmethod, ['TNT', 'DX Freight','Seago Van']) => 'Equipment Arrived',
            $this->type == 'Service' && $this->status == 'Return Booked' && in_array($this->return_transportmethod, ['TNT', 'DX Freight']) => 'Return Booked',
            $this->type == 'Service' && $this->status == 'Return Booked' && $this->return_transportmethod == 'Seago Van' => 'Return Booked',
            $this->type == 'Service' && $this->status == 'Service in Progress' => 'Service Started',
            $this->type == 'Service' && $this->status == 'Finished' && $this->paymentstatus == 'paid' => 'Payment Received',
            $this->type == 'Service' && $this->status == 'Complete' && $this->paymentstatus == 'paid' => 'Service Completed',
            default => null,
        };
       // yii::warning([$subject, $this->type, $this->status,$this->paymentstatus, $this->return_transportmethod]);
        $sendMail = !empty($subject) && Mailqueue::find()->where(['subject' => $subject, 'to_email' => $this->email, 'relatedid' => $this->id, 'status' => 'Active'])->exists() == false 
            ? Mailqueue::SendMail($subject, $this->id, $this->id, 'en', $this->email, null, null, true, 'queue') : false;
        $sendMail !== false ? Yii::$app->session->addFlash('success', 'Email '.$subject.' sent to: '.$this->email) : false;
        return false;
    }

    public function checkandcreate() {
        $counts = $this->counts;
        $items = $this->activitiesitems;
        $bulk = [];
        foreach ($items as $key => $actitem) {
            $id = $actitem->id;
            $type = $actitem->type;
            if (!($servicesheet = $actitem->servicesheet) && Yii::$app->request->isPost) {
                if ($type == 'liferaft' || $counts['lifejacket'] == 1) {
                    if ($type == 'liferaft') {
                        \modules\forms\models\sub\ServiceLifeRaft::createServicesheet($actitem);
                    }elseif ($type == 'lifejacket') {
                        \modules\forms\models\sub\ServiceLifeJacket::createServicesheet($actitem);
                    }
                } elseif ($type !== 'liferaft' || $counts['lifejacket'] > 1) {
                    $bulk[$actitem->id] = [
                        'actid' => $actitem->id,
                        'relatedid' => $actitem->relatedid,
                        'serial' => $actitem->serial,
                        'productid' => $actitem->product,
                        'assetid' => $actitem->assetid,
                    ];
                }
            }
        }
        if (count($bulk) > 0 ) {
            foreach ($items as $key => $actitem) {
                $actitem->type == 'lifejacket' ? $actitem->updateAttributes(['type' => 'lifejacketbulk']) : false;
            }
            \modules\forms\models\sub\ServiceLifeJacketBulk::checkandcreate($this->id, $bulk);    

        }
    }

    public function delete() {
        foreach ($this->allactivitiesitems as $key => $actitem) {
            $actitem->locationid = null;
            $actitem->status = 'Deleted';
            $actitem->delete();
        
            $sb = Servicebaysbe::find()->where(['relatedid' => $actitem->id])->one();
            if ($sb) {
                $sb->occupied = false;
                $sb->relatedid = null;
                $sb->save();   
                if (yii::$app->cache->exists('site_rack')) {
                    yii::$app->cache->delete('site_rack');
                }
            }
        }
        parent::delete();
        $this->status = 'Deleted';
        return $this->save();
    }
}


