<?php

namespace backend\modules\hr\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\User;
use backend\models\CronJobHistory;
use backend\modules\hr\models\Attendancestaff;
use backend\modules\rch\models\GeneralModel as General;
/**
 * Default controller for the `site` module
 */
class AttendancestaffController extends Controller {
    public function behaviors() {
        $roles = array_keys(Yii::$app->authManager->getRoles());

        if (($key = array_search('App User', $roles)) !== false) {
            unset($roles[$key]);
        }

        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' =>  ['@']
                    ]
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function beforeAction($action) {
        $this->enableCsrfValidation = false;
        return parent::beforeAction($action);
    }

    public function actionIndex() {
        $session = Yii::$app->session;
        $userId = \Yii::$app->user->identity->id;
        $objUser = new User();
        $user = $objUser->getUserByUserId($userId);

        $diseases = Yii::$app->params['attendance_staff'];
        $attendance_type= Yii::$app->params['attendance_type'];
        $categories = Yii::$app->params['attendance_staff_detail'];
        $startDate =  date('Y-m-01');
        $endDate =  date('Y-m-d');
        $diseaseName = 'All';
        $diseaseValue = 'd1';
        $rangeType = 'weekly';
        // default filter text setting by logged in user.
        $countryId = $user['country'];
        $stateId = $user['state'];
        $districtId = $user['district'];
        $talukaId = $user['taluka'];
        $phcId = $user['phc'];
        $villageId = $user['village'];
        $centerId = $user['center_id'];
        $tblHeader = $isExport = $filterType = $selectedColumn = $locationLabel ='';
        $locationChange = $flgColumnSelected = 0;
        $arrColHeader = $categories[$diseaseValue];
        $arrColumn = array_keys($categories[$diseaseValue]);
        $postedData = $getTabularData = $totalData = array();

        if (Yii::$app->request->post()) {
            $postedData = Yii::$app->request->post();

//echo "<pre>"; print_r($postedData); die;

            if (isset($postedData['start'])) {
                $startDate = $postedData['start'];
            }
            if (isset($postedData['finish'])) {
                $endDate = $postedData['finish'];
            }
          /*  if (isset($postedData['disease'])) {
                $diseaseValue = $postedData['disease'];
                $diseaseName = $diseases[$diseaseValue];
            }
            if (isset($postedData['disease1'])) {
                $diseaseValue1 = $postedData['disease1'];
                $diseaseName1 = $diseases1[$diseaseValue1];
            }
            if (isset($postedData['disease2'])) {
                $diseaseValue2 = $postedData['disease2'];
                $diseaseName2 = $diseases2[$diseaseValue];
            }
            if (isset($postedData['disease3'])) {
                $diseaseValue3 = $postedData['disease3'];
                $diseaseName3 = $diseases3[$diseaseValue];
            }*/
            if (isset($postedData['rangeType'])) {
                $rangeType = $postedData['rangeType'];
            }
            if (isset($postedData['ftCountry'])) {
                $stateId = $postedData['ftCountry'];
                $locationText = $postedData['ftCountry'];
                $locationType = 'ftCountry';
            }
            if (isset($postedData['ftState'])) {
                $stateId = $postedData['ftState'];
                $locationText = $postedData['ftState'];
                $locationType = 'ftState';
            }
            if (isset($postedData['ftDistrict'])) {
                $districtId = $postedData['ftDistrict'];
                $locationText = $postedData['ftDistrict'];
                $locationType = 'ftDistrict';
            }
            if (isset($postedData['ftSubDistrict'])) {
                $talukaId = $postedData['ftSubDistrict'];
            }
            if (isset($postedData['ftPhc'])) {
                $phcId = $postedData['ftPhc'];
            }
            if (isset($postedData['export']) && !empty($postedData['export']) ) {
                $isExport = $postedData['export'];
            }

            $arrColumn = array_keys($categories[$diseaseValue]);
            if (isset($postedData['column_key']) && !empty($postedData['column_key'])) {
                unset($arrColumn);
                $arrColumn[] = $postedData['column_key'];
                if (isset($postedData['ftSubDistrict']) && !empty($postedData['ftSubDistrict'])) {
                    $arrColumn[] = $postedData['column_key'].'_mids';
                } else {
                    $arrColumn[] = str_replace('_complaint', '_disposed', $postedData['column_key']);
                    $arrColumn[] = str_replace('_complaint', '_pending', $postedData['column_key']);
                }

                $flgColumnSelected = $postedData['column_key'];
                $selectedColumn = $postedData['column_key'];
            }
            $locationChange = $postedData['location_change'];
            $filterType = $postedData['chart_filter_type'];
            $filterText = $postedData['filterText'];
            $tblHeader = $postedData['tbl_header'];
            $rangeSlot = $postedData['rangeSlot'];
        } else {
            $filterText = '';
            if (Yii::$app->user->can('Super Admin')) {
                $filterType = $locationText =  'ftCountry';
                $filterText = $locationType = $countryId;
            } else if (Yii::$app->user->can('Country Admin') || Yii::$app->user->can('Country Admin RO')) {
                $filterType = $locationType = 'ftCountry';
                $filterText = $locationText =$countryId;
            } else if (Yii::$app->user->can('State Admin') || Yii::$app->user->can('State Admin RO')) {
                $filterType = $locationType = 'ftState';
                $filterText = $locationText =$stateId;
            } else if (Yii::$app->user->can('District Admin') || Yii::$app->user->can('District Admin RO')) {
                $filterType = $locationType ='ftDistrict';
                $filterText = $locationText = $districtId;
            } else if(Yii::$app->user->can('Taluka Admin') || Yii::$app->user->can('Taluka Admin RO')) {
                $filterType = 'ftSubDistrict';
                $filterText = $talukaId;
                $locationType = 'ftDistrict';
                $locationText = $districtId;
            } else if(Yii::$app->user->can('PHC Admin') || Yii::$app->user->can('PHC Admin RO')) {
                $filterType = 'ftPhc';
                $filterText = $phcId;
            }
            $rangeSlot = false;
        }

     //   $hrGr    = new Attendancestaff();
        $attendancestaff    = new Attendancestaff();
        $objGeneral = new General();
        $ranges = $objGeneral->getDateRanges($startDate, $endDate, $rangeType);
        $startDate = $objGeneral->getFormattedDateTime($startDate, 'Upper');
        $endDate = $objGeneral->getFormattedDateTime($endDate, 'Lower');

        $str = substr($filterType, 2);
        switch (strtolower($str)) {
            case 'country':
                $locationLabel = 'States';
                break;
            case 'state':
                $locationLabel = 'Districts / Corporations';
                break;
            case 'district':
                $locationLabel = 'SubDistricts / Zones';
                break;
            case 'subdistrict':
                $locationLabel = 'PHC / UHC';
                break;
        }
        // DEFINE NEW RANGE BASED ON RANGESLOT SELECTION
        if ($locationChange && $rangeSlot !== false) {
            $newRange = $ranges[$rangeSlot];
            switch (strtolower($rangeType)) {
                case 'yearly':
                    $rangeType = 'monthly';
                    break;
                case 'monthly':
                    $rangeType = 'weekly';
                    break;
                case 'weekly':
                    $rangeType = 'daily';
                    break;
                default:
                    $rangeType = 'daily';
                    break;
            }
            $ranges = $objGeneral->getDateRanges($newRange['start_date'], $newRange['end_date'], $rangeType);
            $startDate = $objGeneral->getFormattedDateTime($newRange['start_date'], 'Upper');
            $endDate = $objGeneral->getFormattedDateTime($newRange['end_date'], 'Lower');
        }

       /* if ($filterType == 'ftSubDistrict') {
            //$totalData = $hrGr->grSummary($filterType, $filterText, $startDate, $endDate);
            $getTabularData = $hrGr->grVlTabularData($filterType, $filterText, $startDate, $endDate, $arrColumn, $ranges, $flgColumnSelected, $isExport, $categories, $diseaseName);
        } else {
            //$totalData = $hrGr->grSummary($filterType, $filterText, $startDate, $endDate);
            $getTabularData = $hrGr->grTabularData($filterType, $filterText, $startDate, $endDate, $arrColumn, $ranges, $flgColumnSelected, $isExport, $arrColHeader, $locationLabel, $rangeType, $tblHeader, $diseaseName, false);
        }*/

        $arrSummary = $this->getSummary();
        $arrLocations = $objGeneral->getLocationHierarchy($locationType, $locationText, false, true, null);
        $locationName = $objGeneral->getLocationHierarchy($filterType, $filterText, true, false, null);

        $controllerId = Yii::$app->controller->id;
        list($filterLabel, $arrPlaces, $arrHierarchy) = $objGeneral->getFilterList($locationType, $locationText, $controllerId);

        $cronHistory = CronJobHistory::find()
            ->where(['=','cron_code','HR_GRIEVANCE_REDRESSAL'])
            ->asArray()
            ->one();
        if (!empty($cronHistory)) {
            $lastRunDatetime = $cronHistory['last_run_datetime'];
            $session->set('cron_last_run_date', date('d-m-Y h:i A',strtotime($lastRunDatetime)) );
        }

        return $this->render('index', [
            'ranges' => $ranges,
            'rangeType' => $rangeType,
            'arrSummary' => $arrSummary,
            'arrPlaces' => $arrPlaces,
            'filterType' => $filterType,
            'filterText' => $filterText,
            'disease_name' => $diseaseName,
            'location_label' => $locationLabel,
            'location_name' => $locationName,
            'location_change' => $locationChange,
            'flgColumnSelected' => $flgColumnSelected,
            'selectedColumn' => $selectedColumn,
            'filterLabel' => $filterLabel,
            'arrHierarchy' => $arrHierarchy,
            'arrLocations' => $arrLocations,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'disease_value' => $diseaseValue,
            'diseases' => $diseases,
            'attendance_type' => $attendance_type,
            'tbl_header' => $tblHeader,
            'get_tabularData' => $getTabularData,
            'pageHeading' => 'attendancestaff'
        ]);
    }

