<?php

namespace modules\forms\models;

use Yii;
use modules\users\models\User;
use frontend\models\Settings;
use modules\forms\models\Dt179rows;

use modules\activities\models\Activities;
use modules\custom\models\Accounts;
use yii\base\Model;
use yii\helpers\Json;
/**
 * This is the model class For table "dt179".
 *
 * @property integer $id
 * @property string $date
 * @property string $employee1
 * @property string $employee2
 * @property string $welddepot
 * @property string $area
 * @property string $worksite
 * @property string $starttime
 * @property string $starttraveltime
 * @property string $finishtime
 * @property string $finishtraveltime
 * @property string $work
 * @property string $production
 * @property string $comments
 * @property string $client
 * @property string $siterepsignature
 * @property string $siterepprint
 */
class Dt179 extends Model {

    public $id;
    public $padno;
    public $date;
    public $employee1;
    public $employee2;
    public $welddepot;
    public $injobno;
    public $depot;
    public $area;
    public $worksite;
    public $starttime;
    public $starttraveltime;
    public $finishtime;
    public $finishtraveltime;
    public $work_;
    public $production;
    public $comments;
    public $client;
    public $siterepsignature;
    public $siterepprint;
    public $namecc;
    public $date1;
    public $date2;
    public $date3;
    public $date4;
    public $date5;
    public $date6;
    public $date7;
    public $clientpo;
    public $supplierjobno;
    public $weekno;
    public $break1;
    public $break2;
    public $break3;
    public $break4;
    public $break5;
    public $break6;
    public $break7;
    public $signbc;
    public $namebc;
    public $datebc;
    public $signsc;
    public $datesc;
    public $namesc;
    public $signcc;
    public $datecc;
    public $signatureloc;
    public $rowdata;
    public $deleted;
    public $created_by2;
    public $updated_by2;

    
    public $status;
    public $actid;
    public $updated_at;
    public $updated_by;
    public $created_at;
    public $created_by;
    public $deleted_at;
    public $deleted_by;
    public $tracktrolley;
    public $cpono;
    public $jobno;

    public $rowname =[];
    public $rowstatus =[];
    public $rowtrade =[];
    public $rowstart1 =[];
    public $rowfinish1 =[];
    public $rowdate1 =[];
    public $rowdate2 =[];
    public $rowdate3 =[];
    public $rowdate4 =[];
    public $rowdate5 =[];
    public $rowdate6 =[];
    public $rowdate7 =[];
    public $rowstart2 =[];
    public $rowfinish2 =[];
    public $rowstart3 =[];
    public $rowfinish3 =[];
    public $rowstart4 =[];
    public $rowfinish4 =[];
    public $rowstart5 =[];
    public $rowfinish5 =[];
    public $rowstart6 =[];
    public $rowfinish6 =[];
    public $rowstart7 =[];
    public $rowfinish7 =[];
    public $rowupdated_at =[];
    public $rowcreated_at =[];
    public $rowupdated_by =[];
    public $rowcreated_by =[];
    public $rowupdated_by2 =[];
    public $rowcreated_by2 =[];
    
    public $form = 'DT179';
    public $formname = 'Timesheet (DT179)';
    
    public $formLayout = '/dt179/_form.php';
    public $viewLayout = '@modules/forms/views/dt179/_view.php';
    public $formType = 'Other';
    public $createpath = '/forms/dt179/create';
    public $printlayout = 'landscape';
    
    

