<?php

namespace modules\custom\controllers;

use Yii;
use modules\custom\models\Assetsbe;
use modules\custom\models\Assetsbesearch;
use modules\activities\models\Activitiesitemsbe;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * AssetsController implements the CRUD actions for assetsbe model.
 */
class AssetController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

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

        return $this->render('index', [
        	'title' => 'Assets',
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionDates()
    {
        $searchModel = new Assetsbesearch();
        $dataProvider = $searchModel->servicedates(Yii::$app->request->queryParams);

        return $this->render('servicedates', [
        	'title' => 'Service Dates',
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
     
    public function actionDuplicates()
    {
        $searchModel = new Assetsbesearch();
        $dataProvider = $searchModel->Duplicates(Yii::$app->request->queryParams);

        return $this->render('index', [
        	'title' => 'Assets',
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionDiscounted()
    {
        $searchModel = new Assetsbesearch();
        $searchModel->discountservice = true;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
		return $this->render('index', [
        	'title' => 'Assets with Discounts',
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }    
    public function actionNeedsservice()
    {
        $searchModel = new Assetsbesearch();
        $dataProvider = $searchModel->ServiceSearch(Yii::$app->request->queryParams,  90);
		return $this->render('index', [
        	'title' => 'Assets Needing Service',
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    public function actionNeedsserviceemails()
    {
        $searchModel = new Assetsbesearch();
        $dataProvider = $searchModel->ServiceSearchEmail(Yii::$app->request->queryParams,  90);
		return $this->render('index', [
        	'title' => 'Assets Needing Service',
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }


	public function actionImplrserials() {
		$serials = \backend\models\Liferaftserialsbe::find()->all();
		$count = 0;
		$output = [];
		foreach ($serials as $key => $serial) {
			$i = $serial->N1;
			while($i <= $serial->N2) {
				$asset = new \backend\models\Assetsbe();
				$asset->dom = $serial->Date;
				$asset->serialnumber = '0'.$i.$serial->Code;
				$asset->assettype = 'liferaft';
				$asset->model = $serial->model;
				$asset->productid = $serial->ProductID;
				$asset->packed = $serial->Canister;
				$asset->capacity = $serial->Capacity;
				if ($asset->save()) {
				$output['save'][] = ['saved' => $asset->serialnumber];
				} else {
				$output['error'][] = ['saved' => $i.$serial->Code];
					
				}
				$i++;
				$count++;
			}
			
		}
		return print_r($output);	
	}
	
    /**
     * Displays a single assetsbe model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
    
    public function actionViewbatch($orderno) {
        $batch = \backend\models\Assetsbe::find()->where(['=', 'orderno', $orderno])->orderby(['seagoserialnumber' => SORT_ASC])->all();
        return $this->render('viewbatch', [
            'batch' => $batch,
        ]);
    }    
    public function actionPrintbatch($orderno) {
        $batch = \backend\models\Assetsbe::find()->where(['=', 'orderno', $orderno])->asArray()->all();
        return $this->render('printbatch', ['batch' => $batch,]);
    }
	public function actionPdf($orderno) {
   		$batch = \backend\models\Assetsbe::find()->where(['=', 'orderno', $orderno])->asArray()->all();
        $content = $this->renderPartial('printbatch', ['batch' => $batch,]);
    	$pdf = new \Mpdf\Mpdf([
		    'mode' => 'utf-8', //Pdf::MODE_CORE, // leaner size using standard fonts
	    	'format' => 'A4', 
	        'margin_top' => 0,
	        'margin_header' => 0,
	        'margin_left' => 0,
	        'margin_right' => 0,
	        'margin_footer' => 0,
	        'margin_bottom' => 0,
	   	]);
     	//$pdf->autoPadding = true;
    	$pdf->SetTitle('Wireframe');
	 	$pdf->SetSubject('Wireframe');
		$stylesheet = file_get_contents('css/styles.css');
 		$pdf->WriteHTML($stylesheet,1);
   		//$pdf->simpleTables = true;
   	//	$pdf->SetHTMLFooter($this->renderPartial('//pdfs/genfooter', ['model' => $model]));
	//	$pdf->SetHTMLHeader($this->renderPartial('//pdfs/genheader', ['title' => 'wireframe']));
		//$pdf->WriteHTML($content); 
		$pdf->WriteHTML(utf8_encode($content));
		$pdf->Output();
		
	}
    /**
     * Creates a new Assetsbe model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new Assetsbe();
		$model->id = Assetsbe::tempid();
        $data = $model->data;
		if (($clientid = Yii::$app->request->get('clientid')) !== null){
			$model->clientid = $clientid;	
		}
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'data' => $data,
            ]);
        }
    }
    public function actionCreatebatch() {
        $model = new Assetsbe();
        $qty = 0;
        if ($model->load(Yii::$app->request->post())) {
			$i = 0;
			$qty = $model->qty;
         	$array = [];
         	$model->save();
         	$model = assetsbe::find()->where(['=', 'created_at', $model->created_at])->andWhere(['=', 'created_by', $model->created_by])->one();
        	while( $i <= $qty) {
        		$newasset = new Assetsbe();
        		$newasset->attributes = $model->attributes;
        		unset($newasset->seagoserialnumber);
        		unset($newasset->id);
        		$newasset->isNewRecord = true;
				if ($newasset->save()) {
					$array['saved'][] = ['SN' => $newasset->seagoserialnumber];
				} else {
					$array['errors'][] = [$model->errors];
				}
				$i++;
			}
            if (isset($array['errors'])) {
				if (count($array['errors']) > 0) {
					return print_r($array);
				}
			} else {
            	return $this->redirect(['viewbatch', 'orderno' => $model->orderno]);
			}
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing assetsbe model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);
        $data = $model->data;
        if ($data->load(Yii::$app->request->post()) && $model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'data' => $data,
            ]);
        }
    }

    /**
     * Deletes an existing assetsbe model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

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


    public function actionImportfromserviceitems(){
        $items = Activitiesitemsbe::find()->where(['not', ['serial' => ['',  null]]])
        //->limit(100)
        ->all();
        foreach($items as $key => $item){
            $asset = Assetsbe::find()->where(['serialnumber' => $item->serial])->one();
            if($asset == false){
                $asset = Assetsbe::create($item->id);
            } else {
                $asset->updateasset($item->id);
            }
            $item->updateAttributes(['assetid' => $asset->id]);
        }
    }


    public function actionMerge(){
        Yii::$app->response->format = 'json';
        
        $fromAssets = Assetsbe::find()->where(['in', 'id', Yii::$app->request->post('mergeFrom')])->asArray()->all();
        $toAssets = Assetsbe::find()->where(['in', 'assets.id', Yii::$app->request->post('mergeTo')])->joinwith('product')->asArray()->One();

        return ['body' => $this->renderAjax('_merge', ['fromAssets' => $fromAssets, 'toAssets' => $toAssets])];
    }
    public function actionMergedata(){
        Yii::$app->response->format = 'json';
        if(yii::$app->request->isPost){
            $post_data = Yii::$app->request->post();
            parse_str(urldecode($post_data['options']), $options);
            $data = array_merge([
                'from' => json_decode($post_data['from'], 1),
                'to' => $post_data['to'],
            ], $options);
            return Assetsbe::MergeAssets($data);
        }
        throw new notFoundHttpException('not found', 404);
        //return ['body' => $this->renderAjax('_merge')];
    }

    public function actionFindforms($id){
        $model = $this->findModel($id);
        $model->findandLinkSerivices();
        return $this->redirect(Yii::$app->request->referrer);
    }

    public function actionPushsn(){
        /*
        $items = \modules\activities\models\Activitiesitemsbe::find()
        ->where(['not', ['serial'=> ['', null]]])
        ->orderby(['serial' => SORT_ASC])
        ->offset(6001)
        ->limit(5000)
        ->all();
        
foreach($items as $k => $item) {
    $model = $item->updateForm();
}
*/
$items = \modules\activities\models\Activitiesitemsbe::find()
        ->where(['>', new \yii\db\Expression("length(serial)"), 0])
        ->andwhere(['is', 'assetid', null])
        ->orderby(['assetid' => SORT_ASC])
        ->all();         
        foreach($items as $k => $item) {
            $asset = \modules\custom\models\Assetsbe::findorCreate(
                    [
                        'email' => $item->activity?->email, 
                        'serial' => $item->serial, 
                        'status' => 'Active', 
                        'productid' => $item->product,
                        'clientid' => $item->activity?->client?->id,
                        'date_of_purchase' => null, 
                        'type' => $item->type,
                    ]
                );
            $item->updateAttributes(['assetid' => $asset->id]);
        }
    }

    public function actionCheckdates(){
        $servicedate  = new \yii\db\Expression("json_value(`assets`.`data`, '$.last_service')");
        $nservicedate  = new \yii\db\Expression("json_value(`assets`.`data`, '$.next_service')");
        $assets = Assetsbe::find()
            ->where(['assettype' => ['liferaft', 'lifejacket']])
            ->andWhere(['or', ['is', $servicedate, null], ['=', $servicedate, ''],['is', $nservicedate, null], ['=', $nservicedate, '']]);
        foreach($assets->each() as $key => $asset) {
            $ls = json_decode($asset->getLastservice(),0);
            $asset->save();
        }
    }

    
    public function actionCheckdates2(){
        
        $nservicedate  = new \yii\db\Expression("json_value(`assets`.`data`, '$.next_service')");
        $firstservicedate  = new \yii\db\Expression("json_value(`assets`.`data`, '$.first_service')");
        $assets = Assetsbe::find()
            ->where(['assettype' => ['liferaft', 'lifejacket']])
            ->andWhere(['or', ['is', $firstservicedate, null], ['=', $firstservicedate, ''],['is', $nservicedate, null], ['=', $nservicedate, '']]);
        foreach($assets->each() as $key => $asset) {
            $asset->save();
        }
    }
    public function actionCheckdates3(){
        
        $nservicedate  = new \yii\db\Expression("json_value(`assets`.`data`, '$.next_service')");
        $firstservicedate  = new \yii\db\Expression("json_value(`assets`.`data`, '$.first_service')");
        $assets = Assetsbe::find()
            ->where(['assettype' => ['liferaft', 'lifejacket']])
            ->andwhere('JSON_VALUE(data, "$.last_service") > JSON_value(data, "$.next_service")')
            ->all();
        foreach($assets as $key => $asset) {
            $model = $asset->data;
            $model->next_service = $asset->assettype == 'lifejacket' ?  date('Y-m-d', strtotime('+1 years', strtotime(str_replace('/', '-', $model->last_service)))) 
                : ($asset->assettype == 'liferaft' ? date('Y-m-d', strtotime('+3 years', strtotime(str_replace('/', '-', $model->last_service)))) : null);
            $asset->data = $model;
            $asset->save();
        }
    }

    
    public function actionCheckdates4(){
        $assets = Assetsbe::find()
        ->where(['assettype' => ['lifejacket', 'liferaft']])
        ->all();
        foreach($assets as $key => $asset) {
            $years = $asset->assettype == 'lifejacket' ? 2 :3;
            $model = $asset->data;
           // $asset->data = $model;
            $ls = $asset->getLastservice();
            $model->last_service = $ls?->date;
            if(!empty($asset->purchasedate)){
                $model->first_service = !empty($asset->purchasedate) ? date('Y-m-d', strtotime("+$years years", strtotime(str_replace('/', '-', $asset->purchasedate)))) : $model->first_service;
                $model->next_service = $ls?->date_of_next_service !== null ? $ls?->date_of_next_service : $model->first_service;
            } else {
                $model->first_service = !empty($asset->purchasedate) ? date('Y-m-d', strtotime("+$years years")) : $model->first_service;
                $model->next_service = $ls?->date_of_next_service !== null ? $ls?->date_of_next_service : $model->first_service;
            }
            $asset->updateAttributes(['data' => json_encode($model)]); // $asset->data = $model
        }
    }
    public function actionCheckdates5(){
        $assets = Assetsbe::find()
        ->where(['assettype' => ['lifejacket', 'liferaft']])
        ->all();
        foreach($assets as $key => $asset) {
            $asset->findandLinkSerivices();
        }
    }



    public function actionNodata(){
        foreach(Assetsbe::find()->where(['=', 'data', '{}'])->all() as $k => $model){
            $model->save();
        }
    }
    public function actionCreateReminders()
    {
        Yii::$app->queue->jobname('Service Reminders')->push(new \modules\custom\jobs\ServiceReminders());
        yii::$app->session->setFlash('success', 'Service Reminders Job Created');
        return $this->redirect(Yii::$app->request->referrer);
    }
    public function actionFindAsset($q){
        Yii::$app->response->format = 'json';
        $query = new \yii\db\Query;
        $query->select(['id', 'serialnumber', 'assettype', 'productid', 'name'])
            ->from('assets')
            ->where('serialnumber LIKE "'. $q .'%"')
            ->andWhere(['status' => 'Active'])
            ->orderBy('serialnumber');
        $command = $query->createCommand();
        $data = $command->queryAll();
        $out = [];
        foreach ($data as $d) {
            $out[$d['id']] = [
                'value' => $d['id'], 
                'productid' => $d['productid'], 
                'assettype' => $d['assettype'], 
                'text' => $d['name'],
                'serial' => $d['serialnumber'],
                'text' => $d['serialnumber'] . ' - '. $d['name']
            ];
        }
        $out[null] = [
            'value' => $q, 
            'productid' => null, 
            'assettype' => null, 
            'text' => $q,
            'serial' => $q,
            'text' =>  $q,
        ];
        return $out;
    }
}