    private function getSummary() {
        return array(
            array(
                'label' => '% AWC Open',
                'counter' => 0,
                'bg-color' => 'bg-red',
                'color' => '',
                'icon' => 'fa fa-chart-bar'
            ),
            array(
                'label' => '% Mini AWC Open',
                'counter' => 0,
                'bg-color' => 'bg-blue',
                'color' => '',
                'icon' => 'fa fa-chart-bar'
            ),
            array(
                'label' => '% Children Present 3 Years to 5 Years',
                'counter' => 0,
                'bg-color' => 'bg-green',
                'color' => '',
                'icon' => 'fa fa-chart-bar'
            ),
            array(
                'label' => '% Children Present 5 Years to 6 Years',
                'counter' => 0,
                'bg-color' => 'bg-orange',
                'color' => '',
                'icon' => 'fa fa-chart-bar'
            ),  
            array(
                'label' => '% of Office Staff Present',
                'counter' => 0,
                'bg-color' => 'bg-blue',
                'color' => '',
                'icon' => 'fa fa-chart-bar'
            ),
            array(
                'label' => '% AWW& Helper present',
                'counter' => 0,
                'bg-color' => 'bg-green',
                'color' => '',
                'icon' => 'fa fa-chart-bar'
            ),
            array(
                'label' => '%of Beneficiary Provided Supplimentry Food',
                'counter' => 0,
                'bg-color' => 'bg-red',
                'color' => '',
                'icon' => 'fa fa-chart-bar'
            ),
            array(
                'label' => '%of beneficiary Provided Take Home Rashan',
                'counter' => 0,
                'bg-color' => 'bg-blue',
                'color' => '',
                'icon' => 'fa fa-chart-bar'
            ),
          
        );
    }