    /**
	 * @inheritdoc
	 */
    public function rules()
    {
        return [
            [['client','actid'], 'safe'],
            [[ 'injobno'], 'integer'],
            [['date', 'starttime', 'starttraveltime', 'finishtime', 'finishtraveltime', 'employee1', 'signatureloc', 'signcc', 'signbc', 'signsc','work_', 'production', 'comments', 'date1', 'date2', 'date3', 'date4', 'date5', 'date6', 'date7', 'break1', 'break2', 'break3', 'break4', 'break5', 'break6',
             'break7', 'namesc', 'namebc', 'weekno', 'depot', 'supplierjobno', 'datesc', 'datebc', 'datecc', 'namecc','clientpo', 'status', 'cpono', 'jobno', 'tracktrolley', 'deleted_by', ], 'string'], 
            [['rowname', 'rowstatus', 'rowtrade', 
                'rowdate1', 'rowstart1', 'rowfinish1',  
                'rowdate2', 'rowstart2', 'rowfinish2', 
                'rowdate3', 'rowstart3', 'rowfinish3', 
                'rowdate4', 'rowstart4', 'rowfinish4', 
                'rowdate5', 'rowstart5', 'rowfinish5', 
                'rowdate6', 'rowstart6', 'rowfinish6', 
                'rowdate7', 'rowstart7', 'rowfinish7', 
                'rowcreated_by2', 'rowupdated_by2', 'rowcreated_by', 'rowupdated_by', 'rowcreated_at', 
            ], 'safe'], 
            [['employee2', 'welddepot', 'area', 'worksite', 'siterepsignature', 'siterepprint', 'padno'], 'string', 'max' => 45],
            [['rowdata'], 'safe'],
            [['siterepprint', 'worksite'], 'required'],
            ['supplierjobno', 'required', 'message' =>'TO ENSURE PROMPT PAYMENT THE PURCHASE ORDER NUMBER MUST BE RECORDED'],
			//Defaults
			[['deleted'], 'boolean'],
			[['created_at', 'updated_at', 'deleted_at'], 'safe'],
			[['created_by', 'updated_by', 'id'],'safe'],
			//Redundant
			[['created_by2', 'updated_by2'], 'integer'],
        ];
    }

    /**
	 * @inheritdoc
	 */

    /*
    public function attributes()
    {
        return [
            'rowdate1' => 'rowdate1',
            'rowdate2' => 'rowdate2',
            'rowdate3' => 'rowdate3',
            'rowdate4' => 'rowdate4',
            'rowdate5' => 'rowdate5',
            'rowdate6' => 'rowdate6',
            'rowdate7' => 'rowdate7',
            'rowstart1' => 'rowstart1',
            'rowstart2' => 'rowstart2',
            'rowstart3' => 'rowstart3',
            'rowstart4' => 'rowstart4',
            'rowstart5' => 'rowstart5',
            'rowstart6' => 'rowstart6',
            'rowstart7' => 'rowstart7',
            'rowfinish1' => 'rowfinish1',
            'rowfinish2' => 'rowfinish2',
            'rowfinish3' => 'rowfinish3',
            'rowfinish4' => 'rowfinish4',
            'rowfinish5' => 'rowfinish5',
            'rowfinish6' => 'rowfinish6',
            'rowfinish7' => 'rowfinish7',
            'id' => 'id',
            'date' => 'date',
            'employee1' => 'employee1',
            'employee2' => 'employee2',
            'welddepot' => 'welddepot',
            'area' => 'area',
            'worksite' => 'worksite',
            'starttime' => 'starttime',
            'starttraveltime' => 'starttraveltime',
            'finishtime' => 'finishtime',
            'finishtraveltime' => 'finishtraveltime',
            'work_' => 'work_',
            'production' => 'production',
            'comments' => 'comments',
            'client' => 'client',
            'siterepsignature' => 'siterepsignature',
            'siterepprint' => 'siterepprint',
            'namecc' => 'namecc',
            'date1' => 'date1',
            'date2' => 'date2',
            'date3' => 'date3',
            'date4' => 'date4',
            'date5' => 'date5',
            'date6' => 'date6',
            'date7' => 'date7',
            'clientpo' => 'clientpo',
            'date' => 'date',
            'siterepprint' => 'siterepprint',
            'worksite' =>'worksite',
            'supplierjobno' => 'supplierjobno',
            'welddepot' => 'welddepot',

        ];
    }
    */
     
