<?php
namespace modules\activities\controllers;

use Yii;
use modules\activities\models\{Activities, Activitiesusers, ActivitiesSearch,};
use modules\forms\models\{Forms, Formssearch};
use modules\custom\models\{Accounts, Contacts};
use modules\users\models\User;
use backend\models\Mailqueue;
use frontend\models\{Audit, Uploads};
use yii\web\{Controller, ForbiddenHttpException, NotFoundHttpException};
use yii\filters\{AccessControl,VerbFilter};
use yii\helpers\{ArrayHelper, Html, Json};

use yii\base\Model;
use Mpdf\Mpdf;
use yii\db\query;
use yii\httpclient\Client;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
 * ActivitiesController implements the CRUD actions for activities model.
 */
class ActivitiesController extends Controller{


	public $weldforms = ['dt179', 'dt122', 'dt123', 'dt125', 'dt126', 'dt128', 'dt129', 'dt130', 'dt142', 'dt192', 'dt197', 'dt198', 'wel233', 'dt203', 'dt204', 'dt205', 'dt213', 'sop023'];
	public $hseqforms = ['dt022', 'dt127', 'dt131', 'dt132', 'dt133', 'dt135', 'dt188', 'dt194',];

     /**
     * Lists all activities models.
     * @return mixed
     */
    public function beforeAction($action) {
		$id = yii::$app->request->get('id');
		return parent::beforeAction($action);
	}
    public function actionIndex() {
        $searchModel = new ActivitiesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
	public function actionTimesheet() {
    		$model = new Activities();
    		$date = Null;
        return $this->render('timesheet', ['model' => $model, 'date' => $date]);
    }
	public function actionTimesheeti() {
    		$model = new Activities();
    		$date = Null;
    		$welder = Null;
        return $this->render('timesheeti', ['model' => $model, 'date' => $date, 'welder' => $welder]);
    }
    /**
     * Displays a single activities model.
     * @param integer $id
     * @return mixed
     */
    public function actionRoutedeviation() {
		$model = new \frontend\models\Routedeviations();
		$model->actid = Yii::$app->getRequest()->getQueryParam('id');

        if ($model->load(Yii::$app->request->post())) {
			IF($model->save()) {
				return json_encode(['result' => 100, 'message' => 'SAVED']);
			} elseif ($model->errors) {
				return json_encode(['result' => 100, 'message' => $model->errors]);
			}
		} else {
				return $this->renderAjax('routedeviation', ['model' => $model]);
		}
	}


	public function actionCompleted() {
        $searchModel = new ActivitiesSearch();
        $searchModel->jobstatus = 'Completed';
  		$dataProvider = $searchModel->completedsearch(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
   /**
     * Displays a single activities model.
     * @param integer $id
     * @return mixed
     */
    public function actionPending() {
        $searchModel = new ActivitiesSearch();
        $searchModel->jobstatus = 'Booked';
  		$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionAttended() {
        $searchModel = new ActivitiesSearch();
        $searchModel->jobstatus = 'Attended';
  		$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionPrebooked() {
        $searchModel = new ActivitiesSearch();
        $searchModel->jobstatus = 'Pre-Booked';
  		$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionViewinvoiced() {
        $searchModel = new ActivitiesSearch();

        $searchModel->jobstatus = 'Completed';
		$searchModel->billingstatus = 'Invoiced';
  		$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionAllabsence() {
        $searchModel = new ActivitiesSearch();
        $AllabsenceDataProvider = $searchModel->Allabsencesearch(Yii::$app->request->queryParams);

        return $this->render('allabsence', [
            'searchModel' => $searchModel,
            'AllabsenceDataProvider' => $AllabsenceDataProvider,
        ]);
    }

    public function actionSiteattended($id) {
		$model = $this->findModel($id);
		$model->SiteAttended();
		if ($model->errors) {
			return print_r($model->errors);
		} elseif (!$model->errors) {
			return $this->redirect(Yii::$app->request->referrer);
		}
	}
	//as above but quiet
	public function actionSiteattendedq($id) {
		$model = $this->findModel($id);
		$model->SiteAttended();
	}
	//as above but quiet and Remote
	public function actionRsiteattendedq($id) {
		$model = $this->findRmodel($id);
		$model->SiteAttended();
	}
	public function actionJobbooked($id) {
		$model = $this->findModel($id);
		$model->jobstatus = 'Booked';
		$model->save();
		return $this->redirect(Yii::$app->request->referrer);
	}
    /**
     * Displays a single activities model.
     * @param integer $id
     * @return mixed
     */

    public function actionView($id) {
    	$model = $this->findModel($id);
		$welders = explode(',', $model->welder);
		if( (is_array($welders) == true && in_array(Yii::$app->user->identity->username, $welders)) || $model->welder == Yii::$app->user->identity->username || Yii::$app->user->identity->inGroup('Global Admins') == true){			
		
			$jobno = $model->jobno;
			$searchModel = new Formssearch();
			$dataProvider = $searchModel->actsearch(Yii::$app->request->queryParams);

			if ($model->load(Yii::$app->request->post()) && $model->save()) {
				return $this->redirect(['view', 'id' => $model->id]);
				} else {
					if ($model->jobstatus == 'Sickness' ||  $model->jobstatus == 'Annual Leave' ||  $model->jobstatus == 'Lodge' ||  $model->jobstatus == 'Rostered Off' ||  $model->jobstatus == 'Training' || $model->jobstatus == 'Not Available') {
						return $this->render('absview', ['model' => $model]);
					} else {
						$uploads = Uploads::find()
							->select([
								'uploads.id',
								'uploads.category',
								'uploads.filename',
								'uploads.title',
								'uploads.type',
								'uploads.revision',
								'uploads.status',
								'uploads.jobno',
								'uploads.actid',
								'uploads.created_at',
								'uploads.updated_at',
							])
						
						->orderby(['uploads.category' => SORT_ASC])
						->leftJoin('lookuptable', 'lookuptable.relatedid = uploads.id AND lookuptable.source = "Activities" AND lookuptable.sourceid = "'.$model->id.'"')
						->where(['lookuptable.sourceid' => $model->id])
						->indexby('uploads.id');
						!Yii::$app->user->identity->ingroup('Global Admins') ? $uploads->andwhere(['category' => 'TEF']) : null;
						$uploadsAll = $uploads->all();
					return $this->render('view', ['model' => $model, 'dataProvider' => $dataProvider, 'uploadsAll' => $uploadsAll]);
				}
			}
		} else {
			throw new ForbiddenHttpException ('Access Denied');
		}
	}
   	public function actionAwasview($id) {
    	$model = $this->findModel($id);

    	$dtpdf = Forms::find()
     		->andwhere(['jobno' => $model->jobno])
     		->andwhere(['form' => 'dtwas'])
     		->andwhere(['not', ['status' => 'Deleted']])
     		->all();
		$sheetcount = count($dtpdf);
    	$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			'format' => 'A4',
			'margin_top' => 7.5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
			'cssFile' => '../web/css/pdf.css',
			]);
        // format content from your own css file if needed or use the
        // enhanced bootstrap css built by Krajee for mPDF formatting

		return $pdf->output();

    }
	public function actionAwassend($id, $view='pdf') {

		$model = $this->findModel($id);
		$queue = new MailQueue(['id' => $model->Tempid(), 'language' => 'en']);
		$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			'format' => 'A4',
			'margin_top' => 7.5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
		]);
		$stylesheet = file_get_contents('css/PDF179.css');
		$pdf->setTitle('Inline Track Welding Limited - Welding Information & Technical Review');
		$pdf->setSubject('Welding Information & Technical Review');
		$pdf->WriteHTML($stylesheet,1);
		$dtpdf = Forms::find()
				->andwhere(['actid' => $id, 'form' => 'dtwas'])
				->andwhere(['status' => ['Active', null]])
				->all();
				$sheetcount = count($dtpdf);
		if($view !== 'pdf'){
			return $this->render('allwas', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]);
		}
		$pdf->WriteHTML($this->renderPartial('allwas', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]));
		$content = $pdf->Output('', 'S');
		//$content = base64_encode($content);
		if (isset($model->contactemail)) {$queue->to_email = $model->contactemail;};
		if (isset($model->contactemail2)) {$queue->to_email2 = $model->contactemail2;};
		if (isset($model->contactemail3)) {$queue->to_email3 = $model->contactemail3;};
		if (isset($model->contactemail4)) {$queue->to_email4 = $model->contactemail4;};
		if (isset($model->contactemail5)) {$queue->to_email5 = $model->contactemail5;};
		if (isset($model->contactemail6)) {$queue->to_email6 = $model->contactemail6;};
		if (isset($model->contactemail7)) {$queue->to_email7 = $model->contactemail7;};
		if (isset($model->contactemail8)) {$queue->to_email8 = $model->contactemail8;};
		if (isset($model->contactemail9)) {$queue->to_email9 = $model->contactemail9;};
		if (isset($model->contactemail10)) {$queue->to_email10 = $model->contactemail10;};
		//$queue->to_email5 = $model->activity->contactemail6;

		$queue->to_cc = 'NGauge@inlinetrack.co.uk';
		$subject =   'Inline Welding Information & Technical Review - '.$model->location;
		$queue->subject = $subject;
		$queue->from_email = 'Admin@InlineTrack.co.uk';
		$queue->from_name =  'Office Admin';
		$queue->date_published = date("Y-m-d H:i:s.z");
		$queue->max_attempts = 3;  //No of try to send this mail
		$queue->attempts = 0;
		$queue->success = 0;  //will be set to 0 on send.
		//$filename = $subject+".pdf";
		//$filename = $subject+".pdf";
		$filename = $subject.'.pdf';
		$queue->status = 'Active';
		$queue->filename = $filename;
		$queue->message = $this->renderPartial('@frontend/views/emaillayouts/exemail', ['model' => $model]);
		$queue->emailfile = base64_encode(gzcompress(base64_encode($content)));
		$queue->actid = $id;
		$queue->jobno = $model->jobno;
		if ($queue->save()) {
			$check = Activities::checkMail($queue->id);
			return $this->render('emailstatus', ['model' => $check, 'emailid' => $queue->id]);
		} else {
			return print_r($queue->errors);
		}
	}
	public function actionAwassendwelders($id) {

		$model = $this->findModel($id);
		$queue = new MailQueue(['id' => $model->Tempid(), 'language' => 'en']);
			$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			'format' => 'A4',
			'margin_top' => 7.5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
		]);
		$stylesheet = file_get_contents('css/PDF179.css');
		$pdf->setTitle('Inline Track Welding Limited - Welding Information & Technical Review');
		$pdf->setSubject('Welding Information & Technical Review');
		$pdf->WriteHTML($stylesheet,1);
		$dtpdf = Forms::find()
				->andwhere(['actid' => $id, 'form' => 'dtwas'])
				->andwhere(['status' => ['Active', null]])
				->one();
				$sheetcount = 1;
		$operatives = \frontend\models\User::find()->select(['email', 'username'])->asArray()->indexBy('username')->all();
		$pdf->WriteHTML($this->renderPartial('@modules/forms/views/dtwas/_view', ['model' => $dtpdf->data, 'job' => $model, 'operatives' => $operatives,  'sheetcount' => $sheetcount ]));
		$content = $pdf->Output('', 'S');
		//$content = base64_encode($content);
		foreach (explode(',', $model->welder) as $key => $welder) {
			if ($key == 0) {$queue->to_email3 = $operatives[$welder]['email'];}
			if ($key == 1) {$queue->to_email4 = $operatives[$welder]['email'];}
			if ($key == 2) {$queue->to_email5 = $operatives[$welder]['email'];}
			if ($key == 3) {$queue->to_email6 = $operatives[$welder]['email'];}
			if ($key == 4) {$queue->to_email7 = $operatives[$welder]['email'];}
			if ($key == 5) {$queue->to_email8 = $operatives[$welder]['email'];}
			if ($key == 6) {$queue->to_email9 = $operatives[$welder]['email'];}
			if ($key == 7) {$queue->to_email10 = $operatives[$welder]['email'];}
			if ($key == 8) {$queue->to_email11 = $operatives[$welder]['email'];}
			if ($key == 9) {$queue->to_email12 = $operatives[$welder]['email'];}
			if ($key == 10) {$queue->to_email13 = $operatives[$welder]['email'];}
			if ($key == 11) {$queue->to_email14 = $operatives[$welder]['email'];}
			if ($key == 12) {$queue->to_email15 = $operatives[$welder]['email'];}
		}
		//$queue->to_email5 = $model->activity->contactemail6;