    public function actionBarChart()
    {
        $diseases = Yii::$app->params['awc'];
        $chart = 'column';
        $title = "Total Beneficiary Using Govt. Health Facilities Vs Total Family Registered";
        $reportID = 'r1';
        $userId = \Yii::$app->user->identity->id;
        $objUser = new User();
        $user = $objUser->getUserByUserId($userId);
        $objGeneral = new General();
        $awcReport = new Attendancestaff();
       //    $awcReport = new Awc();
        $categories = Yii::$app->params['awc_detail'];
        $startDate =  date('Y-m-01');
        $endDate =  date('Y-m-d');
        $diseaseName = 'All';
        $diseaseValue = 'd1';
        $rangeType = 'weekly';
        // default filter text setting by logged in user.
        $countryId = $user['country'];
        $stateId = $user['state'];
        $districtId = $user['district'];
        $talukaId = $user['taluka'];
        $phcId = $user['phc'];
        $centerId = $user['center_id'];
        $arrColumn = array_keys($categories[$diseaseValue]);
        $postedData = $getTabularData = $totalData = $arrPlace  = $total = $series = $beneficiary = $unverified = array();
        $filterType = $selectedColumn = $filterType = $selectedColumn = '';
        $flgColumnSelected = 0;

        if (Yii::$app->request->post()) {
            $postedData = Yii::$app->request->post();
            $filterType = $postedData['chart_filter_type'];
            $filterText = $postedData['filterText'];
            $tblHeader = $postedData['tbl_header'];

            if (isset($postedData['start'])) {
                $startDate = $postedData['start'];
            }
            if (isset($postedData['finish'])) {
                $endDate = $postedData['finish'];
            }
            if (isset($postedData['disease'])) {
                $diseaseValue = $postedData['disease'];
                $diseaseName = $diseases[$diseaseValue];
            }
            if (isset($postedData['rangeType'])) {
                $rangeType = $postedData['rangeType'];
            }
            if (isset($postedData['ftState'])) {
                $stateId = $postedData['ftState'];
            }
            if (isset($postedData['ftDistrict'])) {
                $districtId = $postedData['ftDistrict'];
            }
            if (isset($postedData['ftSubDistrict'])) {
                $talukaId = $postedData['ftSubDistrict'];
            }
            if (isset($postedData['ftPhc'])) {
                $phcId = $postedData['ftPhc'];
            }
            if (isset($postedData['ftCenter'])) {
                $centerId = $postedData['ftCenter'];
            }
            if (isset($postedData['ftVillage'])) {
                $filterType = 'ftCenter';
                $filterText = $centerId;
            }
            if (isset($postedData['reportID'])) {
                $reportID = $postedData['reportID'];
            }
            if (isset($postedData['column_key']) && !empty($postedData['column_key'])) {
                $flgColumnSelected = $postedData['column_key'];
                $selectedColumn = $postedData['column_key'];
            }
        } else {
            $filterText = '';
            if (Yii::$app->user->can('Super Admin')) {
                $filterType = "ftCountry";
                $filterText = $countryId;
            } else if (Yii::$app->user->can('Country Admin') || Yii::$app->user->can('Country Admin RO')) {
                $filterType = "ftCountry";
                $filterText = $countryId;
            } else if (Yii::$app->user->can('State Admin') || Yii::$app->user->can('State Admin RO')) {
                $filterType = "ftState";
                $filterText = $stateId;
            } else if (Yii::$app->user->can('District Admin') || Yii::$app->user->can('District Admin RO')) {
                $filterType = "ftDistrict";
                $filterText = $districtId;
            } else if (Yii::$app->user->can('Taluka Admin') || Yii::$app->user->can('Taluka Admin RO')) {
                $filterType = "ftSubDistrict";
                $filterText = $talukaId;
            } else if (Yii::$app->user->can('PHC Admin') || Yii::$app->user->can('PHC Admin RO')) {
                $filterType = "ftPhc";
                $filterText = $phcId;
            } else {
                $filterType = "ftCenter";
                $filterText = $centerId;
            }
        }
        $start_date = $objGeneral->getFormattedDateTime($startDate, 'Upper');
        $end_date = $objGeneral->getFormattedDateTime($endDate, 'Lower');
        $ranges = $objGeneral->getDateRanges($startDate, $endDate, $rangeType);

        $str = substr($filterType, 2);
        switch (strtolower($str)) {
            case 'country':
                $locationLabel = "States";
                break;
            case 'state':
                $locationLabel = "Districts / Corporations";
                break;
            case 'district':
                $locationLabel = "SubDistricts / Zones";
                break;
            case 'subdistrict':
                $locationLabel = "PHC / UHC";
                break;
            case 'phc':
                $locationLabel = "Centers";
                break;
            case 'center':
                $locationLabel = "Villages / Area";
                break;
            case 'village':
                $locationLabel = "Members / Name";
                break;
        }

        $categories = Yii::$app->params['awc_chart'];
        $arrColumn = array_keys($categories);

        if ($filterType == 'ftPhc') {
            $totalData = $awcReport->awcSummary($filterType, $filterText, $start_date, $end_date, $diseaseValue);
            $getTabularData = $awcReport->awcChartData($filterType, $filterText, $start_date, $end_date, $arrColumn, $ranges, $flgColumnSelected, $rangeType, $reportID, true, null);
        } else {
            $totalData = $awcReport->awcSummary($filterType, $filterText, $start_date, $end_date, $diseaseValue);
            $getTabularData = $awcReport->awcChartData($filterType, $filterText, $start_date, $end_date, $arrColumn, $ranges, $flgColumnSelected, $rangeType, $reportID, false, null);
        }

        foreach ($getTabularData as $arrData) {
            $arrPlace[] = $arrData['sName'];
        }

        $arrSummary = $this->getSummary($totalData);

        $locationName = $objGeneral->getLocationHierarchy($filterType, $filterText, true, false, null);
        $arrLocations = $objGeneral->getLocationHierarchy($filterType, $filterText, false, true, null);
        $controller_id = Yii::$app->controller->id;
        list($filterLabel, $arrPlaces, $arrHierarchy) = $objGeneral->getFilterList($filterType, $filterText, $controller_id);

        if ($reportID == 'r1') {
            foreach ($getTabularData as $arrData) {
                $beneficiary[] = (int)$arrData['beneficiary_govt_health'];
                $total[] = (int)$arrData['family_registered'];
            }
            $series = array(
                array(
                    'name' => 'Total Family Registered',
                    'data' => $total,
                ),
                array(
                    'name' => 'Total Beneficiary Using Govt. Health Facilities',
                    'data' => $beneficiary
                )
            );
            $title = 'Total Beneficiary Using Govt. Health Facilities Vs Total Family Registered';
        } else if ($reportID == 'r2') {
            foreach ($getTabularData as $arrData) {
                $beneficiary[] = (int)$arrData['beneficiary_govt_kg'];
                $total[] = (int)$arrData['family_registered'];
            }
            $series = array(
                array(
                    'name' => 'Total Family Registered',
                    'data' => $total,
                ),
                array(
                    'name' => 'Total Beneficiary Using Govt. KG.',
                    'data' => $beneficiary
                )
            );
            $title = 'Total Beneficiary Using Govt. KG. Vs Total Family Registered';
        } else if ($reportID == 'r3') {
            foreach ($getTabularData as $arrData) {
                $beneficiary[] = (int)$arrData['beneficiary_govt_schools'];
                $total[] = (int)$arrData['family_registered'];
            }
            $series = array(
                array(
                    'name' => 'Total Family Registered',
                    'data' => $total,
                ),
                array(
                    'name' => 'Total Beneficiary Using Govt. Schools',
                    'data' => $beneficiary
                )
            );
            $title = 'Total Beneficiary Using Govt. Schools Vs Total Family Registered';
        } else if ($reportID == 'Only') {
            foreach ($getTabularData as $arrData) {
                $unverified[] = isset($arrData['unverified']) ? intval($arrData['unverified']) : 0;
            }
            $series = array(
                array(
                    'name' => 'Total Families Unverified',
                    'data' => $unverified
                )
            );
            $title = 'Total Families Unverified '.$locationLabel. ' Wise';
        }

        return $this->render('@backend/views/layouts/bar-chart', [
            'location_name' => $locationName,
            'location_label' => $locationLabel,
            'arrSummary' => $arrSummary,
            'arrPlaces' => $arrPlaces,
            'filterLabel' => $filterLabel,
            'arrHierarchy' => $arrHierarchy,
            'disease_name' => $diseaseName,
            'categories' => array_values($arrPlace),
            'series' => $series,
            'chart' => $chart,
            'title' => $title,
            'reportID' => $reportID,
            'arrLocations' => $arrLocations,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'rangeType' => $rangeType,
            'disease_value' => $diseaseValue,
            'diseases' => $diseases,
            'filterType' => $filterType,
            'filterText' => $filterText,
            'tbl_header' => $tblHeader,
            'selectedColumn' => $selectedColumn,
            'pageHeading' => 'AWC',
            'reports' => Yii::$app->params['awc_report_bar_report']
        ]);
    }