    public function attributeLabels()
    {
        return [
            'rowstart1' => 'Start',
            'rowstart2' => 'Start',
            'rowstart3' => 'Start',
            'rowstart4' => 'Start',
            'rowstart5' => 'Start',
            'rowstart6' => 'Start',
            'rowstart7' => 'Start',
            'rowfinish1' => 'Finish',
            'rowfinish2' => 'Finish',
            'rowfinish3' => 'Finish',
            'rowfinish4' => 'Finish',
            'rowfinish5' => 'Finish',
            'rowfinish6' => 'Finish',
            'rowfinish7' => 'Finish',
            'id' => 'ID',
            'date' => 'Date',
            'employee1' => 'Employee1',
            'employee2' => 'Employee2',
            'welddepot' => 'Welddepot',
            'area' => 'Area',
            'worksite' => 'Worksite',
            'starttime' => 'Starttime',
            'starttraveltime' => 'Starttraveltime',
            'finishtime' => 'Finishtime',
            'finishtraveltime' => 'Finishtraveltime',
            'work_' => 'Work',
            'production' => 'Production',
            'comments' => 'Comments',
            'client' => 'Client',
            'siterepsignature' => 'Siterepsignature',
            'siterepprint' => 'Client Contact',
            'namecc' => 'Client Name Print',
            'date1' => 'Saturday',
            'date2' => 'Sunday',
            'date3' => 'Monday',
            'date4' => 'Tuesday',
            'date5' => 'Wednesday',
            'date6' => 'Thursday',
            'date7' => 'Friday',
            'clientpo' => 'CLIENT PURCHASE ORDER No.',
            'date' => 'Weekending',
            'siterepprint' => 'Client Contact',
            'worksite' =>'WORK LOCATION',
            'supplierjobno' =>'SUPPLIER JOB REF (if required)',
            'welddepot' => 'CLIENT ISSUING DEPOT:'

        ];
    }
	
	public function getAccount() {
        return Accounts::findOne(['id' => $this->client]);
	}



    public function init(){
        if(Yii::$app->controller->action->id == 'create' && $this->actid !== null ){
            $act = Activities::findOne(['id' => $this->actid]);
            $this->worksite = $act->location;
            $this->weekno = $act->weekno;
           // $this->clientpo = $act->customerpono;
            //$this->injobno = $act->jobno;
            $this->clientpo = $act->customerpono;
            $this->supplierjobno = $act->jobno;
            $this->client = $act->relatedid;
        	$this->welddepot = $act->travelfinishtime;
        }
        return parent::init();
    }
    public static function hoursRange( $lower = 0, $upper = 86400, $step = 3600, $format = '' ) {
        $times = [];
        if ( empty( $format ) ) {
            $format = 'H:i ';
        }
        foreach ( range( $lower, $upper, $step ) as $increment ) {
            $increment = gmdate( 'H:i', $increment );
            list( $hour, $minutes ) = explode( ':', $increment );
            $date = new \DateTime( $hour . ':' . $minutes );
            $times[(string) $increment] = $date->format( $format );
        }
        return $times;
    }
    public function beforeValidate(){
        $this->padno = $this->padno == null ? User::Padno() : $this->padno;
        return parent::beforeValidate();
    }

        public static function adminFormButtons($buttons, $model){
      $_this = new self();
        $buttons[$_this->formType]['items'][] = [
            'label' => $_this->formname,
            'url' => [$_this->createpath, 'actid' => $model->id],
            'linkOptions' =>  ['target'=>'_blank'],
        ];
        return $buttons;
    }