		$queue->to_cc = 'NGauge@inlinetrack.co.uk';
		$subject =   'Inline Welding Information & Technical Review - '.$model->location;
		$queue->subject = $subject;
		$queue->from_email = 'Admin@InlineTrack.co.uk';
		$queue->from_name =  'Office Admin';
		$queue->date_published = date("Y-m-d H:i:s.z");
		$queue->max_attempts = 3;  //No of try to send this mail
		$queue->attempts = 0;
		$queue->success = 0;  //will be set to 0 on send.
		//$filename = $subject+".pdf";
		//$filename = $subject+".pdf";
		$filename = $subject.'.pdf';
		$queue->status = 'Active';
		$queue->filename = $filename;
		$queue->message = $this->renderPartial('@modules/forms/views/dtwas/email', ['model' => $dtpdf->data, 'job' => $model]);
		$queue->emailfile = base64_encode(gzcompress(base64_encode($content)));
		$queue->actid = $id;
		$queue->jobno = $model->jobno;
		if ($queue->save()) {
			$check = Activities::checkMail($queue->id);
			return $this->render('emailstatus', ['model' => $check, 'emailid' => $queue->id]);
		} else {
			return print_r($queue->errors);
		}
	}

    public function actionApdfview($id) {
		$model = $this->findModel($id);

    	     $dtpdf = Forms::find()
     		->andwhere(['actid' => $model->id])
     		->andwhere(['or', ['is', 'status', null],['not',['status' => 'Deleted']]])
			 ->andfilterwhere(['in', 'form', $this->weldforms])
			 ->orderby(['form' => SORT_ASC])
			 ->all();


			 $order = $this->weldforms;
			 usort($dtpdf, function ($a, $b) use ($order) {
				 $pos_a = array_search($a['form'], $order);
				 $pos_b = array_search($b['form'], $order);
				 if ($a === false && $b === false) { // both items are dont cares
					return 0;                       // a == b
				} else if ($pos_a === false) {          // $a is a dont care
					return 1;                       // $a > $b
				} else if ($pos_b === false) {          // $b is a dont care
					return -1;                      // $a < $b
				} else {
					return $pos_a - $pos_b;                 // sort $a and $b ascending
				}
			 });

			$sheetcount = count($dtpdf);
		$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			'format' => 'A4',
			'margin_top' => 5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
			'shrink_tables_to_fit' => true,
		]);
		$stylesheet = file_get_contents('css/PDF179.css');
		$pdf->setTitle('Inline Track Welding Limited - ');
		$pdf->setSubject('..');
		$pdf->WriteHTML($stylesheet,1);
		$pdf->WriteHTML($this->renderPartial('pdfs', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]));
		return $pdf->output();
		//** 2025 */
		/*$dtpdf = Forms::find()
			->andwhere(['actid' => $model->id])
			->andwhere(['or', ['is', 'status', null],['not',['status' => 'Deleted']]])
			->andfilterwhere(['in', 'form', $this->weldforms])
			->orderby(['form' => SORT_ASC])
			->all();
			$order = $this->weldforms;
			usort($dtpdf, function ($a, $b) use ($order) {
				$pos_a = array_search($a['form'], $order);
				$pos_b = array_search($b['form'], $order);
				if ($a === false && $b === false) { // both items are dont cares
				return 0;                       // a == b
			} else if ($pos_a === false) {          // $a is a dont care
				return 1;                       // $a > $b
			} else if ($pos_b === false) {          // $b is a dont care
				return -1;                      // $a < $b
			} else {
				return $pos_a - $pos_b;                 // sort $a and $b ascending
			}
			});

		$sheetcount = count($dtpdf);
		$html = $this->renderPartial('pdfs', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]);
		// Generate single multi-page PDF with CSS controlling orientation
		$pdfContent = Yii::$app->pdf->fromPages($html, true);
		
		return Yii::$app->response->sendContentAsFile($pdfContent, 'Docs-' . $id . '.pdf', [
            'mimeType' => 'application/pdf'
        ]);*/
	}

	public function actionPdfview($id) {
    	$model = $this->findModel($id);
    		 $dtpdf = Forms::find()
     		->where(['actid' => $model->id])
			->andwhere(['not', ['status' => 'deleted']])
     		->andfilterwhere(['in', 'form', $this->weldforms])
     		->orderby('status ASC')
     		->all();
		$sheetcount = count($dtpdf);
    	$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			// A4 paper format
			'format' => 'A4',
			'margin_top' => 7.5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
        ]);
		$stylesheet = file_get_contents('css/PDF179.css');
		$pdf->WriteHTML($stylesheet,1);
		$pdf->WriteHTML($this->renderPartial('pdfs', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]));
		return $pdf->output();

    }
   	public function actionContacts() {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
            if ($parents != null) {
                $cat_id = $parents[0];
                $out = Contacts::getcontacts($cat_id);
                // the getSubCatList function will query the database based on the
                // cat_id and return an array like below:
                // [
                //    ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
                //    ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
                // ]
                return Json::encode(['output' => $out, 'selected'=>'']);
            }
        }
        echo Json::encode(['output'=>'', 'selected'=>'']);
    }

   	public function actionAbsclone($id) {
		$obj = Activities::findOne(['id' => $id]);
		$clone = new Activities();
		$clone->attributes = $obj->attributes;
		$clone->welder = explode(',', $clone->welder);
		unset($clone->id);
		$clone->isNewRecord = true;
		$clone->id = $clone->Tempid();
		$clone->save();
	    return $this->redirect(['absupdate', 'id' => $clone->id]);
	}

	public function actionClone($id) {
		$obj = Activities::findOne(['id' => $id]);
		$clone = new Activities();
		$clone->attributes = $obj->attributes;
		$clone->welder = explode(',', $clone->welder);
		unset($clone->id, $clone->jobstatus, $clone->billingstatus);
		$clone->isNewRecord = true;
		$clone->visitno = $obj->visitno +1;
		$clone->id = $clone->Tempid();
		$clone->save();
	    return $this->redirect(['update', 'id' => $clone->id]);
	}
	public function actionClonenewjobno($id) {
		$obj = Activities::findOne(['id' => $id]);
		$clone = new Activities();
		$clone->attributes = $obj->attributes;
		$clone->welder = explode(',', $clone->welder);
		unset($clone->id, $clone->jobstatus, $clone->billingstatus,$clone->jobno,$clone->visitno );
		$clone->isNewRecord = true;
		$clone->id = $clone->Tempid();
		$clone->save();
	    return $this->redirect(['update', 'id' => $clone->id]);
	}

	public function actionCreate()
	{
		
		if (Yii::$app->user->identity->ingroup('Global Admins') == true) {
			$model = new Activities(['id' => Activities::Tempid()]);
			$model->type = 'welding';
			$welder = User::find()->select(['username'])->where(['=', 'id', Yii::$app->request->get('group', null)])->one();
			$model->welder = $welder?->username;
			$model->sdate = Yii::$app->request->get('date', null) . ' 23:00:00';
			$model->save();
			return $this->redirect(['update', 'id' => $model->id]);
		} else {
			throw new ForbiddenHttpException('You are not allowed to Perform this function', '403');
		}
    }
	public function actionCreateTraining()
	{
		
		if (Yii::$app->user->identity->ingroup('Global Admins') == true) {
			$model = new Activities(['id' => Activities::Tempid()]);
			$model->type = 'training';
			$welder = User::find()->select(['username'])->where(['=', 'id', Yii::$app->request->get('group', null)])->one();
			$model->welder = $welder?->username;
			$model->relatedid = '99F04AC0-4857-4B80-9EC7-36BD83165025';

			$model->sdate = Yii::$app->request->get('date', null) . ' 08:00:00';
			$model->edate = Yii::$app->request->get('date', null) . ' 16:00:00';
			$model->save();
			return $this->redirect(['update', 'id' => $model->id]);
		} else {
			throw new ForbiddenHttpException('You are not allowed to Perform this function', '403');
		}
    }
	public function actionCreateAdministration()
	{
		
		if (Yii::$app->user->identity->ingroup('Global Admins') == true) {
			$model = new Activities(['id' => Activities::Tempid()]);
			$model->type = 'administration';
			$welder = User::find()->select(['username'])->where(['=', 'id', Yii::$app->request->get('group', null)])->one();
			$model->welder = $welder?->username;
			$model->relatedid = '99F04AC0-4857-4B80-9EC7-36BD83165025';
			$model->sdate = Yii::$app->request->get('date', null) . ' 08:00:00';
			$model->edate = Yii::$app->request->get('date', null) . ' 16:00:00';
			$model->save();
			return $this->redirect(['update', 'id' => $model->id]);
		} else {
			throw new ForbiddenHttpException('You are not allowed to Perform this function', '403');
		}
    }

	public function actionAbsence()
	{
    	$model = new Activities(['id' => Activities::tempid(), 'relatedid' => '0CA12FA4-330C-4CFD-8E1C-0CD1954DEF41', ]);
	   	if ($model->load(\Yii::$app->request->post()) && $model->save()) {
	        return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('absence', [
                'model' => $model,
            ]);
		};
	}

	public function actionPdf($id)
	{
		$model = $this->findModel($id);
		$queue = new MailQueue(['id' => $model->Tempid(), 'language' => 'en']);
		$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			'format' => 'A4',
			'margin_top' => 7.5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
		]);
		$stylesheet = file_get_contents('css/PDF179.css');
		$pdf->WriteHTML($stylesheet,1);
		$dtpdf = Forms::find()
				->andwhere(['actid' => $model->id])
				->andwhere(['or', ['is', 'status', null],['not',['status' => 'Deleted']]])
				->andfilterwhere(['in', 'form', $this->weldforms])
				->andwhere(['created_by' => Yii::$app->user->identity->id])
				->all();
		$sheetcount = count($dtpdf);
		$pdf->WriteHTML($this->renderPartial('pdfs', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]));
		$content = base64_encode($pdf->Output('', 'S'));

		if (isset($model->contactemail)) {$queue->to_email = $model->contactemail;};
		if (isset($model->contactemail2)) {$queue->to_email2 = $model->contactemail2;};
		if (isset($model->contactemail3)) {$queue->to_email3 = $model->contactemail3;};
		if (isset($model->contactemail4)) {$queue->to_email4 = $model->contactemail4;};
		if (isset($model->contactemail5)) {$queue->to_email5 = $model->contactemail5;};
		if (isset($model->contactemail6)) {$queue->to_email6 = $model->contactemail6;};
		if (isset($model->contactemail7)) {$queue->to_email7 = $model->contactemail7;};
		if (isset($model->contactemail8)) {$queue->to_email8 = $model->contactemail8;};
		if (isset($model->contactemail9)) {$queue->to_email9 = $model->contactemail9;};
		if (isset($model->contactemail10)) {$queue->to_email10 = $model->contactemail10;};
		$queue->subject = $model->emailsubject;
		$queue->from_email = 'NGauge@InlineTrack.co.uk';
		$queue->from_name =  'Office Admin';
		$queue->to_cc =  'NGauge@InlineTrack.co.uk';
		$queue->date_published = date("Y-m-d H:i:s.z");
		$queue->filename = $model->emailsubject.".pdf";
		$queue->message = $this->renderPartial('@frontend/views/emaillayouts/exemail', ['model' => $model]);
		$queue->emailfile = base64_encode(gzcompress($content,9));
		$queue->actid = $id;
		$queue->jobno = $model->jobno;
		$queue->save();

		$model->jobstatus = 'Attended';
		$model->save();
		return $this->redirect(['getmupdate','emailid' => $queue->id]);
	}


	public function actionCancelled($id) {
		$model = $this->findModel($id);
		$model->jobstatus = 'Cancelled';
		$model->save();
		$welders = explode(',', $model->welder);
		foreach ($welders as $welder) {
			$uemail = ArrayHelper::getColumn(user::find()->select('personalemail')->where(['username' => $welder])->all(), 'personalemail');
			foreach ($uemail as $x => $mmail ) {
				$email1[] = $mmail;
			}
			$email = implode(',', $email1);
		}

		$queue = new MailQueue(['id' => $model->Tempid(), 'language' => 'en']);
		$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			'format' => 'A4',
			'margin_top' => 7.5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
		]);
		//$mpdf = $pdf->api;
		$stylesheet = file_get_contents('../web/css/PDF.css');
		$pdf->WriteHTML($stylesheet,1);
		$dtpdf = dtpdf::find()
				->andwhere(['jobno' => $model->jobno])
				->andwhere(['url' => 'was'])
				->all();
				$sheetcount = count($dtpdf);
		$pdf->WriteHTML($this->renderPartial('allwas', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]));
		$content = $pdf->Output('', 'S');
		$content = base64_encode($content);
		if (isset($model->contactemail)) {$queue->to_email = $email.$model->contactemail;};
		if (isset($model->contactemail2)) {$queue->to_email2 = $model->contactemail2;};
		if (isset($model->contactemail3)) {$queue->to_email3 = $model->contactemail3;};
		if (isset($model->contactemail4)) {$queue->to_email4 = $model->contactemail4;};
		if (isset($model->contactemail5)) {$queue->to_email5 = $model->contactemail5;};
		if (isset($model->contactemail6)) {$queue->to_email6 = $model->contactemail6;};
		if (isset($model->contactemail7)) {$queue->to_email7 = $model->contactemail7;};
		if (isset($model->contactemail8)) {$queue->to_email8 = $model->contactemail8;};
		if (isset($model->contactemail9)) {$queue->to_email9 = $model->contactemail9;};
		if (isset($model->contactemail10)) {$queue->to_email10 = $model->contactemail10;};
		//$queue->to_email5 = $model->activity->contactemail6;
		$queue->to_cc = 'NGauge@inlinetrack.co.uk';
		$subject =   'CANCELLED - Inline Welding Information & Technical Review - '.$model->location.' CANCELLED';
		$queue->subject = $subject;
		$queue->from_email = 'Admin@InlineTrack.co.uk';
		$queue->from_name =  'Office Admin';
		$queue->date_published = date("Y-m-d H:i:s.z");
		$queue->max_attempts = 3;  //No of try to send this mail
		$queue->attempts = 0;
		$queue->success = 0;  //will be set to 1 on send.
		//$filename = $subject+".pdf";
		//$filename = $subject+".pdf";
		$filename = $subject.'.pdf';
		$queue->filename = $filename;
		$queue->message = $this->renderPartial('/emaillayouts/cancelledemail', ['model' => $model]);
		$queue->emailfile = base64_encode(gzcompress($content,9));
		$queue->actid = $id;
		$queue->jobno = $model->jobno;
		$queue->save();
		if ($mail) {
			$check = Activities::checkMail($queue->id);
			return $this->redirect(['getmupdate','emailid' => $queue->id]);
		}
    }

    public function actionGetroute($id) {
    	$model = $this->findModel($id);
		$client = new Client(['responseConfig' => [
	    	'format' => Client::FORMAT_JSON
	    ],]);
		$response = $client->createRequest()
			->setMethod('get')
			->setUrl('https://maps.googleapis.com/maps/api/directions/json')
			->setData([
				'origin' => Yii::$app->params['settings']['postcode'],
				'destination' => $model->postcode,
				'departure_time' => $model->starttime,
				'avoid' => 'tolls',
				'units' => 'imperial',
				'region' => 'gb',
				'traffic_model' => 'pessimistic',
				'apiKey'=> 'AIzaSyBBchyGKQR6JT0nShSyXlceU83PXj8mBdY'])
			->setOptions(['timeout' => 5, ])// set timeout to 5 seconds for the case server is not responding
			->send();
		$html = '';
		$routes = $response->data;
		if (isset($routes['routes']['0'])) {
		 	$html .= '<li>Total Distance: '.$routes['routes']['0']['legs']['0']['distance']['text'].'</li>';
		 	$html .= '<li>Total Distance: '.$routes['routes']['0']['legs']['0']['duration']['text'].'</li>';
	    	foreach ($routes['routes']['0']['legs']['0']['steps'] as $a => $route) {
	    		$html .= '<li>'.$route['html_instructions'].' for '.$route['distance']['text'].' ('.$route['duration']['text'].')</li>';
			}
			$model->route = $html;
			$model->save();
			return $html;
		 } else {
		 	return print_r($routes);
		 }
	}

	public function actionGetmupdate($emailid) {
		$check = Activities::checkMail($emailid);
		return $this->render('emailstatus', ['model' => $check, 'emailid' => $emailid]);
	}



	public function actionApdf($id) {

		$model = $this->findModel($id);
		$queue = new MailQueue(['id' => $model->Tempid(), 'language' => 'en']);
			$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			'format' => 'A4',
			'margin_top' => 7.5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
		]);
		$stylesheet = file_get_contents('css/PDF179.css');
		$pdf->setTitle('Inline Track Welding Limited - ');
		$pdf->setSubject('..');
		$pdf->WriteHTML($stylesheet,1);
		$dtpdf = Forms::find()
			->andwhere(['or', ['is', 'status', null],['not',['status' => 'Deleted']]])
			->andwhere(['actid' => $model->id])
			->andfilterwhere(['in', 'form', $this->weldforms])
			->all();
		$sheetcount = count($dtpdf);
		$pdf->WriteHTML($this->renderPartial('pdfs', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]));
		$content = $pdf->Output('', 'S');
		$content = base64_encode($content);
		isset($model->contactemail) == true ? $queue->to_email = $model->contactemail : false;
		isset($model->contactemail2) == true ? $queue->to_email2 = $model->contactemail2 : false;
		isset($model->contactemail3) == true ? $queue->to_email3 = $model->contactemail3 : false;
		isset($model->contactemail4) == true ? $queue->to_email4 = $model->contactemail4 : false;
		isset($model->contactemail5) == true ? $queue->to_email5 = $model->contactemail5 : false;
		isset($model->contactemail6) == true ? $queue->to_email6 = $model->contactemail6 : false;
		isset($model->contactemail7) == true ? $queue->to_email7 = $model->contactemail7 : false;
		isset($model->contactemail8) == true ? $queue->to_email8 = $model->contactemail8 : false;
		isset($model->contactemail9) == true ? $queue->to_email9 = $model->contactemail9 : false;
		isset($model->contactemail10) == true ? $queue->to_email10 = $model->contactemail10 : false;
		//$queue->to_email5 = $model->activity->contactemail6;
        $queue->to_cc = 'NGauge@inlinetrack.co.uk';
     	$subject =   $model->emailsubject ;
		$queue->subject = $subject;
		$queue->from_email = 'Admin@InlineTrack.co.uk';
		$queue->from_name =  'Office Admin';
		$queue->date_published = date("Y-m-d H:i:s.z");
		$queue->max_attempts = 3;  //No of try to send this mail
		$queue->attempts = 0;
		$queue->success = 0;  //will be set to 0 on send.
		//$filename = $subject+".pdf";
		//$filename = $subject+".pdf";
		$filename = $subject.'.pdf';
		$queue->filename = $filename;
		$queue->message = $this->renderPartial('@frontend/views@frontend/views/emaillayouts/exemail', ['model' => $model]);
		$queue->emailfile = base64_encode(gzcompress($content,9));
		$queue->actid = $id;
		$queue->jobno = $model->jobno;
		$queue->save();

    	$model->SiteAttended();

		return $this->redirect(['getmupdate', 'emailid' => $queue->id]);
	}

    public function actionPdfincidentview($id) {
    	$model = $this->findModel($id);
    	$dtpdf = Forms::find()
		->andwhere(['or', ['is', 'status', null],['not',['status' => 'Deleted']]])
     		->andwhere(['actid' => $id])
     		->andfilterwhere(['in', 'form', $this->hseqforms])
     		->all();
		$sheetcount = count($dtpdf);
    //return var_dump($dtpdf);
    	$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			// A4 paper format
			'format' => 'A4',
			'margin_top' => 7.5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
        ]);
		$stylesheet = file_get_contents('css/PDF179.css');
		$pdf->WriteHTML($stylesheet,1);
		$pdf->WriteHTML($this->renderPartial('pdfs', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]));
		return $pdf->output();

    }
    public function actionPdfincident($id) {
   		$model = $this->findModel($id);
		   $queue = new MailQueue(['id' => $model->Tempid(), 'language' => 'en']);
		$pdf = new mPDF([
			'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
			'format' => 'A4',
			'margin_top' => 7.5,
			'margin_header' => 0,
			'margin_left' => 5,
			'margin_right' => 5,
			'margin_footer' => 0,
			'margin_bottom' => 1,
			'default_font_size' => 6,
			'default_font' => "Gill Sans MT",
		]);
		$stylesheet = file_get_contents('css/PDF179.css');
		$pdf->setTitle('Inline Track Welding Limited - Incident Report');
		$pdf->setSubject('..');
		$pdf->WriteHTML($stylesheet,1);
		$dtpdf = Forms::find()
		->andwhere(['or', ['is', 'status', null],['not',['status' => 'Deleted']]])
			->andwhere(['actid' => $id])
			->andfilterwhere(['in', 'form', $this->hseqforms])
			->all();
		$sheetcount = count($dtpdf);
	//return var_dump($dtpdf);
		$pdf->WriteHTML($this->renderPartial('pdfs', ['model' => $model, 'dtpdf' => $dtpdf, 'sheetcount' => $sheetcount ]));
		$content = $pdf->Output('', 'S');
		$content = base64_encode($content);
		if (isset($model->contactemail)) {$queue->to_email = $model->contactemail;};
		if (isset($model->contactemail2)) {$queue->to_email2 = $model->contactemail2;};
		if (isset($model->contactemail3)) {$queue->to_email3 = $model->contactemail3;};
		if (isset($model->contactemail4)) {$queue->to_email4 = $model->contactemail4;};
		if (isset($model->contactemail5)) {$queue->to_email5 = $model->contactemail5;};
		if (isset($model->contactemail6)) {$queue->to_email6 = $model->contactemail6;};
		if (isset($model->contactemail7)) {$queue->to_email7 = $model->contactemail7;};
		if (isset($model->contactemail8)) {$queue->to_email8 = $model->contactemail8;};
		if (isset($model->contactemail9)) {$queue->to_email9 = $model->contactemail9;};
		if (isset($model->contactemail10)) {$queue->to_email10 = $model->contactemail10;};
   		//$queue->to_email5 = $model->activity->contactemail6;
        $queue->to_cc = 'NGauge@inlinetrack.co.uk';
    	$subject = 'Inline Track Welding Limited - Incident Report '.$model->location ;
		$queue->subject = $subject;
		$queue->from_email = 'Admin@InlineTrack.co.uk';
		$queue->from_name =  'Office Admin';
		$queue->date_published = date("Y-m-d H:i:s.z");
		$queue->max_attempts = 3;  //No of try to send this mail
		$queue->attempts = 0;
		$queue->success = 0;  //will be set to 0 on send.
		//$filename = $subject+".pdf";
		//$filename = $subject+".pdf";
		$filename = $subject.'.pdf';
		$queue->filename = $filename;
		$queue->message = $this->renderPartial('/@frontend/views/emaillayouts/exemail', ['model' => $model]);
		$queue->emailfile = base64_encode(gzcompress($content,9));
		$queue->actid = $id;
		$queue->jobno = $model->jobno;
		$queue->save();
		$created = $queue->created_at;
		if ($queue) {
			$check = Activities::checkMail($queue->id);
			return $this->render('emailstatus', ['model' => $check, 'emailid' => $queue->id]);
		}
    }


    public Function actionGetactivity($modelid) {
		$modelid = Activities::findOne(['id' => $modelid]);
		echo Json::Encode($modelid);
	}

    public function actionWeektimeline() {
        $model = new Activities();
         if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
             } else {
             return $this->render('weektimeline', array(
                'model' => $model,
            ));
        }
    }

    public function actionTimeline() {
		$attended = Activities::find()->select(['jobstatus','billingstatus', 'deleted', 'status'])->andWhere(['status' => ['active', null]])->andWhere(['jobstatus' => 'Attended'])->all();
		$completed = Activities::find()->select(['jobstatus','billingstatus', 'deleted', 'status'])->andWhere(['status'=> ['active', null]])->andWhere(['jobstatus' => 'completed'])->andwhere(['or', ['!=', 'billingstatus', 'Invoiced'], ['is', 'billingstatus', null]])->all();
		$invoiced = Activities::find()->select(['jobstatus','billingstatus', 'deleted', 'status'])->andWhere(['status' => ['active', null]])->andWhere(['jobstatus' => 'completed'])->andwhere(['=', 'billingstatus', 'Invoiced'])->all();
		$sdate = date('d/m/Y', strtotime('-7 days'));
		$users = \common\models\User::find()
			->select(['id', 'username', 'adv'])
			->andWhere(['not', ['username' => ['admin', 'a.pickstock@portalpeople.uk', 'Server02@inlinetrack.co.uk', 'HelenThomson', null]]])
			->andwhere(['sys_user.status' => 10, ])
			//->andwhere(['is', 'sys_user.blocked_at', null ])
			->all();
		$groups = [];
		foreach($users as $key => $user){
			$groups[$user->username] =  [
				'id' => (string) $user->id,
				'name' =>  (string) $user->fullname,
			];
		}
		$from = date('Y-m-d', strtotime('today -1 month'));
		$to   = date('Y-m-d', strtotime('today +1 month'));
		$statuss = Yii::$app->user->identity->inGroup('Global Admins') == true ? ['Cancelled', 'Deleted'] : ['Cancelled', 'Deleted', 'Hidden'];
		$items =  \modules\activities\models\Activities::find()
			->select('id, sdate AS start_date, edate AS end_date, shiftlength, shift, jobstatus, billingstatus, comments, welder,deleted,jobno')
			->andwhere(['status' => ['Active', null]])
			->andwhere(['not', ['in', 'jobstatus', $statuss]])
			->andWhere(['or', ['>=', "sdate", $from,], ['<=', "sdate", $to ]])
			->orderBy(['sdate' => SORT_DESC]);
		Yii::$app->user->identity->inGroup('Admins') ? $items->andwhere(['!=', 'jobstatus', 'Hidden']) : false;
		$data = [];
		foreach($items->asArray()->all() as $key => $job){
			foreach(explode(',', $job['welder']) as $k => $welder){
				$user = array_key_exists($welder, $groups) ? $groups[$welder] : null;
				if($user){
					$data[] =  [
						'title' =>  (string) $job['jobno'].' - '.$job['comments'],
						'sectionID' => (string) $user['id'],
						'id' => (string) $job['id'].'|'.trim($welder),
						'data' => (string) $job['comments'],
						'style' => (string) $job['jobstatus'],
						'sd' => (string) $job['start_date'],
						'fd' => (string) $job['end_date'],
					];
				}
			}
		}
		return $this->render('timeline', ['attended' => $attended, 'completed' => $completed, 'invoiced' =>$invoiced, 'sdate' => $sdate, 'data' => $data, 'groups' => $groups ]);
    }

    public function actionTimelinedata($to,$from ) {

    	$from = date('Y-m-d', strtotime($from));
    	$to   = date('Y-m-d', strtotime($to));
    	\Yii::$app->response->format = 'json';
		$statuss = Yii::$app->user->identity->inGroup('Global Admins') == true ? ['Cancelled', 'Deleted'] : ['Cancelled', 'Deleted', 'Hidden'];
		$items =  Activities::find()
			->select('id, sdate AS start_date, edate AS end_date, shiftlength, shift, jobstatus, billingstatus, comments AS text, welder,deleted,jobno')
			->andwhere(['status' => ['Active', null]])
			->andwhere(['not', ['in', 'jobstatus', $statuss]])
			->andWhere(['or', ['>=', "sdate", $from,], ['<=', "sdate", $to ]]);
		Yii::$app->user->identity->inGroup('Admins') ? $items->andwhere(['!=', 'jobstatus', 'Hidden']) : false;
		return $items->asArray()->all();
	}

	public function actionTimelineuserdata()
	{
		\Yii::$app->response->format = 'json';
		$users = \common\models\User::find()
		->select(['username as key', "concat(sys_useradv.firstname, ' ', sys_useradv.lastname,' ', sys_user.stampno) as label", 'username as welder', 'sys_user.username','sys_user.stampno', 'sys_user.id', 'sys_user.blocked_at', 'sys_useradv.sequence'])
		//->andwhere(['not', ['users.deleted' => true]])
		->andwhere(['sys_usergroups.name' => 'Welders', 'sys_user.status' => 10, ])
		->andwhere(['is', 'sys_user.blocked_at', null ])
		->orderby(['sys_useradv.sequence' => SORT_ASC, 'sys_useradv.lastname' => SORT_ASC,])
		->joinwith(['useradv', 'groups'])
		->all();
		$out = [];
		foreach($users as $key =>$user){
			$out[] = ['key' => $user->username, 'label' => $user->useradv->firstname.' '.$user->useradv->lastname.' - '. $user->stampno, 'welder' => $user->username, 'username' => $user->username];
		}
    	return $out;
	}


	public function actionSuperupdate($id) {
		$model = Activities::findOne(['id' => $id]);
		$jobs = Activities::find()
			->where(['=', 'jobno', $model->jobno])
			->andwhere(['>', 'starttime', $model->starttime])
			->all();
		$x = 0;
		$data = [];
		foreach ($jobs as $key => $job) {
			if ($job->location = $model->location) {$job->location = $model->location;}
			if ($job->jobstatus <> $model->jobstatus) {$job->jobstatus = $model->jobstatus;}
			if ($job->billingstatus <> $model->billingstatus) {$job->billingstatus = $model->billingstatus;}
			if ($job->details <> $model->details) {$job->details = $model->details;}
			if ($job->jobtype <> $model->jobtype) {$job->jobtype = $model->jobtype;}
			if ($job->weldtype <> $model->weldtype) {$job->weldtype = $model->weldtype;}
			if ($job->railgrade <> $model->railgrade) {$job->railgrade = $model->railgrade;}
			if ($job->railgrade2 <> $model->railgrade2) {$job->railgrade2 = $model->railgrade2;}
			if ($job->railgrade3 <> $model->railgrade3) {$job->railgrade3 = $model->railgrade3;}
			if ($job->railsection <> $model->railsection) {$job->railsection = $model->railsection;}
			if ($job->railsection2 <> $model->railsection2) {$job->railsection2 = $model->railsection2;}
			if ($job->railsection3 <> $model->railsection3) {$job->railsection3 = $model->railsection3;}
			if ($job->journey <> $model->journey) {$job->journey = $model->journey;}
			if ($job->customerpono <> $model->customerpono) {$job->customerpono = $model->customerpono;}
			if ($job->tracktrolley <> $model->tracktrolley) {$job->tracktrolley = $model->tracktrolley;}
			if ($job->orderdata <> $model->orderdata) {$job->orderdata = $model->orderdata;}
		//	if ($job->weekno <> $model->weekno) {$job->weekno = $model->weekno;}
			if ($job->accesspoint <> $model->accesspoint){$job->accesspoint = $model->accesspoint;}
			if ($job->railwear <> $model->railwear) {$job->railwear = $model->railwear;}
			if ($job->railwear2 <> $model->railwear2) {$job->railwear2 = $model->railwear2;}
			if ($job->railwear3 <> $model->railwear3) {$job->railwear3 = $model->railwear3;}
			if ($job->railtrack <> $model->railtrack) {$job->railtrack = $model->railtrack;}
			if ($job->railtrack2 <> $model->railtrack2) {$job->railtrack2 = $model->railtrack2;}
			if ($job->railtrack3 <> $model->railtrack3) {$job->railtrack3 = $model->railtrack3;}
			if ($job->railclosure <> $model->railclosure) {$job->railclosure = $model->railclosure;}
			if ($job->process <> $model->process) {$job->process = $model->process;}
			if ($job->fuelgas <> $model->fuelgas) {$job->fuelgas = $model->fuelgas;}
			if ($job->portion <> $model->portion) {$job->portion = $model->portion;}
			if ($job->mould <> $model->mould) {$job->mould = $model->mould;}
			if ($job->wpsno <> $model->wpsno) {$job->wpsno = $model->wpsno;}
			if ($job->notes <> $model->notes) {$job->notes = $model->notes;}
			if ($job->railsupport <> $model->railsupport) {$job->railsupport = $model->railsupport;}
			if ($job->railsupport2 <> $model->railsupport2) {$job->railsupport2 = $model->railsupport2;}
			if ($job->railsupport3 <> $model->railsupport3) {$job->railsupport3 = $model->railsupport3;}
			if ($job->weld <> $model->weld) {$job->weld = $model->weld;}
			if ($job->weld2 <> $model->weld2) {$job->weld2 = $model->weld2;}
			if ($job->weld3 <> $model->weld3) {$job->weld3 = $model->weld3;}
			if ($job->noofwelds1 <> $model->noofwelds1) {$job->noofwelds1 = $model->noofwelds1;}
			if ($job->noofwelds2 <> $model->noofwelds2) {$job->noofwelds2 = $model->noofwelds2;}
			if ($job->noofwelds3 <> $model->noofwelds3) {$job->noofwelds3 = $model->noofwelds3;}
			if ($job->defectno1 !== $model->defectno1) {$job->defectno1 = $model->defectno1;}
			if ($job->defectno2 !== $model->defectno2) {$job->defectno2 = $model->defectno2;}
			if ($job->defectno3 !== $model->defectno3) {$job->defectno3 = $model->defectno3;}
			if ($job->weldprocess1 <> $model->weldprocess1) {$job->weldprocess1 = $model->weldprocess1;}
			if ($job->weldprocess2 <> $model->weldprocess2) {$job->weldprocess2 = $model->weldprocess2;}
			if ($job->weldprocess3 <> $model->weldprocess3) {$job->weldprocess3 = $model->weldprocess3;}
			if ($job->notes2 <> $model->notes2) {$job->notes2 = $model->notes2;}
			if ($job->notes3 <> $model->notes3) {$job->notes3 = $model->notes3;}
			if ($job->jnotes <> $model->jnotes) {$job->jnotes = $model->jnotes;}
			if ($job->fuelgas2 <> $model->fuelgas2) {$job->fuelgas2 = $model->fuelgas2;}
			if ($job->fuelgas3 <> $model->fuelgas3) {$job->fuelgas3 = $model->fuelgas3;}
			if ($job->elr <> $model->elr) {$job->elr = $model->elr;}
			if ($job->depot <> $model->depot) {$job->depot = $model->depot;}
			$job->save();
			if ($job->errors) {
				$data[] = ['id' => $job->id, 'Errors' => $job->errors];
			}
			$x++;
		}
		if ($data) {
			return print_r($data);
		} else {
	 		return $x.'Jobs Updated';
		}
	}


    /**
     * Updates an existing activities model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionAbsupdate($id) {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('absupdate', [
                'model' => $model,
            ]);
        }
    }
    public function actionUpdate($id) {
        $model = $this->findModel($id);
		$times = Activitiesusers::find()->where(['actid' => $model->id, 'status' => 'Active'])->indexBy('id')->all();
       	if ($model->load(Yii::$app->request->post()) && $model->save()) {
		   	Model::loadMultiple($times, Yii::$app->request->post());
		   	foreach($times as $key => $time) {
			   $time->save();
		   	}
			return $this->redirect(['view', 'id' => $model->id]);
		} elseif ($model->errors) {
			// if (!$model->validate()) {
			return print_R($model->errors);
			// }
		}
		if (Yii::$app->user->identity->ingroup('Global Admins') == true) {
			$welder = explode(',', $model->welder);
			if (is_array($welder)) {
				$model->welder = $welder;
			}
			return $this->render('update', ['model' => $model]);
		} else {
			return $this->redirect(['view', 'id' => $model->id]);
		}
	}


    /**
     * Deletes an existing activities model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionExc() {
    	Yii::$app->session->setFlash('success', [
			'type' => 'danger',
			'icon' => 'fa fa-users',
			'message' => Html::encode(Yii::$app->request->post('description')),
			'title' => Html::encode('Exceedence'),
		]);
		$exc = new \frontend\models\Activityexceedences();
    	$exc->actid = Yii::$app->request->post('id');
    	$exc->description = Yii::$app->request->post('description');
    	$exc->value = Yii::$app->request->post('value');
		return  $exc->save() ? 'success' : 'failure';
	}

    public function actionDeleted() {
        $searchModel = new ActivitiesSearch();
        $dataProvider = $searchModel->deleted(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

	public function actionDelete($id) {
        $model = $this->findModel($id);
        $model->delete();
        return $this->redirect(Yii::$app->request->referrer);
    }
    public function actionUndelete($id) {
        $model = $this->findModel($id);
        $model->status  = 'Active';
        $model->deleted = null;
        $model->save();
        return $this->redirect(Yii::$app->request->referrer);
    }

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

	public function actionDeletetime(){
		if(Yii::$app->request->isPost == true){
			Yii::$app->response->format = 'json';
			$actuser = Activitiesusers::findOne(['id' => Yii::$app->request->post('id')]);
			return $actuser->delete() ? ['status' => 200, 'Message' => 'Deleted'] : ['status' => 100, 'Message' => $actuser->errors];
		}
	}

	public function actionTimelineModal(){
		$id = Yii::$app->request->post('id')[0];
		list($id, $welder) = explode('|', $id);
		$model = $this->findModel($id);
		Yii::$app->response->format = 'json';
		return [
			'title' => $model->location.' - '.$model->jobno.' - '.$welder,
			'body' => $this->renderAjax('_timelinemodal', ['model' => $model]),
			'footer' => '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>',
		];
	}

	public function actionImportTraining(){
		$filePath = Yii::getAlias('@uploads/data/training.xlsx');
		$spreadsheet = IOFactory::load($filePath);
		$sheet = $spreadsheet->getActiveSheet();
		$rows = $sheet->toArray(null, true, true, true);

		$headers = array_shift($rows);
		$data = [];
		$rowNo = 1;
		foreach ($rows as $rowNo1 => $row) {
			++$rowNo;
			$cell = 'A';
			$item = [];
			foreach ($headers as $key => $header) {
				$item[strtolower(str_replace(' ', '_', $header))] = isset($row[$key]) ? $row[$key]: null;
				if ($header == 'Folder'){
					$sheetCell = $sheet->getCell($key . $rowNo);
					$url = $sheetCell->getHyperlink()->getUrl();
					$item['url'] = !empty($url) ? match(true){
						substr($url, 0, 12) == '../../../../' => str_replace('../../../../', 'https://inlinetrack.sharepoint.com/', $url),
						substr($url, 0, 9) == '../../../' => str_replace('../../../', 'https://inlinetrack.sharepoint.com/', $url),
						substr($url, 0, 6) == '../../' => str_replace('../../', 'https://inlinetrack.sharepoint.com/', $url),
						substr($url, 0, 3) == '../' => str_replace('../', 'https://inlinetrack.sharepoint.com/', $url),
						default => 'https://inlinetrack.sharepoint.com/'.$url,
					}: null;
					$item['folder'] = $row[$key];	
					//$item['coords'] = $key . $rowNo;	
				}
				$cell++;
			}
			// Drop row if both "Training Course" and "Client" are empty
			if (empty($item['training_course']) && empty($item['client']) || (strtolower($item['training_course']) == 'bh' && strtolower($item['client']) == 'bh')) {
				continue;
			}
			$data[] = $item;	
		}
		foreach($data as $key => $tevent){
			$model = new \modules\activities\models\Activities();
			$model->id = $model::tempid();
			$model->status = 'Active';
			$model->type = 'training';
			$model->relatedid = '99F04AC0-4857-4B80-9EC7-36BD83165025';
			$model->jobstatus = date('Y-m-d', strtotime(str_replace('/', '-', $tevent['start_time']))) < date('Y-m-d') ? 'completed' : 'Booked';
			$model->postcode = 'ME172GQ';
			$model->location = 'Office';
			
			$model->customerpono = $tevent['po'];
			$model->notes = $tevent['notes'];
			$model->welder = match($tevent['user']){
				'S Thomson' => 'SebThomson',
				'ScottMarsh' => 'ScottMarsh',
				'M. Wargen' => 'MarkWargen',
				default => 'SebThomson',
			};
			$model->sdate = date('Y-m-d H:i:s',strtotime(str_replace('/', '-', $tevent['start_time'])));
			$model->edate = date('Y-m-d H:i:s',strtotime(str_replace('/', '-', $tevent['end_time'])));
			
			$mdata = $model->data;
			$mdata['Training']->course = $tevent['training_course'];
			$mdata['Training']->company = $tevent['client'];
			$mdata['Training']->jobno = $tevent['folder'];
			
			$mdata['Training']->SharePointUrl = $tevent['url'];
			$model->data = $mdata;
			$model->save();
		}

		echo '<pre>' . print_r($data, true) . '</pre>';
	}
}