<?php

namespace modules\forms\controllers;

use Yii;
use yii\helpers\Url;
use frontend\models\Dt_WAS;
use frontend\models\WASsearch;
use frontend\models\Mailqueue;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use Mpdf\mPdf;
use yii\filters\AccessControl;
use modules\custom\models\Contacts;;
use yii\helpers\json;
use yii\base\Model; 
use frontend\models\Dtpdf;
/**
 * WASController implements the CRUD actions for dt_WAS model.
 */
class WasController extends Controller {

public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::class,
                'rules' => [
                    [
                        'actions' => ['undelete', 'deleted', 'purge'],
                        'allow' => true,
                        'matchCallback' => function ($rule, $action) {
                    	    if (!yii::$app->user->isGuest) {
                	            return yii::$app->user->identity->useradv->accesslevel >= 9;
							} else { 
						   		return $this->redirect(['site/login']);
	                        }
                        }
                    ],
                    [
                        'actions' => ['create','index', 'delete','pdf','send', 'view', 'update', 'addrow','deleterow','savefield', 'kpi'],
                        'allow' => true,
                        'matchCallback' => function ($rule, $action) {
                    	    if (!yii::$app->user->isGuest) {
                	            return yii::$app->user->identity->useradv->accesslevel >= 2;
							} else { 
						   		return $this->redirect(['site/login']);
	                        }
                        }
                    ],
            	],
                'denyCallback' => function ($rule, $action) {
				   	if (yii::$app->user->isGuest) {
				   		return $this->redirect(['site/login']);
					} else {
				   		return $this->redirect(['site/accessdenied']);
					   	
					}
				}
            
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }
 	public function beforeAction($action) {
   		$id = yii::$app->request->get('id');
		Yii::$app->runaction('/audit/qcreate', ['id' => $id ? $id : null , 'controller' =>  Yii::$app->controller->id, 'action' => Yii::$app->controller->action->id, 'attributes' => null]);
		return parent::beforeAction($action);
	}

    /**
     * Lists all dt_WAS models.
     * @return mixed
     */
         public function actionContacts() {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
            
            if ($parents != null) {
                $cat_id = $parents[0];
                $out = Contacts::getcontactswas($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>']
                // ]
                echo Json::encode(['output'=>$out, 'selected'=>'']);
                return;
            }
        }
        echo Json::encode(['output'=>'', 'selected'=>'']);
    }
    
    public function actionIndex()
    {
        $searchModel = new WASsearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionContact()
    {
        $data = contacts::find()->where(['=','accountid','4'])->asArray()->all();
        return print_r($data);
    }
    
    
    
    
   public function actionSend($id)
    {
    $model = $this->findModel($id);
   	$queue = new MailQueue();
   	 	$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('_view', ['model' => $this->findModel($id)]));
	$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 = "'admin@inlinetrack.co.uk', 'GaryStevens@Inlinetrack.co.uk'";
    $queue->subject = $model->emailsubject." ".$model->job->location;
    //$queue->from_email = ['Admin@InlineTrack.co.uk'=> 'Inline Track'];
    $queue->from_email = 'Admin@InlineTrack.co.uk';
    $queue->from_name =  'Office Admin';
    $queue->date_published = date("Y-m-d H:i:s.z");
    $filename = $model->emailsubject.'.pdf';
    $queue->filename = $filename;
    $queue->message = $this->renderPartial('email', ['model' => $model]);;
    $queue->emailfile = $content;
    $queue->save(); 
	$this->actionSendext($id = $model->id);
   	$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 actionSendext($id) {
	$model = $this->findModel($id);
   	$queue = new MailQueue();
 	$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('_view', ['model' => $this->findModel($id)]));
	$content = $pdf->Output('', 'S');
	$content = base64_encode($content);
	
   	if (isset($model->activity->contactemail)) {$queue->to_email = $model->activity->contactemail;};
   	if (isset($model->activity->contactemail2)) {$queue->to_email2 = $model->activity->contactemail2;};
   	if (isset($model->activity->contactemail3)) {$queue->to_email3 = $model->activity->contactemail3;};
   	if (isset($model->activity->contactemail4)) {$queue->to_email4 = $model->activity->contactemail4;};
   	if (isset($model->activity->contactemail5)) {$queue->to_email5 = $model->activity->contactemail5;};
   	if (isset($model->activity->contactemail6)) {$queue->to_email6 = $model->activity->contactemail6;};
   	if (isset($model->activity->contactemail7)) {$queue->to_email7 = $model->activity->contactemail7;};
   	if (isset($model->activity->contactemail8)) {$queue->to_email8 = $model->activity->contactemail8;};
   	if (isset($model->activity->contactemail9)) {$queue->to_email9 = $model->activity->contactemail9;};
   	if (isset($model->activity->contactemail10)) {$queue->to_email10 = $model->activity->contactemail10;};
    //$queue->to_email1 = $model->email1;
    $queue->to_cc = "'admin@inlinetrack.co.uk', 'GaryStevens@Inlinetrack.co.uk'";
    $queue->subject = $model->emailsubject." ".$model->job->location;
    $queue->from_email = 'Admin@InlineTrack.co.uk';
    //$queue->from_email = ['Admin@InlineTrack.co.uk'=> 'Inline Track'];
    $queue->from_name =  'Office Admin';
    $queue->date_published = date("Y-m-d H:i:s.z");
    $filename = $model->emailsubject.'.pdf';
    $queue->filename = $filename;
    $queue->message = $this->renderPartial('emailex', ['model' => $model]);;
    $queue->emailfile = $content;
    $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');										
					}
   
 }
    /**
     * Displays a single dt_WAS model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
    public function actionViewn($id)
    {
        return $this->render('viewn', [
            'model' => $this->findModel($id),
        ]);
    }
    /**
     * Creates a new dt_WAS model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionSaveSend()
    {
        $model = new dt_WAS();
        $dtpdf = new Dtpdf();

      if ($model->load(Yii::$app->request->post()) && $dtpdf->load(Yii::$app->request->post()) && Model::validateMultiple([$model, $dtpdf])) {
            $model->save(false); // skip validation as model is already validated
			$created = $model->created_at;
			$id = dt_WAS::findBySql("SELECT id FROM dt_WAS where created_at = $created")->scalar(); 
        	$dtpdf->jobno = $model->jcnno;
        	//$dtpdf->welder = $model->weldersname;
        	$dtpdf->form = 'Welding Arrangement Sheet';
			$dtpdf->url = "was";
        	//$dtpdf->actid = $model->id;
        	$dtpdf->formid = $id;
        	$dtpdf->save();
        	//$content = $this->renderPartial('email', ['model' => $model]); 
        	//Yii::$app->mailer->compose()
    		//->setFrom(['Admin@InlineTrack.co.uk' => 'Office Admin'])
     		//->setTo('a.pickstock@chalvingtongroup.com')
			//->setTo(array($model->email1, $model->email2, $model->email3, $model->email4, $model->email5, $model->email6, $model->email7, $model->email8, $model->email9, $model->email10,  $model->pcemail1,  $model->pcemail2, $model->pcemail3,  $model->pcemail4,  $model->pcemail5, 'admin@inlinetrack.co.uk', 'GaryStevens@Inlinetrack.co.uk'))
     		//->setCc(array($model->pcemails))
			//->setHtmlBody($content)
     		//->setSubject('Work Alert')
     		//->send();
     		//$emails = $model->email1,"; ",$model->email2,"; ",$model->email3,"; ",$model->email4,"; ",$model->email5,"; ",$model->email6,"; ",$model->email7,"; ",$model->email8,"; ",$model->email9,"; ",$model->email10,"; ",$model->pcemail1,"; ",$model->pcemail2,"; ",$model->pcemail3,"; ",$model->pcemail4,"; ",$model->pcemail5;
    $queue = new MailQueue();
    $queue->to_email1 = $model->email1;
    $queue->to_email2 = $model->email2;
    $queue->to_email3 = $model->email3;
    $queue->to_email4 = $model->email4;
    $queue->to_email5 = $model->email5;
    $queue->to_email6 = $model->email6;
    $queue->to_email7 = $model->email7;
    $queue->to_email8 = $model->email8;
    $queue->to_email9 = $model->email9;
    $queue->to_email10 = $model->email10;
    $queue->to_email11 = $model->pcemail1;
    $queue->to_email12 = $model->pcemail2;
    $queue->to_email13 = $model->pcemail3;
    $queue->to_email14 = $model->pcemail4;
    $queue->to_email15 = $model->pcemail5;
    //$queue->to_email1 = $model->email1;
    $queue->to_cc = "'admin@inlinetrack.co.uk', 'GaryStevens@Inlinetrack.co.uk'";
    $queue->subject = 'Work Alert';
    $queue->from_email = ['Admin@InlineTrack.co.uk'=> 'Inline Track'];
    $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 = 1;  //will be set to 0 on send.
    $queue->message = $this->renderPartial('email', ['model' => $model]);
    $queue->save(); 
			return $this->redirect(['view', 'id' => $id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    
    public function actionCreate()
        {
        $model = new DT_WAS();
			$model->planneddate = date('d-m-Y', strtotime('now'));
			$model->signdate = date('d-m-Y', strtotime('now'));

		$act = \modules\activities\models\Activities::find()->where(['id' => yii::$app->request->get('actid')])->one();
		if ($act) {		
	        $model->jcnno = strval($act->jobno);
			$model->actid =  $act->id;
			$model->company =  $act->company;

		}	

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        	$model->padno = Yii::$app->runaction('/user/padno');
			
        	$model->save(false); // skip validation as model is already validated
	        $model = DT_WAS::find()->where(['created_at' => $model->created_at, 'created_by' => $model->created_by])->one();
		 	
        	
        	$dtpdf = new Dtpdf();
			$dtpdf->actid = $model->actid;
            $dtpdf->jobno = $model->jcnno;
        	//$dtpdf->welder = $model->insepectorid;
        	$dtpdf->form = 'Work Instruction and Technical Review';
			$dtpdf->url = "was";
        	//$dtpdf->actid = $model->id;
        	$dtpdf->formid = $model->id;
        	$dtpdf->save();
			return $this->redirect(['view', 'id' => $model->id]);
        } elseif ($model->errors) {
        	return Print_r($model->errors);
			
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    public function actionCreaten()
        {
        $model = new DT_WAS();
        $dtpdf = new Dtpdf();

      if ($model->load(Yii::$app->request->post()) && $dtpdf->load(Yii::$app->request->post()) && Model::validateMultiple([$model, $dtpdf])) {
            $model->save(false); // skip validation as model is already validated
        	$created = $model->created_at;
			$id = dt_was::findBySql("SELECT id FROM dt_was where created_at = $created")->scalar(); 
			$model->actid = $dtpdf->actid;
            $dtpdf->jobno = $model->jcnno;
        	//$dtpdf->welder = $model->insepectorid;
        	$dtpdf->form = 'Work Instruction and Technical Review';
			$dtpdf->url = "was";
        	//$dtpdf->actid = $model->id;
        	$dtpdf->formid = $id;
        	$dtpdf->save();
			return $this->redirect(['view', 'id' => $id]);
        } else {
            return $this->render('createn', [
                'model' => $model,
                'dtpdf' => $dtpdf
            ]);
        }
    	}

    
    public function actionPdf($id) {
 	$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('_view', ['model' => $this->findModel($id)]));
    $pdf->output();
}

	
	/**
     * Updates an existing dt_WAS model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    
    
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $userrole = Yii::$app->user->identity->role;
    	

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
        	return $this->redirect(['view', 'id' => $model->id]);
        } if ($userrole != 'Engineer') {
            //if ($model->welder !== array())
            //$weldertags = explode(',', $model->welder);
  			//$model->welder = $weldertags;
            return $this->render('update', ['model' => $model]);
        } else {
			return $this->redirect(['view', 'id' => $model->id]);
		}
    }
	/**
     * Deletes an existing dt_WAS model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
       public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $model->deleted_at = strtotime('now');
        $model->deleted = TRUE;
        $model->save();
        return $this->redirect(['index']);
    }
    public function actionUndelete($id)
    {
        $model = $this->findModel($id);
        $model->deleted_at = null;
        $model->deleted = null;
        $model->save();
        return $this->redirect(['index']);
    }

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

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