    public static function Sitetimes($id){
		$x = 1;
		$total = 0;
		
        $forms = Forms::find()->where(['form' => 'DT179', 'actid' => $id])->all();
        foreach($forms as $key => $data){
            $model = $data->data;
            $x = 0;
            $total = 0;
            while($x < 10){
                $start1 = \Datetime::createfromFormat('d/m/Y H:i', $model->date1 .' '. $model->rowstart1[$x]); 
                $start2 = \Datetime::createfromFormat('d/m/Y H:i', $model->date2 .' '. $model->rowstart2[$x]); 
                $start3 = \Datetime::createfromFormat('d/m/Y H:i', $model->date3 .' '. $model->rowstart3[$x]); 
                $start4 = \Datetime::createfromFormat('d/m/Y H:i', $model->date4 .' '. $model->rowstart4[$x]); 
                $start5 = \Datetime::createfromFormat('d/m/Y H:i', $model->date5 .' '. $model->rowstart5[$x]); 
                $start6 = \Datetime::createfromFormat('d/m/Y H:i', $model->date6 .' '. $model->rowstart6[$x]); 
                $start7 = \Datetime::createfromFormat('d/m/Y H:i', $model->date7 .' '. $model->rowstart7[$x]); 
                $end1 = \Datetime::createfromFormat('d/m/Y H:i', $model->date1 .' '. $model->rowfinish1[$x]); 
                $end2 = \Datetime::createfromFormat('d/m/Y H:i', $model->date2 .' '. $model->rowfinish2[$x]); 
                $end3 = \Datetime::createfromFormat('d/m/Y H:i', $model->date3 .' '. $model->rowfinish3[$x]); 
                $end4 = \Datetime::createfromFormat('d/m/Y H:i', $model->date4 .' '. $model->rowfinish4[$x]); 
                $end5 = \Datetime::createfromFormat('d/m/Y H:i', $model->date5 .' '. $model->rowfinish5[$x]); 
                $end6 = \Datetime::createfromFormat('d/m/Y H:i', $model->date6 .' '. $model->rowfinish6[$x]); 
                $end7 = \Datetime::createfromFormat('d/m/Y H:i', $model->date7 .' '. $model->rowfinish7[$x]);
                
                $diff1 = is_object($start1) && is_object($end1) ? $start1->diff($end1) : 0;
                $diff2 = is_object($start2) && is_object($end2) ? $start2->diff($end2) : 0;
                $diff3 = is_object($start3) && is_object($end3) ? $start3->diff($end3) : 0;
                $diff4 = is_object($start4) && is_object($end4) ? $start4->diff($end4) : 0;
                $diff5 = is_object($start5) && is_object($end5) ? $start5->diff($end5) : 0;
                $diff6 = is_object($start6) && is_object($end6) ? $start6->diff($end6) : 0;
                $diff7 = is_object($start7) && is_object($end7) ? $start7->diff($end7) : 0;
                Yii::Warning($diff1 !== 0 ? $diff1->format('%h:%i') : '0', 'Diff1');
                $x++;
            }
        }

		$format = '%02d:%02d';
		$hours = floor($total / 60);
    	$minutes = ($total % 60);
   		return Json_encode(sprintf($format, $hours, $minutes));
		
	}
    
