<?php
namespace modules\forms\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
use yii\helpers\FileHelper;
use yii\helpers\Url;

use yii\filters\AccessControl;
use yii\base\Model;

use modules\activities\models\Activities;
use frontend\models\Signature;
use modules\forms\models\Forms;
use modules\forms\models\Formssearch;

use frontend\models\Mailqueue;
//PDF's
use Mpdf\Mpdf;
use Spatie\Browsershot\Browsershot;

use yii\httpclient\Client;
/**
 * DT123Controller implements the CRUD actions for DT123 model.
 */
class FormsController extends Controller
{

    public $defaultAction = 'index';




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

        return $this->render('@modules/forms/views/index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }


	public function actionSend($id) {
	   	$model = $this->findModel($id);
        $model->send();
    }

    /**
     * Displays a single model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id, $form) {
        $formModel = $this->findModel($id, $form);
        $model = $formModel->data;
        if(is_object($model) == true){
            $rowdata = property_exists($model, 'rowdata') ? $model->rowdata : false;
            return $this->render('@modules/forms/views/view', [
                'model' => $model,
                'formModel' => $formModel,
            ]);
        } else {

            throw new NotFoundHttpException('The was a problem with the data.');
        }
    }
    /**
     * Displays a single DT123 model.
     * @param integer $id
     * @return mixed
     */
    public function actionViewp($id, $form) {
        $formModel = $this->findModel($id, $form);
        $model = $formModel->data;
        $layout = $model->viewLayout ? $model->viewLayout : '_'.$formModel->form.'v';
   	    $this->layout = 'pdf';
        return $this->render($layout, [
            'model' => $model,
            'formModel' => $formModel,
        ]);
    }

    public function actionPdfn($id, $form, $view=null)
    {
        $model = new Forms();
        $pdfid = $model::Tempid();
        $url = \yii\helpers\Url::to(["/forms/$form/viewp", 'id' => $id,], true);
        return \common\models\Base::generatePdf($pdfid, 'pdf', $url);
    }

    public function actionPdf($id, $form) {
        $formModel = $this->findModel($id, $form);
        if($form !== 'sop023'){
            $pdf = new mPDF([
                'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
                'format' => 'A4',
                'orientation' => $formModel->data->printlayout,
                '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($formModel->formname);
            $pdf->setSubject($form);
            $pdf->WriteHTML($stylesheet,1);
            $model = $formModel->data;
            $layout = $model->viewLayout ? $model->viewLayout : '_'.$formModel->form.'v';
            $pdf->WriteHTML($this->renderPartial($layout, ['model' => $formModel->data]));
            //    $content = $pdf->output('', 'S');
            return $pdf->output();
        } else {
            return $formModel->data->pdf();
        }
    }

    /**
     * Creates a new DT123 model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($form)
    {
        $actid = Yii::$app->request->get('actid', null);
        if(file_exists(Yii::getAlias('@modules/forms/models/'. ucwords($form) . '.php'))){
            $formClass = '\\modules\\forms\\models\\'. ucwords($form);
        } elseif(file_exists(Yii::getAlias('@frontend/models/forms/'. ucwords($form) . '.php'))){
            $formClass = '\\frontend\\models\\forms\\'. ucwords($form);
        }
        $formModel = new Forms(['formclass' => $formClass, 'actid' => $actid, 'id' => Forms::tempid()]);
        if(empty(Yii::$app->request->get('actid')) == false){
            $activity = Activities::findOne(['id' => $actid]);
            $formModel->actid = $activity->id;
            $formModel->jobno = $activity->jobno;
            $formModel->relatedid = $activity->relatedid;
        }
        $formModel->language = 'en';
        $formModel->form = $form;
        $formModel->subclass = property_exists($formModel, 'subclass') ? $formModel->subclass : null;
        $model = $formModel->data;
        method_exists($model, 'setData') ? $model->setData() : false;
        $signatures = $formModel->form == 'dt127' ? $model->signatures : null;
        if ($model->load(Yii::$app->request->post()) && $model->validate() && $formModel->save()) {
            return $this->redirect(['view', 'id' => $formModel->id, 'form' => $form]);
        } else {
            return $this->render('@modules/forms/views/create', [
                'model' => $model,
                'formModel' => $formModel,
                'signatures' => $signatures,
            ]);
        }
    }

    public function actionAddsignature($id)
    {
        $formModel = $this->findModel($id, 'dt127');
        $formdata = $formModel->data;
        $count = count($formdata->signatures);

        $model = new Signature([
                'relatedid' => $id, 
                'form' => 'dt127',
                'name' => Yii::$app->user->identity->username,
                'sequence' => $count + 1,
            ]);
        Yii::$app->response->format = 'json';
        return $model->save() ? ['body' => $this->renderAjax('signature', ['signature' => $model])] : false;

    }
    public function actionRemovesignature()
    {
        $id = Yii::$app->request->get('id');
        $model = Signature::findOne(['id' => $id]);
        
        Yii::$app->response->format = 'json';
        return $model->delete() ? ['status' => 200, 'message' => 'Deleted'] : ['status' => 100, 'message' => $model->errors];

    }


    public function actionDt127signs(){
        $forms = Forms::find()->where(['form' => 'dt127'])->all();
        foreach($forms as $key => $model){
            //$model = $formModel->data;
            $model->data->UpdateSignatures();
        }
    }


    public function actionUpdate($id, $form)
    {
        $formModel = $this->findModel($id, $form);
        $model = $formModel->data;
        
        if($formModel->form == 'dt127'){
            $signatures = $model->signatures;
            if(Yii::$app->request->isPost == true){
                $signatures = Signature::find()->where(['relatedid' => $formModel->id])->indexby('id')->all();
                Model::LoadMultiple($signatures, Yii::$app->request->post());
                foreach($signatures as $id => $signature) {
                    $signature->save();
                }
            }
        } else {
            $signatures = null;
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $formModel->save()) {
            return $this->redirect(['view', 'id' => $formModel->id, 'form' => $form]);
        } else {
            return $this->render('@modules/forms/views/update', [
                'model' => $model,
                'formModel' => $formModel,
                'signatures' => $signatures,
            ]);
        }
    }

    /**
     * Deletes an existing DT123 model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id, $form)
    {
        $model = $this->findModel($id, $form);
        $model->delete();
        return $this->redirect(Yii::$app->request->referrer);
    }
    public function actionUndelete($id)
    {
        $model = $this->findModel($id);
        $model->undelete();
        return $this->redirect(Yii::$app->request->referrer);
    }


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

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



    /**
     * Pushes a DT198 job to the Queue
     *
     * @param [date] $date YYYY-MM-DD;
     * @return void
     */
    public function actionDt198mailbox($date){
        Yii::$app->Jobqueue->push(new \console\jobs\Gcmmail(['date' => $date]));
    }

    /**
     * Updates an existing dt198 model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
	public function actionGetdropbox($actid, $date){
        file_exists("C:\NGauge\etc\ssl\cacert.pem") == true ? ini_set('curl.cainfo', "C:\NGauge\etc\ssl\cacert.pem") : false;
        $form = 'Dt198';
		$dbtoken = 'cm-E2LU0DLAAAAAAAAAAGJI313oSLrtEVuQ5va19eUi9YoP4MWGn7pEFEk3-8h1m';
		$cruverasdiis = NULL;
		$grade = NULL;
		$shiftstart = NULL;
		$shiftend = NULL;
		$senior = NULL;
		$assist1 = NULL;
		$assist2 = NULL;
		$assist3 = NULL;
		$actual = NULL;
		$planned = NULL;
		$last24 = strtotime('-24 hours');
        $apdata = [];

		$client = new \Spatie\Dropbox\Client($dbtoken);
		$adapter = new \Spatie\FlysystemDropbox\DropboxAdapter($client);
		$filesystem = new \League\Flysystem\Filesystem($adapter);


		$contents = $filesystem->listContents('Inline/Customer', true);
		//return print_r($contents);
        $file = date('Y_n_j', strtotime($date))."_CustomerFile.csv";

        $found = NULL;
		foreach ($contents as $object) {
			$tmp = "download.csv";
			echo $object['basename'].PHP_EOL;
			$out[] = [$object['basename'] => $file];
            //echo $object['basename']. ' - '.$file .PHP_EOL ;

			if ($object['basename'] == $file){
			    $found = 'Yes';
			    $stream = $filesystem->readStream($object['path']);
				file_put_contents($tmp, $stream);
				if (($handle = fopen($tmp, "r")) !== FALSE) {
		    		$row = 0;
					$x = 1;
		    		while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        $num = count($data);
                        $row++;
                        if($row == 3){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){$cruverasdiis = $value;}

                                    }
                                }
                            }
                        }
                        if($row == 4){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){$grade = $value;}

                                    }
                                }
                            }
                        }
                        if($row == 5){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){$shiftstart = $value;}

                                    }
                                }
                            }
                        }
                        if($row == 6){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){$shiftend = $value;}

                                    }
                                }
                            }
                        }
                        if($row == 7){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){$planned = $value;}

                                    }
                                }
                            }
                        }
                        if($row == 8){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){$actual = $value;}

                                    }
                                }
                            }
                        }
                        if($row == 9){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){$senior = $value;}

                                    }
                                }
                            }
                        }
                        if($row == 10){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){$assist1 = $value;}

                                    }
                                }
                            }
                        }
                        if($row == 11){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){$assist2 = $value;}

                                    }
                                }
                            }
                        }
                        if($row == 12){
                            for ($c=0; $c < $num; $c++) {
                                if($num > 1){
                                    foreach($data as $key => $value){
                                        if($key == 1){
                                            $assist3 = $value;
                                        }
                                    }
                                }
                            }
                        }
                        echo $row.PHP_EOL;

                        if($row > 15){
							
							$ap = [];
                            foreach($data as $key => $value){
								if($key == 0){$ap['type'] = trim($value);}
								if($key == 1){$ap['no'] = $value;}
								if($key == 2){$ap['distance'] = $value;}
								if($key == 3){$ap['voltsavg'] = $value;}
								if($key == 4){$ap['voltsmax'] = $value;}
								if($key == 5){$ap['voltsmin'] = $value;}
								if($key == 6){$ap['ampsavg'] = $value;}
								if($key == 7){$ap['ampsmin'] = $value;}
								if($key == 8){$ap['ampsmax'] = $value;}
								if($key == 9){$ap['speedavg'] = $value;}
								if($key == 10){$ap['speedmax'] = $value;}
								if($key == 11){$ap['speedmin'] = $value;}
								if($key == 12){$ap['inputkjavg'] = $value;}
								if($key == 13){$ap['inputkjmax'] = $value;}
								if($key == 14){$ap['inputkjmin'] = $value;}
								if($key == 15){$ap['interpassavg'] = $value;}
								if($key == 16){$ap['interpassmax'] = $value;}
								if($key == 17){$ap['interpassmin'] = $value;}
								if($key == 18){$ap['strikeonavg'] = $value;}
								if($key == 19){$ap['strikeoffavg'] = $value;}
							//	if($key == 16){$ap['strikeonmax'] = $value;}
							//	if($key == 17){$ap['strikeonmin'] = $value;}
							//	if($key == 19){$ap['strikeoffmax'] = $value;}
							//	if($key == 20){$ap['strikeoffmin'] = $value;}
								$ap['rowno'] = $x;
								
								
							}
							if( array_key_exists('distance', $ap) == true && empty($ap['distance']) ==false &&  $ap['distance'] !== 'Distance'){
								$apdata[] = $ap;
								$x++;
							}
                        }
                        
                    }
                }
                fclose($handle);
            } 
        }
        //print_r($apdata);

        if(is_array($apdata) == true && count($apdata) > 1){
            $mime = Filehelper::getMimeType($tmp);
            $contents = stream_get_contents($filesystem->readStream($object['path']));
            //fclose($contents);
            $actid = Yii::$app->request->get('actid') ? Yii::$app->request->get('actid') : null;
            $formclass = '\\frontend\\models\\'. ucwords($form);
            $formModel = new Forms(['formclass' => ucwords('Dt198'), 'actid' => $actid, 'id' => Forms::tempid()]);
            if(Yii::$app->request->get('actid') !== null){
                $activity = Activities::findOne(['id' => $actid]);
                $formModel->actid = $activity->id;
                $formModel->jobno = $activity->jobno;
                $formModel->relatedid = $activity->relatedid;
            }
            $formModel->language = 'en';
            $formModel->form = $form;
            $formModel->subclass = property_exists($formModel, 'subclass') ? $formModel->subclass : null;
            $model = $formModel->data;
            $y = 0;
			$allowed = ['ROOT BEAD', 'SUBSEQUENT BEAD', 'TOP BEAD'];
            foreach($apdata as $key => $val) {
				
                if($val['rowno'] > 0 && in_array($val['type'], $allowed) == true) {
					$model->rowno[$y] = $y;
					$model->rowtype[$y] = $val['type'];
					$model->rowdistance[$y] = $val['distance'];
					$model->rowvoltsavg[$y] = $val['voltsavg'];
					$model->rowvoltsmin[$y] = $val['voltsmin'];
					$model->rowvoltsmax[$y] = $val['voltsmax'];
					$model->rowampsavg[$y] = $val['ampsavg'];
					$model->rowampsmin[$y] = $val['ampsmin'];
					$model->rowampsmax[$y] = $val['ampsmax'];
					$model->rowspeedavg[$y] = $val['speedavg'];
					$model->rowspeedmin[$y] = $val['speedmin'];
					$model->rowspeedmax[$y] = $val['speedmax'];
					$model->rowinputkjavg[$y] = $val['inputkjavg'];
					$model->rowinputkjmin[$y] = $val['inputkjmin'];
					$model->rowinputkjmax[$y] = $val['inputkjmax'];
					$model->rowstrikeonavg[$y] = $val['strikeonavg'];
			//		$model->strikeonmin = $val['strikeonmin'];
			//		$model->strikeonmax = $val['strikeonmax'];
					$model->rowstrikeoffavg[$y] = $val['strikeoffavg'];
			//		$model->strikeoffmin = $val['strikeoffmin'];
			//		$model->strikeoffmax = $val['strikeoffmax'];
					$model->rowinterpassavg[$y] = $val['interpassavg'];
					$model->rowinterpassmin[$y] = $val['interpassmin'];
					$model->rowinterpassmax[$y] = $val['interpassmax'];
					$model->rowrowno[$y] = $val['rowno'];
					$model->rowstatus[$y] = 'Active';
				}
				$y++;
            }
            $model->curveradii = $cruverasdiis;
            $model->railgrade = $grade;
            $model->shiftstart = $shiftstart;
            $model->shiftend = $shiftend;
            $model->seniorwelder = $senior;
            $model->actualmeterage = $actual;
            $model->plannedmeterage = $planned;
            $model->assistant1 = $assist1;
            $model->assistant2 = $assist2;
            $model->assistant3 = $assist3;
            $model->filename = $object['filename'];
            $model->filedata = "data:".$mime.";base64,".base64_encode($contents);
            $model->validate();
            if($formModel->save()) {
                return $this->redirect(['update', 'id' => $formModel->id, 'form' => $form]);

            }
        } else {
            return 'Something Went Wrong';
        }
    }

    public function actionSendwitr($id, $form)
    {
        $model = $this->findModel($id, $form);
        $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 - Work Instruction and Technical Review');
        $pdf->setSubject('WITR');
        $pdf->WriteHTML($stylesheet,1);
        $pdf->WriteHTML($this->renderPartial('_dtwasv', ['model' => $model->data]));
        $content = $pdf->Output('', 'S');
        $content = base64_encode($content);

        //$queue->to_email1 = $model->email1;
        //$queue->to_email2 = $model->email2;
        foreach (explode(',', $model->activity->welder) as $key => $welder) {
            $operative = \frontend\models\User::find()->where(['username' => $welder])->one();
            if ($key == 0) {$queue->to_email3 = $operative->email;}
            if ($key == 1) {$queue->to_email4 = $operative->email;}
            if ($key == 2) {$queue->to_email5 = $operative->email;}
            if ($key == 3) {$queue->to_email6 = $operative->email;}
            if ($key == 4) {$queue->to_email7 = $operative->email;}
            if ($key == 5) {$queue->to_email8 = $operative->email;}
            if ($key == 6) {$queue->to_email9 = $operative->email;}
            if ($key == 7) {$queue->to_email10 = $operative->email;}
            if ($key == 8) {$queue->to_email11 = $operative->email;}
            if ($key == 9) {$queue->to_email12 = $operative->email;}
            if ($key == 10) {$queue->to_email13 = $operative->email;}
            if ($key == 11) {$queue->to_email14 = $operative->email;}
            if ($key == 12) {$queue->to_email15 = $operative->email;}
        }
        $queue->to_cc = "'NGauge@inlinetrack.co.uk'";
        $queue->subject = $model->data->emailsubject." ".$model->data->job->location;
        //$queue->from_email = ['Admin@InlineTrack.co.uk'=> 'Inline Track'];
        $queue->from_email = 'NGauge@InlineTrack.co.uk';
        $queue->from_name =  'Office Admin (Automated email – DO NOT REPLY –)';
        $queue->date_published = date("Y-m-d H:i:s.z");
        $filename = $model->data->emailsubject.'.pdf';
        $queue->filename = $filename;
        $queue->message = $this->renderPartial('//was/email', ['model' => $model->data]);;
        $queue->emailfile = base64_encode(gzcompress($content));
        $queue->save();
        $this->actionSendwitrext($id = $model->id, $form);
        $created = $queue->created_at;
        if (mailqueue::find()
    				->where(['created_at' => $created])
    				->exists()
        ) {
            return $this->render('/emaillayouts/emailsent');
        } else {
            return $this->render('/emaillayouts/notsent');
        }
	}




	public function actionSendwitrext($id, $form) {
        $model = $this->findModel($id, $form);
        $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 - Work Instruction and Technical Review');
        $pdf->setSubject('WITR');
        $pdf->WriteHTML($stylesheet,1);
        $pdf->WriteHTML($this->renderPartial('_dtwasv', ['model' => $model->data]));
        $content = $pdf->Output('', 'S');
        $content = base64_encode($content);
        $activity = $model->activity;
        !empty($activity->contactemail) ? $queue->to_email = $activity->contactemail : false;
        !empty($activity->contactemail2) ? $queue->to_email2 = $activity->contactemail2 : false;
        !empty($activity->contactemail3) ? $queue->to_email3 = $activity->contactemail3 : false;
        !empty($activity->contactemail4) ? $queue->to_email4 = $activity->contactemail4 : false;
        !empty($activity->contactemail5) ? $queue->to_email5 = $activity->contactemail5 : false;
        !empty($activity->contactemail6) ? $queue->to_email6 = $activity->contactemail6 : false;
        !empty($activity->contactemail7) ? $queue->to_email7 = $activity->contactemail7 : false;
        !empty($activity->contactemail8) ? $queue->to_email8 = $activity->contactemail8 : false;
        !empty($activity->contactemail9) ? $queue->to_email9 = $activity->contactemail9 : false;
        !empty($activity->contactemail10) ? $queue->to_email10 = $activity->contactemail10 : false;
        //$queue->to_email1 = $model->email1;
        $queue->to_cc = "'NGauge@InlineTrack.co.uk'";
        $queue->subject = $model->data->emailsubject." ".$model->data->job->location;
        $queue->from_email = 'NGauge@InlineTrack.co.uk';
        //$queue->from_email = ['Admin@InlineTrack.co.uk'=> 'Inline Track'];
        $queue->from_name =  'Office Admin (Automated email – DO NOT REPLY –)';
        $queue->date_published = date("Y-m-d H:i:s.z");
        $filename = $model->data->emailsubject.'.pdf';
        $queue->filename = $filename;
        $queue->message = $this->renderPartial('//was/emailex', ['model' => $model->data]);;
        $queue->emailfile = base64_encode(gzcompress($content));
        $queue->success = 0;
        $queue->save();
        Yii::$app->runAction('activities/jobbooked', ['id' => $model->actid]);
        $created = $queue->created_at;
        if (Mailqueue::find()
                        ->where(['created_at' => $created])
                        ->exists()
        ) {
            return $this->render('/emaillayouts/emailsent');
        } else {
            return $this->render('/emaillayouts/notsent');
        }
    }


    /**
     * Finds the DT123 model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Forms the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id, $form)
    {

        if (($model = Forms::findOne(['id' => $id, 'form' => $form]) ) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
 
}