    public function actionPieChart()
    {
        $diseases = Yii::$app->params['awc'];
        $reportID = 'r1';
        $userId = \Yii::$app->user->identity->id;
        $objUser = new User();
        $user = $objUser->getUserByUserId($userId);

       // $ancReg = new Awc();
        $ancReg = new Attendancestaff();
        $objGeneral = new General();
        $categories = Yii::$app->params['awc_detail'];
        $startDate =  date('Y-m-01');
        $endDate =  date('Y-m-d');
        $diseaseName = 'All';
        $diseaseValue = 'd1';
        $rangeType = 'weekly';
        // default filter text setting by logged in user.
        $countryId = $user['country'];
        $stateId = $user['state'];
        $districtId = $user['district'];
        $talukaId = $user['taluka'];
        $phcId = $user['phc'];
        $villageId = $user['village'];
        $centerId = $user['center_id'];
        $arrColumn = array_keys($categories[$diseaseValue]);
        $postedData = $getTabularData = $totalData = array();
        $filterType = $selectedColumn = '';
        $flgColumnSelected = 0;

        if (Yii::$app->request->post()) {
            $postedData = Yii::$app->request->post();
            $filterType = $postedData['chart_filter_type'];
            $filterText = $postedData['filterText'];
            $tblHeader = $postedData['tbl_header'];

            if (isset($postedData['start'])) {
                $startDate = $postedData['start'];
            }
            if (isset($postedData['finish'])) {
                $endDate = $postedData['finish'];
            }
            if (isset($postedData['disease'])) {
                $diseaseValue = $postedData['disease'];
                $diseaseName = $diseases[$diseaseValue];
            }
            if (isset($postedData['rangeType'])) {
                $rangeType = $postedData['rangeType'];
            }
            if (isset($postedData['ftState'])) {
                $stateId = $postedData['ftState'];
            }
            if (isset($postedData['ftDistrict'])) {
                $districtId = $postedData['ftDistrict'];
            }
            if (isset($postedData['ftSubDistrict'])) {
                $talukaId = $postedData['ftSubDistrict'];
            }
            if (isset($postedData['ftPhc'])) {
                $phcId = $postedData['ftPhc'];
            }
            if (isset($postedData['ftCenter'])) {
                $centerId = $postedData['ftCenter'];
            }
            if (isset($postedData['ftVillage'])) {
                $villageId = $postedData['ftVillage'];
                $filterType = 'ftCenter';
                $filterText = $centerId;
            }
            if (isset($postedData['reportID'])) {
                $reportID = $postedData['reportID'];
            }
            if (isset($postedData['column_key']) && !empty($postedData['column_key'])) {
                $flgColumnSelected = $postedData['column_key'];
                $selectedColumn = $postedData['column_key'];
            }
        } else {
            $filterText = '';
            if (Yii::$app->user->can('Super Admin')) {
                $filterType = "ftCountry";
                $filterText = $countryId;
            } else if (Yii::$app->user->can('Country Admin') || Yii::$app->user->can('Country Admin RO')) {
                $filterType = "ftCountry";
                $filterText = $countryId;
            } else if (Yii::$app->user->can('State Admin') || Yii::$app->user->can('State Admin RO')) {
                $filterType = "ftState";
                $filterText = $stateId;
            } else if (Yii::$app->user->can('District Admin') || Yii::$app->user->can('District Admin RO')) {
                $filterType = "ftDistrict";
                $filterText = $districtId;
            } else if (Yii::$app->user->can('Taluka Admin') || Yii::$app->user->can('Taluka Admin RO')) {
                $filterType = "ftSubDistrict";
                $filterText = $talukaId;
            } else if (Yii::$app->user->can('PHC Admin') || Yii::$app->user->can('PHC Admin RO')) {
                $filterType = "ftPhc";
                $filterText = $phcId;
            } else {
                $filterType = "ftVillage";
                $filterText = $villageId;
            }
        }
        $start_date = $objGeneral->getFormattedDateTime($startDate, 'Upper');
        $end_date = $objGeneral->getFormattedDateTime($endDate, 'Lower');
        $ranges = $objGeneral->getDateRanges($startDate, $endDate, $rangeType);

        $str = substr($filterType, 2);
        switch (strtolower($str)) {
            case 'country':
                $locationLabel = "States";
                break;
            case 'state':
                $locationLabel = "Districts / Corporations";
                break;
            case 'district':
                $locationLabel = "SubDistricts / Zones";
                break;
            case 'subdistrict':
                $locationLabel = "PHC / UHC";
                break;
            case 'phc':
                $locationLabel = "Centers";
                break;
            case 'center':
                $locationLabel = "Villages / Area";
                break;
            case 'village':
                $locationLabel = "Members / Name";
                break;
        }
        $categories = Yii::$app->params['awc_chart'];
        $arrColumn = array_keys($categories);

        if ($filterType == 'ftCenter') {
            $totalData = $ancReg->awcSummary($filterType, $filterText, $start_date, $end_date, $diseaseValue);
            $getTabularData = $ancReg->awcChartData($filterType, $filterText, $start_date, $end_date, $arrColumn, $ranges, $flgColumnSelected, $rangeType, $reportID, true, null);
        } else {
            $totalData = $ancReg->awcSummary($filterType, $filterText, $start_date, $end_date, $diseaseValue);
            $getTabularData = $ancReg->awcChartData($filterType, $filterText, $start_date, $end_date, $arrColumn, $ranges, $flgColumnSelected, $rangeType, $reportID, false, null);
        }

        $arrPlace = $diedComp = $series = array();

        foreach ($getTabularData as $arrData) {
            $arrPlace[] = $arrData['sName'];
        }
        $arrSummary = $this->getSummary($totalData);

        $locationName = $objGeneral->getLocationHierarchy($filterType, $filterText, true, false, null);
        $arrLocations = $objGeneral->getLocationHierarchy($filterType, $filterText, false, true, null);
        $controller_id = Yii::$app->controller->id;
        list($filterLabel, $arrPlaces, $arrHierarchy) = $objGeneral->getFilterList($filterType, $filterText, $controller_id);

        $series = array(
            array(
                'name' => $diseaseName,
                'colorByPoint' => true,
                'data' => array()
            )
        );
        if ($reportID == 'r1') {
            $series[0]['name'] = 'Total Families Unverified';
            foreach ($getTabularData as $arrData) {
                $diedComp[] = $arrData['unverified'];
            }
            foreach ($arrPlace as $key => $location) {
                $tmp = (int)$diedComp[$key];
                $series[0]['data'][] = [
                    'name' => $location,
                    'y' => $tmp,
                ];
            }
            $title = 'Total Families Unverified Vs Total of All '.$locationLabel;
        }

        return $this->render('@backend/views/layouts/pie-chart', [
            'location_name' => $locationName,
            'location_label' => $locationLabel,
            'arrSummary' => $arrSummary,
            'arrPlaces' => $arrPlaces,
            'filterLabel' => $filterLabel,
            'arrHierarchy' => $arrHierarchy,
            'disease_name' => $diseaseName,
            'categories' => array_values($arrPlace),
            'series' => $series,
            'title' => $title,
            'reportID' => $reportID,
            'arrLocations' => $arrLocations,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'rangeType' => $rangeType,
            'disease_value' => $diseaseValue,
            'diseases' => $diseases,
            'filterType' => $filterType,
            'filterText' => $filterText,
            'tbl_header' => $tblHeader,
            'selectedColumn' => $selectedColumn,
            'pageHeading' => 'AWC',
            'reports' => Yii::$app->params['awc_report_pie_report']
        ]);
    }

