<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\ActiveDataProvider;
use yii\data\ArrayDataProvider;

use app\base\Converter;
use app\models\Ostvisitnew;
use app\models\Linkidlinkage;
use app\models\Ostmonthreport;

/**
 * OstmonthreportController implements the CRUD actions for Ostmonthreport model.
 */
class OstmonthreportController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Arvmaster models.
     * @return mixed
     */
    public function actionIndex()	
    {
        $model = new Ostmonthreport();
		
		if ($model->load(Yii::$app->request->post()) || $model->load(Yii::$app->request->get())) {
            if(!$model->validate()) {
                return $this->render('index', ['model' => $model]);
            } else {
                $ostmodel = new Ostvisitnew();
                $linkmodel = new Linkidlinkage();
			    $osttable = Ostvisitnew::tableName();
                $frmdate = "01-".$model->month;
                $todate = self::last_day_of_the_month($frmdate);
                $frmdate = Converter::toUnixTimeformat($frmdate);
                if(date('m-Y') == date('m-Y', $frmdate))
                    $todate = strtotime(date('Y/m/d'));
                else
                    $todate = Converter::toUnixTimeformat($todate);

                $query = Ostvisitnew::find()->joinWith('otherids')->where(['between', Ostvisitnew::tableName().'.record_date', $frmdate, $todate])->orderBy(["length(ost_visit_part_id)" => SORT_ASC, "ost_visit_part_id" => SORT_ASC])->groupBy(["ost_visit_part_id"]);
                // $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => false, 'sort' => false]);

                $dispData = [];
                $totaldays = date("d", $todate);
                $title = "Monthly Distribution Chart for ".date("F - Y", $todate);
                $index = 0;
                $columns = [
                    ['class' => 'yii\grid\SerialColumn'],
                    [
                        'attribute' => 'ost_visit_part_id',
                        'label' => $ostmodel->getAttributeLabel('ost_visit_part_id')
                    ],
                    [
                        'attribute' => 'ost_visit_q1',
                        'label' => 'OST ID'
                    ],
                    [
                        'attribute' => 'link_idlinkage_q1',
                        'label' => $linkmodel->getAttributeLabel('link_idlinkage_q1'),
                    ],
                ];
                for($i = 1; $i <= $totaldays; $i++) {
                    if($i < 10)
                        $i = "0".$i;
                    $day = $i."-".$model->month;
                    $columns[] = ['attribute' => $i, 'label' => $i];
                }
                $columns[] = ['attribute' => 'total', 'label' => 'Total Taken'];
                $columns[] = ['attribute' => 'total_missed', 'label' => 'Total # Days Missed'];

                // $models = $dataProvider->getModels();
                $models = $query->all();
                foreach ($models as $key => $value) {
                    $dispData[$index]['ost_visit_part_id'] = $value->ost_visit_part_id;
                    $dispData[$index]['ost_visit_q1'] = $value->ost_visit_q1;
                    if($value->otherids && $value->otherids->link_idlinkage_q1 != '')
                        $dispData[$index]['link_idlinkage_q1'] = $value->otherids->link_idlinkage_q1;
                    else
                        $dispData[$index]['link_idlinkage_q1'] = "-";
                    $sum = 0;
                    $tmiss = 0;
                    for($i = 1; $i <= $totaldays; $i++) {
                        if($i < 10)
                            $i = "0".$i;
                        $day = $i."-".$model->month;
                        $Model = Ostvisitnew::find()->where(['ost_visit_part_id' => $value->ost_visit_part_id, 'ost_visit_q7' => Converter::toUnixTimeformat($day)])->one();
                        if($Model !== null) {
                            $sum += $Model->ost_visit_q5;
                            $dispData[$index][$i] = $Model->ost_visit_q5;
                        }
                        else {
                            $dispData[$index][$i] = "-";
                            $tmiss++;
                        }
                    }
                    $dispData[$index]['total'] = number_format($sum, 2, '.', '');
                    $dispData[$index]['total_missed'] = $tmiss;
                    $index++;
                }

                $provider = new ArrayDataProvider(['allModels' => $dispData]);
                return $this->render('index', ['model' => $model, 'dataProvider' => $provider, 'columns' => $columns, 'title' => $title]);
            }
        }
        return $this->render('index', ['model' => $model]);  
    }

    function last_day_of_the_month($date = '')
    {
        $month  = date('m', strtotime($date));
        $year   = date('Y', strtotime($date));
        $result = strtotime("{$year}-{$month}-01");
        $result = strtotime('-1 second', strtotime('+1 month', $result));
        return Converter::toDisplay($result);
    }
}
