<?php
/**
 *
 */

namespace modules\activities\controllers;

use modules\activities\models\{Activities, Activitiesitemsbe, Activitiessearch};
use modules\custom\models\{Assetsbesearch};
use backend\models\{Servicebaysbe, Mailqueue,Pagegroupbe, User, Signupform, Lookuptablebe, Attributesvalues, Assetsbe, Departmentsbe};
use common\models\Base;
use yii\helpers\{Arrayhelper, FileHelper, Json};
use Yii;
use yii\filters\VerbFilter;
use yii\web\{Controller, NotFoundHttpException};

/**
 * ActivitiesController implements the CRUD actions for Activities model.
 */
class DefaultController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Activities models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new Activitiessearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionCompleted()
    {
        $searchModel = new Activitiessearch();
        $dataProvider = $searchModel->completedsearch(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionMy()
    {
        $searchModel = new Activitiessearch();
        $searchModel->engineer = Yii::$app->user->identity->id;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionTasklist()
    {
        $searchModel = new Activitiessearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionUrgent()
    {
        $searchModel = new Activitiessearch();
        $searchModel->engineer = Yii::$app->user->identity->id;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->renderPartial('Sindex', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionToday()
    {
        $searchModel = new Activitiessearch();
        $dataProvider = $searchModel->myduetodaysearch(Yii::$app->request->queryParams);

        return $this->renderPartial('Sindex', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Activitiesitems function
     * Enables Kartik + to the left of the grid
     * @link /activities/index
     * @return void
     */
    public function actionActivitiesitems()
    { 
        $id = yii::$app->request->get('id');
        $language = yii::$app->request->get('language');
        $language = ($language == "NGauge" || $language == "") ? "en_gb" : $language;

        $items = Activitiesitemsbe::find()
        ->where(['or', ['is', 'status', null], ['!=', 'status', 'Deleted']])
        ->andWhere(['relatedid' => $id])
        ->all(); 
        return $this->renderAjax('items', ['items' => $items, 'activity_id' => $id, 'language'=>$language]);
    }

    /**
     * actionAjaxitemdata function
     * Enables edit icon of the grid
     * @link /activities/items_update_form
     * @return modal content
     */
    public function actionAjaxitemdata(){

       $id = yii::$app->request->post('id'); 
       $activity_id = yii::$app->request->post('activity_id'); 
       $language = yii::$app->request->post('language'); 

       $item = Activitiesitemsbe::find()
        ->where(['id' => $id])
        ->one(); 

       return $this->renderAjax('items_update_form', ['model' => $item, 'activity_id' => $activity_id, 'language' => $language]);
    }

    /**
     * actionAjaxsaveitemdata function
     * Enables update from modal
     * @return json
     */
    public function actionAjaxsaveitemdata(){
        
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
       
       $id = yii::$app->request->post('id');
       $locationid = yii::$app->request->post('locationid');
       $status = yii::$app->request->post('status');

        $item = Activitiesitemsbe::find()->where(['id' => $id])->one();

        if($locationid)
            $item->locationid = $locationid;

        if($status)
            $item->status = $status;

        if($item->save(false))
            return ['success' => true, 'message' => 'Data updated successfully.'];
        else
            return ['success' => false, 'message' => 'Something went wrong!! Please try again.'];

    }

    /**
     * Shorter Activitiesitems function
     * Enables Kartik + to the left of the grid
     * @link /
     * @return void
     */
    public function actionHomeactivitiesitems()
    {
        $id = yii::$app->request->post('expandRowKey');
        $items = Activitiesitemsbe::find()->where(['relatedid' => $id])->all();
        return $this->renderAjax('homeitems', ['items' => $items]);
    }

    public function actionArrived($id){
        
        $data = json_decode(base64_decode($id), 1);
        if ($data) {
            $dataid = $data['id'];
        } else {
            $dataid = $id;
        }
        
        $model = Activities::find()->where(['id' => $dataid])->one();
        if(!$model){
            $modela = Activitiesitemsbe::find()->where(['id' => $dataid])->one();
            $model = $modela?->activity;
        }
        $actitems = Activitiesitemsbe::find()->where(['relatedid' => $model->id])->andWhere(['or', ['is', 'status', null], ['not', ['status' => 'Deleted']]])->indexby('id')->all();
        if(yii\base\Model::loadMultiple($actitems, yii::$app->request->post()) && yii\base\Model::ValidateMultiple($actitems)){
            $arrived = 0;
            foreach($actitems as $key => $item){
                if($item->arrived == true){
                    $item->status = 'Arrived';
                    $arrived++;
                }
                $item->save(false);
            }
            if(count($actitems) > $arrived){
                Mailqueue::SendMail('Missing Items', $model->id, $model->id, 'en', 'sales@seagogroup.com', null, null, null, 'queue');
                Yii::$app->session->addFlash('warning', 'Missing Items, Email Sent to Admin');
                $model->status = 'Arrived Partial';
            } elseif(count($actitems) == $arrived){
                $model->status = 'Arrived';
                $model->arrived = Date('d/m/Y');
                Yii::$app->session->addFlash('success', 'Arrived successfully');
            }
            $model->save();
            return $this->redirect(['warehouse']);
        } else {
            return $this->render('arrived', ['model' => $model, 'actitems' => $actitems]);
        }
    }

    public function actionServiceupdate($id)
    {
        $data = json_decode(base64_decode($id), 1);
        if ($data) {
            $id = $data['id'];
            $model = Activitiesitemsbe::find()->where(['id' => $id])->one();
			if(!$model){
                $act = $model = Activities::find()->where(['id' => $id])->one();
            } else {
                $act = $model->activity;
            }
            $bays = ArrayHelper::map(Servicebaysbe::find()->where(['or', ['id' => $model->locationid], ['is', 'occupied', null], ['!=', 'occupied', 1]])->orderby('sequence')->all(), 'id', 'name', 'location');
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->relatedid]);
            } elseif ($model->load(Yii::$app->request->post()) && !$model->save()) {
                return print_r($model->errors);
            } else {
                switch (yii::$app->request->get('value')) {
                    case 'update': return $this->render('serviceupdate', ['model' => $model, 'bays' => $bays]);
                        break;
                    case 'service':
                        if ($model->type == 'liferaft') {
                            return $this->redirect(['/forms/update', 'id' => $model->servicesheet->id, 'language' => 'en', 'type' => 'ServiceLifeRaft']);
                        } elseif ($model->type == 'lifejacket') {
                            return $this->redirect(['/forms/update', 'id' => $model->servicesheet->id, 'language' => 'en', 'type' => 'ServiceLifeJacket']);
                        }
                        return $this->render('serviceupdate', ['model' => $model, 'bays' => $bays]);
                        break;
                    case 'arrive':
                        $model->updateAttributes(['status' => 'Arrived']);
                        $act->status = $message = 'Arrived';
                        $act->arrived = date('d/m/Y H:i');
                        if ($model->save()) {
                            return $this->redirect(['/activities/serviceindex', 'message' => $message]);
                        }
                        break;
                    case 'depart':
                        $model->status = $message = 'Complete & Returned';
                        if ($model->save()) {
                            return $this->redirect(['/activities/serviceindex', 'message' => $message]);
                        }
                        break;
                }
            }
        } else {
            $message = 'Error with QR Code';
            return $this->redirect(['/activities/serviceindex', 'message' => $message]);

        }
    }
    public function actionServiceindex($message = null)
    {
        return $this->render('qrscanner', ['message' => $message]);
    }
    public function actionWarehouse($message = null)
    {
        return $this->render('preqrscanner', ['message' => $message]);
    }

    public function actionClient($client)
    {
        $searchModel = new Activitiessearch();
        $dataProvider = $searchModel->searchall(
            $client,
            Yii::$app->request->queryParams
        );

        return $this->renderPartial(
            'index',
            [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,

            ]
        );
    }
    /**
     * Displays a single Activities model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
    public function actionLabel($id)
    {
        //$item = Activitiesitemsbe::findOne($id);
        $model = $this->findModel($id);
        return $this->render('label', ['model' => $model/*, 'item' => $item*/]);
    }
    public function actionLabels($id)
    {

        return $this->render('labels', ['model' => $this->findModel($id)]);

    }

    public function actionLabelpdf($id)
    {

        $snappy = new \Knp\Snappy\Pdf('"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf"');
        $snappy->setOption('orientation', 'portrait');
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="file.pdf"');
        $url = Yii::$app->request->hostInfo . "/NGauge/activities/labels?id=$id";
        echo $snappy->getOutput($url);
    }

    /**
     * Creates a new Activities model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionNew()
    {
        $signup = new Signupform();
        $model = new Activities();
        $model->id = Base::Tempid();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['update', 'id' => $model->id]);
        } elseif ($model->load(Yii::$app->request->post()) && !$model->save()) {
            return print_r($model->errors);
        } else {
            return $this->render('create', [
                'model' => $model,
                'signup' => $signup,
                'actitems' => null,
                'serviceitems' => null,
                'userassetProvider' => null,
            ]);
        }
    }
    /**
     * Creates a new Activities model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $signup = new Signupform();
        $model = new Activities();
        $model->id = Base::Tempid();
        $actitems = [new Activitiesitemsbe([
            'id' => Base::Tempid(),
            'relatedid' => $model->id,
        ])];
        
        $serviceitems = new Assetsbesearch();
        $userassetProvider = $serviceitems->clientsearch(Yii::$app->request->queryParams);
        $serviceitems = [];

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $actitems = Activitiesitemsbe::find()
                ->where(['relatedid' => $model->id])
                ->indexby(['id'])
                ->all();
            if (\yii\base\model::loadMultiple($actitems, yii::$app->request->post())) {
                foreach ($actitems as $key => $item) {
                    $item->save();
                }
            } else {
                if(in_array('Activitiesitemsbe', Yii::$app->request->post())){
                    foreach (Yii::$app->request->post('Activitiesitemsbe') as $id => $item) {
                        $actitem = new Activitiesitemsbe([
                            'id' => Base::Tempid(),
                            'relatedid' => $model->id,
                        ]);
                        foreach($item as $field => $value){
                            $actitem->$field = $value;
                        }
                        $actitem->save();
                    }
                }
            }
            return $this->redirect(['update', 'id' => $model->id]);

        } elseif ($model->load(Yii::$app->request->post()) && !$model->save()) {
            return print_r($model->errors);
        } else {
            return $this->render('create', [
                'model' => $model,
                'signup' => $signup,
                'actitems' => $actitems,
                'serviceitems' => $serviceitems,
                'userassetProvider' => $userassetProvider,
                
            ]);
        }
    }
    /**
     * Creates a new Activities model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreatetraining()
    {

        $model = new Activities();
        $tempid = Yii::$app->session->get('actid');
        if (!$tempid) {
            Yii::$app->session->set('actid', Base::Tempid());
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model = activities::find()->where(['created_at' => $model->created_at, 'created_by' => $model->created_by])->one();
            $linked = Lookuptablebe::find()->where(['sourceid' => Yii::$app->session->get('actid')])->all();
            foreach ($linked as $a => $link) {
                $link->sourceid = $model->id;
                $link->save();
            }
            Yii::$app->session->remove('actid');

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('createtraining', [
                'model' => $model,
            ]);
        }
    }
    public function actionMissingQr()
    {
        $models = Activitiesitemsbe::find()->where(['qrimage' => ''])->orWhere(['is', 'qrimage', null])->all();
        foreach ($models as $key => $amend) {
            $amend->qrimage = Base::Qr(base64_encode(json_encode(['type' => 'Activity', 'id' => $amend->id])));
            $amend->save();
        }
    }
    public function actionAdditem()
    {
        $sourceid = Yii::$app->request->post('id');
        $qty = Yii::$app->request->post('qty') !== null ? Yii::$app->request->post('qty') : 1;
        $x = 1;
        $result = [];
        while($x <= $qty){        
            $r1 = new Activitiesitemsbe(['id'=> Activitiesitemsbe::tempid()]);
            $r1->relatedid = $sourceid;
            $r1->type = yii::$app->request->post('type');
            if ($r1->save()) {
                $result['saves'][] = ['message' => 'Created'];
            } else {
                $result['errors'][] = ['message' => $r1->errors];
            }
            $x++;
        }
        $model = Activities::findONe($sourceid);
        $model->checkandcreate();
        $model->refresh();
        Yii::$app->response->format = 'json';
        $actitems = Activitiesitemsbe::find()
            ->where(['relatedid' => $sourceid, 'status' => Activitiesitemsbe::STATUS])
            ->all();
        $form = \yii\widgets\ActiveForm::begin();
        return $this->renderAjax('activitiesitems', ['model' => $model ? $model : new Activities(['id' => $sourceid]), 'actitems' => $actitems, 'form' => $form]);
        //return isset($result['errors']) && count($result['errors']) > 0  ? $result['errors'] : $result['saves'];
    }
    public function actionDelitem()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $sourceid = Yii::$app->request->post('id');
        $r1 = Activitiesitemsbe::find()->where(['id' => $sourceid])->one();
        if ($r1->delete()) {
            return ['result' => 200, 'message' => 'Deleted'];
        } else {
            return ['result' => 100, 'message' => $r1->errors];
        }
    }

    public function actionAddClient()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $model = new Signupform();
        if ($model->load(Yii::$app->request->post()) && $model->signup()) {
            $id = $model->modelid;
            $model = User::find()->where(['email' => $model->email])->one();
            return ['result' => 200, 'message' => 'User Created', 'data' => ['id' => $model->id, 'fullname' => $model->fullname]];
        } else {
            return ['result' => 100, 'message' => $model];

        }
    }
    public function actionAddAgent()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $model = new Signupform();
        if ($model->load(Yii::$app->request->post()) && $model->signup()) {
            $id = $model->modelid;
            $model = User::find()->where(['email' => $model->email])->one();
            if ($model) {
                $group = new Lookuptablebe();
                $group->sourceid = $model->id;
                $group->source = 'User';
                $group->relatedid = 'B6A89CD0-93F8-4359-8C74-A60C23724167';
                $group->related = 'usergroup';
                return $group->save() ? ['result' => 200, 'message' => 'User Created'] : false;
            } else {
                return ['result' => 100, 'message' => $model->errors];
            }
        } else {
            return ['result' => 100, 'message' => $model->errors];

        }
    }
    public function actionCheckserial()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $serial = Assetsbe::findbySerial(Yii::$app->request->post('serial'));
        if (!$serial) {
            return ['result' => 100, 'message' => 'No Matching Serial'];
        } else {
            return ['result' => 200, 'message' => 'Serial Matched', 'data' => $serial, 'name' => $serial->product->product_name];
        }

    }
    public function actionViewp($id)
    {
        $model = $this->findModel($id);
        $contents = Pagegroupbe::find()->where(['url' => 'jobconfirmationfile'])->one();
        return $this->renderPartial('jobconfirmation', [
            'model' => $model,
            'contents' => $contents,
        ]);
    }

    public function actionPdf($id)
    {
        Yii::$app->response->sendContentAsFile(Base::GeneratePdf($id, 'string',  "/NGauge/activities/viewp?id=$id", $id.'.pdf'), 'File.pdf', ['mimeType' => 'application/pdf', 'inline' => 'false'])->send();
    }

    public function actionEmailconfirmation($id)
    {
        $mail = new Mailqueue();
        $model = $this->findModel($id);
        if ($model) {
            $mail->to_email = $model->clientsl[0]['email'];
            $mail->subject = 'Job Confirmation';
            $mail->message = $this->actionViewp($id);
            $mail->save();
        }
        return $this->redirect(yii::$app->request->referrer);
    }

    public function actionRunqr()
    {
        $data = json_encode(['Type' => 'Bike', 'orderno' => 123, 'productno' => 'ac-165-nm', 'serial' => 123456, 'dom' => '2019-01-12', 'extra' => ['batterysn' => 9876, 'origin' => 'eastbourne']]);
        return \yii\helpers\Html::img(Base::Qr($data), ['height' => '100px', 'width' => '100px']);
    }


    public function actionServicingtimeline()
    {
        return $this->render('timeline');
    }
    /**
     * Timeline function
     *
     * @return mixed timeline page
     */
    public function actionTimeline()
    {
        return $this->render('timeline');
    }

    /**
     * Updates an existing Activities model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */

    public function actionGridupdate()
    {
        $models = Activities::find()->where(['id' => Yii::$app->request->post('id')])->indexBy('id')->all(); // your model can be loaded here
        // Check if there is an Editable ajax request
        if (isset($_POST['hasEditable'])) {
            // use Yii's response format to encode output as JSON
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            // read your posted model attributes
            if (Yii\base\Model::loadMultiple($models, yii::$app->request->post())) {
                foreach ($models as $key => $mod) {
                    $mod->scenario = 'grid_update';
                    $var = yii::$app->request->post('editableAttribute');
                    $value = $mod->$var;
                    if ($mod->save()) {
                        // return JSON encoded output in the below format
                        return ['output' => $value, 'message' => ''];
                    } else {
                        // return JSON encoded output in the below format
                        // validation error
                        return ['output' => '', 'message' => $mod->errors];
                    }
                }
                // read or convert your posted information

            }
            // else if nothing to do always return an empty JSON encoded output
            else {
                return ['output' => '', 'message' => ''];
            }
        }

        // Else return to rendering a normal view
        return $this->render('view', ['model' => $model]);
        //}

        /*$id= yii::$app->request->post('id');
    $value = yii::$app->request->post('value');
    $field = yii::$app->request->post('attribute');
    $model = Activities::find()->where(['id' => $id])->one();
    $model->$field = $value;
    if ($model->save()) {
    return json_encode(['result' => 200, 'message' => 'Saved']);
    } else {
    return json_encode(['result' => 100, 'message' => $model->errors]);

    }*/
    }

    /**
     * Update function
     *
     * @param [unique] $id
     *
     * @return mixed view / update screen
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $actitems = Activitiesitemsbe::find()
            ->where(['relatedid' => $model->id, 'status' => Activitiesitemsbe::STATUS])
            ->indexby(['id'])
            ->all();

        $serviceitemsSearch = new Assetsbesearch();
        $serviceitemsSearch->clientid = $model->clientid;
        $serviceitemsSearch->existingids = array_column($actitems, 'assetid');
        $userassetProvider = $serviceitemsSearch->clientsearch(Yii::$app->request->queryParams);
            
        $serviceitems = [];
        foreach($userassetProvider->models as $key => $asset){
            ($item = new Activitiesitemsbe([
                'id' => Activitiesitemsbe::Tempid(),
                'relatedid' => $model->id,
                'assetid' => $asset->id,
                'serial' => $asset->serialnumber,
                'product' => $asset->productid,
                'type' => $asset->assettype,
                'status' => 'Quote Needed',
                ]));
            $serviceitems[$item->assetid] = $item;
        }
        if ($model->load(Yii::$app->request->post())  && $model->save()) {
            $actitems = Activitiesitemsbe::find()
            ->where(['relatedid' => $model->id])
            ->indexby(['id'])
            ->all();
            if (\yii\base\Model::loadMultiple($actitems, yii::$app->request->post())) {
                foreach ($actitems as $key => $item) {
                    ($model->status == 'Complete' || $model->status == 'Finished') && $item->status !== 'Deleted' ? $item->status = $model->status : false;
                    if($model->status == 'Complete'){
                        $item->status = 'Complete';
                        $item->locationid = null;
                    }
                    $item->save();
                }
            }
            $model->checkandcreate();

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render(
                'update',
                [
                    'model' => $model,
                    'actitems' => $actitems,
                    'serviceitems' => $serviceitems,
                    'userassetProvider' => $userassetProvider,
                ]
            );
        }
    }

    public function actionServiceableitems(string $id, string  $userid = null){
        if(Yii::$app->request->isAjax == true){
            $model = new Activities(['id' => $id]);
            $serviceitemsSearch = new Assetsbesearch();
            $serviceitemsSearch->clientid = $model->clientid;
            $userassetProvider = $serviceitemsSearch->clientsearch(Yii::$app->request->queryParams);
            $serviceitems = [];
            foreach($userassetProvider->models as $key => $asset){
				($item = new Activitiesitemsbe([
					'id' => Activitiesitemsbe::Tempid(),
					'relatedid' => $model->id,
					'assetid' => $asset->id,
					'serial' => $asset->serialnumber,
					'product' => $asset->productid,
					'type' => $asset->assettype,
					'status' => 'Quote Needed',
					]));
				$serviceites[$item->assetid] = $item;
			}
            return $this->renderAjax(
                'update_serviceable',
                [
                    'serviceitems' => $serviceitems, 
                    'id' => $id,
                    'model' => $model,
                    'userassetProvider' => $userassetProvider,
                ]
            );
        }
    }

    public function actionAddtoservice($id, $userid = null){
        $model = Activities::findOne(['id' => $id]);
        $userid = !empty($userid) ? $userid : $model->clientid; 
        $serviceitemsSearch = new Assetsbesearch();
        $serviceitemsSearch->clientid = $userid;
        $userassetProvider = $serviceitemsSearch->clientsearch(Yii::$app->request->queryParams);
        $serviceitems = [];
        $post = Yii::$app->request->post('Activitiesitemsbe');
        foreach($userassetProvider->models as $key => $asset){
            if(array_key_exists($asset->id, $post)){
                $item = new Activitiesitemsbe([
                    'id' => Activitiesitemsbe::Tempid(),
                    'relatedid' => $model->id,
                    'assetid' => $asset->id,
                    'serial' => $asset->serialnumber,
                    'product' => $asset->productid,
                    'type' => $asset->assettype,
                    'status' => 'Quote Needed',
                ]);
                $item->attributes = $post[$item->assetid];
                if(boolval($item->service) == true){
                    $item->save();
                }
            }
        }
        $model->checkandcreate();
        Yii::$app->response->format = 'json';
        $actitems = Activitiesitemsbe::find()
            ->where(['relatedid' => $id, 'status' => Activitiesitemsbe::STATUS])
            ->all();
        $form = \yii\widgets\ActiveForm::begin();
        return $this->renderAjax('activitiesitems', ['model' => $model, 'actitems' => $actitems, 'form' => $form]);

    }
    /**
     * Deletes an existing Activities model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        if (strpos(Yii::$app->request->referrer, 'view') == false) {
            return $this->redirect(Yii::$app->request->referrer);
        } else {
            return $this->redirect(['index']);
        }
    }

    public function actionGetusers($department = null)
    {
        $output = [];
        $users = User::find()->where(['sys_useradv.type' => 'staff'])->andfilterWhere(['sys_useradv.department' => $department])->joinwith('useradv')->all();
        foreach ($users as $a => $model) {
            $output[] = ['id' => $model->id, 'name' => $model->fullname, 'class' => isset($model->publicattribute) ? $model->publicattribute['colour'] : 'Black'];
        }
        return $this->asJson($output);
    }

    public function actionGetdata($department = null)
    {
        $forwards = strtotime('+6 months');
        $backwards = strtotime('-6 months');
        $output = [];

        $users = Activities::find()
            ->where(['>=', 'duetime', $backwards])
            ->andwhere(['<=', 'duetime', $forwards])
            ->all();
        foreach ($users as $a => $model) {

            $output[] = [
                'id' => $model->id,
                'sectionID' => $model->engineer,
                'name' => $model->title,
                'start' => date('Y-m-d H:i:s', $model->starttime),
                'end' => date('Y-m-d H:i:s', $model->finishtime),
                'classes' => $model->status,

            ];

        }
        return $this->asJson($output);
    }

    public function actionTimelinedata($to, $from)
    {

        $from = date('Y-m-d', strtotime($from));
        $to = date('Y-m-d', strtotime($to));
        \Yii::$app->response->format = 'json';

        $items = Activities::find()
            ->select('activities.id, start AS start_date, finish AS end_date, description AS text, engineer')
            ->andWhere(['between', "start", $from, $to])
            ->asArray()
            ->all();
        return $items;
    }

    public function actionTimelineuserdata()
    {
        $nonusers = ['admin', 'chalvington'];
        \Yii::$app->response->format = 'json';
        $departments = Departmentsbe::find()->all();
        $out = [];
        foreach ($departments as $a => $model) {
            if (isset($model->usersadv)) {
                $user = [];
                foreach ($model->usersadv as $b => $usermod) {
                    $user[] = ['key' => $usermod->userid, 'label' => "$usermod->firstname $usermod->lastname", 'open' => true];
                }
                $out[] = ['key' => $model->id, 'label' => $model->department, 'children' => $user, 'open' => true];
            } else {
                $out[] = ['key' => $model->id, 'label' => $model->department];

            }
        }

        return $out;
    }

    public function actionCitylist($q = null, $id = null)
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!is_null($q)) {
            $query = new Query;
            $query->select('id, name AS text')
                ->from('city')
                ->where(['like', 'name', $q])
                ->limit(20);
            $command = $query->createCommand();
            $data = $command->queryAll();
            $out['results'] = array_values($data);
        } elseif ($id > 0) {
            $out['results'] = ['id' => $id, 'text' => City::find($id)->name];
        }
        return $out;
    }

    public function actionGetclients($q = null, $id = null)
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        $json1 = new \yii\db\Expression("json_unquote(json_extract(`sys_user`.`adv`, '$.firstname'))");
        $json2 = new \yii\db\Expression("json_unquote(json_extract(`sys_user`.`adv`, '$.lastname'))");
        if (!is_null($q)) {
            $data = User::find()
                ->select(['sys_user.id', "concat($json1,' ', $json2, ' - ',sys_user.email ) AS text"])
                ->where(['or', ['like', $json2, $q], ['like', $json1, $q], ['like', 'email', $q]])
                ->asArray()
                ->limit(100)
                ->all();
            $out['results'] = array_values($data);
        } elseif ($id > 0) {
            $out['results'] = ['id' => $id, 'text' => User::find()->where(['id' => $id])->fullname];
        }
        return $out;
    }

    public function actionUpdatefield(){
        yii::$app->response->format = 'json';
        if (yii::$app->request->isAjax && yii::$app->request->Post()) {

            $id = yii::$app->request->post('id');
            $attribute = yii::$app->request->post('attribute');
            $value = yii::$app->request->post('value');

            $model = $this->findModel($id);
            $model->$attribute = $value;
            if($model->save()){
                return ['status' => 100, 'message' => 'Saved'];

            } else {
                return ['status' => 100, 'message' => $model->errors];
            }
        } else {
            return ['status' => 100, 'message' => 'Error'];
        }
    }

    public function actionItemfield(){
        yii::$app->response->format = 'json';
        if (yii::$app->request->isAjax && yii::$app->request->Post()) {

            $id = yii::$app->request->post('id');
            $attribute = yii::$app->request->post('attribute');
            $value = yii::$app->request->post('value');

            $item = Activitiesitemsbe::find()->where(['id' => $id])->one();
            //print_r($item); exit;
            $item->$attribute = $value;
            if($item->save()){
                return ['status' => 100, 'message' => 'Saved'];

            } else {
                return ['status' => 100, 'message' => $model->errors];
            }
        } else {
            return ['status' => 100, 'message' => 'Error'];
        }
    }

    /**
     * Finds the Activities model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Activities the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Activities::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionQuickupdate($id)
    {
        $act = Activitiesitemsbe::find()->where(['id' => $id])->one();
    
        $locationsa = ArrayHelper::map(
            Servicebaysbe::find()
                ->where(
                    [
                        'or', 
                        ['=', 'id', $act->locationid], 
                        ['is', 'occupied', null], 
                        ['!=', 'occupied', 1]
                    ]
                )
                ->andwhere(['in', 'location', ['LR', 'F']])
                ->orderby('sequence')
                ->all(),
                'id', 
                'name', 
                'location'
            );
        $locationsb = ArrayHelper::map(
            Servicebaysbe::find()
            ->andwhere(['not',['in', 'location', ['LR', 'F']]])
            ->orderby('sequence')    
            ->all(),
            'id', 
            'name', 
            'location'
        );
        $locations = array_merge($locationsa, $locationsb);
        arsort($locations);
        $statuss = ArrayHelper::map(Attributesvalues::find()->where(['attributes.name' => 'Status'])->joinwith('att')->all(), 'label', 'label');

        return $this->renderPartial('quickupdate', ['act' => $act, 'statuss' => $statuss, 'locations' => $locations]);
    }


    public function actionUpdateagents(){
        $jobs = activities::find()->where(['not', ['is', 'agentid', null]])->all();
        foreach($jobs as $key => $job){
            $user = User::find()->where(['id' => $job->agentid])->one();
            $job->agentname = isset($job->agentid) && $user ? $user->fullname : $job->agentname;
            echo $job->save() ? 'good' : print_r($job->errors); 
        }
    }

    public function actionSheetstatus(){
        $models = Activities::find()->all();
        foreach($models as $a => $model){
            if($model->activitiesitems){
                foreach($model->activitiesitems as $b => $actitem){
                    $model->status == 'Complete' && $actitem->servicesheet ? $actitem->servicesheet->updateAttributes(['status' => 'Complete']): false;
                }
            }
        
        }

    }
    public function actionUsers(){
        $acts = Activities::find()
            ->select(['activities.id', 'activities.clientname','activities.created_at', 'sys_user.email', 'activities.duetime'])
            ->where(['not', ['is', 'clientname', null]])
            ->andWhere(['is', 'sys_user.id', null])
            ->Joinwith('client')
            ->asArray()
            ->all();
        $out = [];
        foreach($acts as $key => $model){
            $firstname = new \yii\db\expression("json_value(`sys_user`.`adv`, '$.firstname')");
            $lastname = new \yii\db\expression("json_value(`sys_user`.`adv`, '$.laststname')");
            $user = User::find()
                ->where(['between', 'created_at', $model['created_at'] - 600, $model['created_at'] + 600])
                ->andWhere(['or', ['in', $firstname, explode(' ', $model['clientname'])], ['in', $lastname, explode(' ', $model['clientname'])]])
                ->asArray()
                ->one();
            if($user){
                $adv = json_decode($user['adv']);
                $out[$model['id']] = [
                    'clientname' => $model['clientname'],
                    'created_at' => date('d/m/Y H:i', $model['created_at']),
                    'user' => [
                        'id' => $user['id'],
                        'email' => $user['email'],
                        'name' => $adv->firstname. ' '. $adv->lastname,
                    ],
                ];
                $lt = (new lookuptablebe(['sourceid' => $model['id'], 'relatedid' => $user['id'],'source'=> 'Activitiy', 'related' => 'user']))->save();
            } else {
                $out[$model['id']] = [
                    'clientname' => $model['clientname'],
                    'created_at' => date('d/m/Y H:i', $model['created_at']),
                    'user' => null,
                ];
            }
        }
        return print_r($out);
    }

    public function actionFileupload($jobno){
        $tmpfilepath = yii::getAlias('@tmp');
        $filepath = yii::getAlias('@documents')."/".$jobno;
        if (!file_exists($filepath)) {
            FileHelper::createDirectory($filepath);
        }
        $filename = $_FILES['upload']['name'];
        $to = $tmpfilepath.'/'.$filename;
        $response = move_uploaded_file($_FILES['upload']['tmp_name'], $to);
        $pathinfo = pathinfo($to);
        
        $renameto = $filepath . '/' . file_newname($filepath, \common\models\Base::format_uri($pathinfo['filename']) .'.'. $pathinfo['extension']);
        copy($to, $renameto) ?? unlink($to);
        $pathinfo = pathinfo($renameto);
        file_put_contents($filepath.'/'.$pathinfo['filename'].'.json', json_encode([
            'created_at' => date('d/m/Y H:i'),
            'created_by' => Yii::$app->user->identity->id,
            'createdby_name' => Yii::$app->user->identity->fullname,
            'name' => $pathinfo['basename'],
            'type' => mime_content_type($renameto),
            'certno' => null,
            'filepath' => '/'.$jobno.'/'.$pathinfo['basename'],
            'extension' => $pathinfo['extension'],
        ]));
        Yii::$app->response->format = 'json';
        return $response;
    }

    public function actionServiceitems($id, $productid, $assetid = ''){
        $render = yii::$app->request->isAjax ? 'renderAjax' : 'render';
        return $this->$render('_serviceitem', ['id' => $id, 'productid' => $productid, 'assetid' => $assetid]);
        
    }

    public function actionRemduplicates(){

        $acts = Activities::find()
            ->where(['status' => ['ADP Deleted LOW', 'ADP DUP Deleted']]);
        foreach($acts->each() as $key => $model){
            $model->delete();
        }
    }

}
function file_newname($path, $filename){
    if ($pos = strrpos($filename, '.')) {
           $name = substr($filename, 0, $pos);
           $ext = substr($filename, $pos);
    } else {
           $name = $filename;
    }

    $newpath = $path.'/'.$filename;
    $newname = $filename;
    $counter = 2;
    while (file_exists($newpath)) {
           $newname = $name .'_'. $counter . $ext;
           $newpath = $path.'/'.$newname;
           $counter++;
     }

    return $newname;
}