    public function actionLineChart()
    {
        $diseases = Yii::$app->params['awc'];
        $title = "Different Facilities";
        $reportID = 'district_wise';
        $userId = \Yii::$app->user->identity->id;
        $objUser = new User();
        $user = $objUser->getUserByUserId($userId);

        $objGeneral = new General();
        //$ancReg = new Awc();
        $ancReg = new Attendancestaff();
        $categories = Yii::$app->params['awc_detail'];
        $startDate =  date('Y-m-01');
        $endDate =  date('Y-m-d');
        $diseaseName = 'All';
        $diseaseValue = 'd1';
        $rangeType = 'weekly';
        // default filter text setting by logged in user.
        $countryId = $user['country'];
        $stateId = $user['state'];
        $districtId = $user['district'];
        $talukaId = $user['taluka'];
        $phcId = $user['phc'];
        $villageId = $user['village'];
        $centerId = $user['center_id'];
        $arrColumn = array_keys($categories[$diseaseValue]);
        $lineModel = $categories[$diseaseValue];

        $postedData = $getTabularData = $totalData = $series = $place = array();
        $filterType = $selectedColumn = $tblHeader = $selectedColumn  = '';
        $flgColumnSelected = 0;
        
        if (Yii::$app->request->post()) {
            $postedData = Yii::$app->request->post();
            $filterType = $postedData['chart_filter_type'];
            $filterText = $postedData['filterText'];
            $tblHeader = $postedData['tbl_header'];
            if (isset($postedData['start'])) {
                $startDate = $postedData['start'];
            }
            if (isset($postedData['finish'])) {
                $endDate = $postedData['finish'];
            }
            if (isset($postedData['disease'])) {
                $diseaseValue = $postedData['disease'];
                $diseaseName = $diseases[$diseaseValue];
            }
            if (isset($postedData['rangeType'])) {
                $rangeType = $postedData['rangeType'];
            }
            if (isset($postedData['ftState'])) {
                $stateId = $postedData['ftState'];
            }
            if (isset($postedData['ftDistrict'])) {
                $districtId = $postedData['ftDistrict'];
            }
            if (isset($postedData['ftSubDistrict'])) {
                $talukaId = $postedData['ftSubDistrict'];
            }
            if (isset($postedData['ftPhc'])) {
                $phcId = $postedData['ftPhc'];
            }
            if (isset($postedData['ftCenter'])) {
                $centerId = $postedData['ftCenter'];
            }
            if (isset($postedData['ftVillage'])) {
                $villageId = $postedData['ftVillage'];
                $filterType = 'ftCenter';
                $filterText = $centerId;
            }
            if (isset($postedData['reportID'])) {
                $reportID = $postedData['reportID'];
            }
            if (isset($postedData['column_key']) && !empty($postedData['column_key'])) {
                unset($arrColumn);
                $arrColumn[] = $postedData['column_key'];
                if (isset($postedData['ftVillage'])) {
                    $arrColumn[] = $postedData['column_key'] . "_member_ids";
                }
                $flgColumnSelected = $postedData['column_key'];
                $selectedColumn = $postedData['column_key'];
            }
        } else {
            $filterText = '';
            if (Yii::$app->user->can('Super Admin')) {
                $filterType = "ftCountry";
                $filterText = $countryId;
            } else if (Yii::$app->user->can('Country Admin') || Yii::$app->user->can('Country Admin RO')) {
                $filterType = "ftCountry";
                $filterText = $countryId;
            } else if (Yii::$app->user->can('State Admin') || Yii::$app->user->can('State Admin RO')) {
                $filterType = "ftState";
                $filterText = $stateId;
            } else if (Yii::$app->user->can('District Admin') || Yii::$app->user->can('District Admin RO')) {
                $filterType = "ftDistrict";
                $filterText = $districtId;
            } else if (Yii::$app->user->can('Taluka Admin') || Yii::$app->user->can('Taluka Admin RO')) {
                $filterType = "ftSubDistrict";
                $filterText = $talukaId;
            } else if (Yii::$app->user->can('PHC Admin') || Yii::$app->user->can('PHC Admin RO')) {
                $filterType = "ftPhc";
                $filterText = $phcId;
            } else {
                $filterType = "ftVillage";
                $filterText = $villageId;
            }
        }
        $start_date = $objGeneral->getFormattedDateTime($startDate, 'Upper');
        $end_date = $objGeneral->getFormattedDateTime($endDate, 'Lower');
        $ranges = $objGeneral->getDateRanges($startDate, $endDate, $rangeType);

        $str = substr($filterType, 2);
        switch (strtolower($str)) {
            case 'country':
                $locationLabel = "States";
                break;
            case 'state':
                $locationLabel = "Districts / Corporations";
                break;
            case 'district':
                $locationLabel = "SubDistricts / Zones";
                break;
            case 'subdistrict':
                $locationLabel = "PHC / UHC";
                break;
            case 'phc':
                $locationLabel = "Centers";
                break;
            case 'center':
                $locationLabel = "Villages / Area";
                break;
            case 'village':
                $locationLabel = "Members / Name";
                break;
        }
        $categories = Yii::$app->params['awc_linechart'];
        $arrColumn = array_keys($categories);

        if ($filterType == 'ftPhc') {
            $totalData = $ancReg->awcSummary($filterType, $filterText, $start_date, $end_date, $diseaseValue);
            $getTabularData = $ancReg->awcChartData($filterType, $filterText, $start_date, $end_date, $arrColumn, $ranges, $flgColumnSelected, $rangeType, $reportID, true, 'lineChart');
        } else {
            $totalData = $ancReg->awcSummary($filterType, $filterText, $start_date, $end_date, $diseaseValue);
            $getTabularData = $ancReg->awcChartData($filterType, $filterText, $start_date, $end_date, $arrColumn, $ranges, $flgColumnSelected, $rangeType, $reportID, false, 'lineChart');
        }
        $arrPlace = $series = $date = array();
        $arrSummary = $this->getSummary($totalData);

        $locationName = $objGeneral->getLocationHierarchy($filterType, $filterText, true, false, null);
        $arrLocations = $objGeneral->getLocationHierarchy($filterType, $filterText, false, true, null);
        $controller_id = Yii::$app->controller->id;
        list($filterLabel, $arrPlaces, $arrHierarchy) = $objGeneral->getFilterList($filterType, $filterText, $controller_id);

        $ranges = $objGeneral->getDateRanges($startDate, $endDate, $rangeType);
        $chartHeading = Yii::$app->params['awc_linechart'];
        if ($reportID == 'disease_wise') {
            foreach ($getTabularData as $place) {
                $name = $place['sName'];
                unset($place['sName'], $place['id']);

                $series[] = [
                    'name' => $name,
                    'data' => array_values($place)
                ];
            }
            $date = array_keys($place);
            $title = Yii::$app->params['awc_detail']['d1'][$flgColumnSelected] . ' With Different ' . $locationLabel;
        } else {
            if (!empty($getTabularData)) {
                foreach ($getTabularData as $tableData) {
                    foreach ($chartHeading as $key => $value) {
                        $arrValue[$key][] = $value;
                        foreach ($tableData as $dValue) {
                            $arrValue[$key][] = (int)$dValue[$key];
                        }
                    }
                }
                $date = array_keys($tableData);
            } else {
                foreach ($chartHeading as $key => $value) {
                    $arrValue[$key][] = $value;
                    foreach ($ranges as $range) {
                        $arrValue[$key][] = (int) 0;
                    }
                }
                foreach ($ranges as $range) {
                    $startOrg = date('d-m-Y', strtotime($range['start_date']));
                    $endOrg = date('d-m-Y', strtotime($range['end_date']));
                    $dateRange = ($rangeType == 'daily') ? $startOrg : $startOrg . ' / ' . $endOrg;
                    $date[] = $dateRange;
                }
            }
            foreach ($arrValue as $place) {
                $name = $place[0];
                unset($place[0]);

                $series[] = [
                    'name' => $name,
                    'data' => array_values($place)
                ];
            }
            $title = 'Different Facilities With Same '.$str;
        }
        $series = array_values($series);

        return $this->render('@backend/views/layouts/line-chart', [
            'location_name' => $locationName,
            'location_label' => $locationLabel,
            'arrSummary' => $arrSummary,
            'arrPlaces' => $arrPlaces,
            'filterLabel' => $filterLabel,
            'arrHierarchy' => $arrHierarchy,
            'disease_name' => $diseaseName,
            'categories' => array_values($arrPlace),
            'series' => $series,
            'title' => $title,
            'reportID' => $reportID,
            'ranges' => array_values($ranges),
            'arrLocations' => $arrLocations,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'rangeType' => $rangeType,
            'disease_value' => $diseaseValue,
            'diseases' => $diseases,
            'filterType' => $filterType,
            'filterText' => $filterText,
            'selectedColumn' => $selectedColumn,
            'lineModel' => $lineModel,
            'tbl_header' => $tblHeader,
            'date' => array_values($date),
            'pageHeading' => 'AWC',
            'reports' => Yii::$app->params['awc_report_line_report']
        ]);
    }   

    public function actionCronJob() {
        /*$rootPath = dirname(__DIR__, 4);
        $cronHistory = CronJobHistory::find()
            ->where(['=','cron_code','HR_GRIEVANCE_REDRESSAL'])
            ->asArray()
            ->one();

        if (!empty($cronHistory)) {
            $session = Yii::$app->session;
            $lastRunDatetime = $cronHistory['last_run_datetime'];
            $session->set('cron_last_run_date', date('d-m-Y h:i A',strtotime($lastRunDatetime)) );
        }
        system('php '.$rootPath.'\yii hr-grievance-redressal');*/

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