    public function actionTraveltimes($id){
			$x = 1;
		$total = 0;
		
			$start1 = new Query;
			$start1->select(["case when dt179rows.start1 > dt179rows.finish1 then DATEDIFF(mi, concat('2016-01-01 ',dt179rows.start1),concat('2016-01-02',' ',dt179rows.finish1)) else DATEDIFF(mi, concat('2016-01-01',' ',dt179rows.start1),concat('2016-01-01',' ',dt179rows.finish1)) end as diff1, dt179.actid, dbo.dt179rows.dt179id, dbo.dt179.created_at"])
			->join('right outer join', 'dt179', 'dt179.id = dt179rows.dt179id')
			->where(['=', 'dt179rows.dt179id', $id])
			->andwhere(['=', 'dt179rows.trade', 'Travel'])
			->from('dt179rows');
			
			
			$start2 = new Query;
			$start2->select(["case when dt179rows.start2 > dt179rows.finish2 then DATEDIFF(mi, concat('2016-01-01 ',dt179rows.start2),concat('2016-01-02',' ',dt179rows.finish2)) else DATEDIFF(mi, concat('2016-01-01',' ',dt179rows.start2),concat('2016-01-01',' ',dt179rows.finish2)) end as diff1, dt179.actid, dbo.dt179rows.dt179id, dbo.dt179.created_at"])
			->join('right outer join', 'dt179', 'dt179.id = dt179rows.dt179id')
			->where(['=', 'dt179rows.dt179id', $id])
			->andwhere(['=', 'dt179rows.trade', 'Travel'])
			->from('dt179rows');
			
			$start3 = new Query;
			$start3->select(["case when dt179rows.start3 > dt179rows.finish3 then DATEDIFF(mi, concat('2016-01-01 ',dt179rows.start3),concat('2016-01-02 ',dt179rows.finish3)) else DATEDIFF(mi, concat('2016-01-01',' ',dt179rows.start3),concat('2016-01-01',' ',dt179rows.finish3)) end as diff1, dt179.actid, dbo.dt179rows.dt179id, dbo.dt179.created_at"])
			->join('right outer join', 'dt179', 'dt179.id = dt179rows.dt179id')
			->where(['=', 'dt179rows.dt179id', $id])
			->andwhere(['=', 'dt179rows.trade', 'Travel'])
			->from('dt179rows');
			
			$start4 = new Query;
			$start4->select(["case when dt179rows.start4 > dt179rows.finish4 then DATEDIFF(mi, concat('2016-01-01 ',dt179rows.start4),concat('2016-01-02 ',dt179rows.finish4)) else DATEDIFF(mi, concat('2016-01-01',' ',dt179rows.start4),concat('2016-01-01',' ',dt179rows.finish4)) end as diff1, dt179.actid, dbo.dt179rows.dt179id, dbo.dt179.created_at"])
			->join('right outer join', 'dt179', 'dt179.id = dt179rows.dt179id')
			->where(['=', 'dt179rows.dt179id', $id])
			->andwhere(['=', 'dt179rows.trade', 'Travel'])
			->from('dt179rows');
			
			$start5 = new Query;
			$start5->select(["case when dt179rows.start5 > dt179rows.finish5 then DATEDIFF(mi, concat('2016-01-01 ',dt179rows.start5),concat('2016-01-02',' ',dt179rows.finish5)) else DATEDIFF(mi, concat('2016-01-01',' ',dt179rows.start5),concat('2016-01-01',' ',dt179rows.finish5)) end as diff1, dt179.actid, dbo.dt179rows.dt179id, dbo.dt179.created_at"])
			->join('right outer join', 'dt179', 'dt179.id = dt179rows.dt179id')
		->where(['=', 'dt179rows.dt179id', $id])
				->andwhere(['=', 'dt179rows.trade', 'Travel'])
			->from('dt179rows');
			
			$start6 = new Query();
$start6->select(["case when dt179rows.start6 > dt179rows.finish6 then DATEDIFF(mi, concat('2016-01-01 ',dt179rows.start6),concat('2016-01-02',' ',dt179rows.finish6)) else DATEDIFF(mi, concat('2016-01-01',' ',dt179rows.start6),concat('2016-01-01',' ',dt179rows.finish6)) end as diff1, dt179.actid, dbo.dt179rows.dt179id, dbo.dt179.created_at"])
			->join('right outer join', 'dt179', 'dt179.id = dt179rows.dt179id')
		->where(['=', 'dt179rows.dt179id', $id])
				->andwhere(['=', 'dt179rows.trade', 'Travel'])
			->from('dt179rows');
			
			$start7 = new Query();
$start7->select(["case when dt179rows.start7 > dt179rows.finish7 then DATEDIFF(mi, concat('2016-01-01 ',dt179rows.start7),concat('2016-01-02',' ',dt179rows.finish7)) else DATEDIFF(mi, concat('2016-01-01',' ',dt179rows.start7),concat('2016-01-01',' ',dt179rows.finish7)) end as diff1, dt179.actid, dbo.dt179rows.dt179id, dbo.dt179.created_at"])
			->join('right outer join', 'dt179', 'dt179.id = dt179rows.dt179id')
		->where(['=', 'dt179rows.dt179id', $id])
				->andwhere(['=', 'dt179rows.trade', 'Travel'])
			->from('dt179rows');
			
			$start1 =$start1->all();
			$start2 =$start2->all();
			$start3 =$start3->all();
			$start4 =$start4->all();
			$start5 =$start5->all();
			$start6 =$start6->all();
			$start7 =$start7->all();
			
			$start1  = Array_merge($start1, $start2,$start3,$start4,$start5,$start6,$start7);
			//	print_r($time);
			//print $s1 =  array_sum($start1);
			//$dt179rows[] = $start1;
			foreach ($start1 as $key1 => $row){
					$total  += $row['diff1'];
				
			}
		$format = '%02d:%02d';
		$hours = floor($total / 60);
    	$minutes = ($total % 60);
   		return Json_encode(sprintf($format, $hours, $minutes));
		
	}
}