<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of worker_tracker_sheet_model
 *
 * @author zmq163
 */
class Worker_tracker_sheet_model extends CI_Model {

    //put your code here
    var $mdb;

    public function __construct() {
        parent::__construct();
        $this->mdb = $this->load->database('mdb', TRUE);
        include APPPATH . 'third_party/libchart/classes/libchart.php';
        $this->load->model('Graphically_draw_data_model');
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function getAnmWorkSheetANCModel($regionCode = NULL, $pageNumber = NULL, $perPageRow = NULL) {
        $tempRegionDetail = $this->getDataTable('master_area_create_by_super', array('region_code_super' => $regionCode, 'mapping_status' => 1));
        $tempRegionIds = $this->getMiraWorkerRegionId($tempRegionDetail);
        $tempWomenList = $this->getWomenListPregnant($tempRegionIds, $pageNumber, $perPageRow);
        for ($i = 0; $i < count($tempWomenList); $i++) {
            $tempWomenList[$i]['anc_status'] = $this->getAncStatusPregnantId($tempWomenList[$i]['pregnant_id'], $tempWomenList[$i]['pregnant_date']);
        }
        return $tempWomenList;
    }

    private function getAncStatusPregnantId($pregnantId, $lpmDate) {
        $anc1Status = 3;
        $anc2Status = 3;
        $anc3Status = 3;
        $anc4Status = 3;
        $ancCodeTilldate = $this->getAncCodeArray($this->getWeek(floor((time() - strtotime($lpmDate)) / (60 * 60 * 24))));
        for ($i = 0; $i < count($ancCodeTilldate); $i++) {
            $tempAncDataDeatil = $this->getDataTable('anm_anc_critical', array('pregnant_id' => $pregnantId, 'anc_code' => $ancCodeTilldate[$i]));
            if ($i < (count($ancCodeTilldate) - 1)) {

                switch ($ancCodeTilldate[$i]) {
                    case 1:
                        if ($tempAncDataDeatil) {
                            $anc1Status = 1;
                        } else {
                            $anc1Status = 0;
                        }
                        break;
                    case 2:
                        if ($tempAncDataDeatil) {
                            $anc2Status = 1;
                        } else {
                            $anc2Status = 0;
                        }
                        break;
                    case 3:
                        if ($tempAncDataDeatil) {
                            $anc3Status = 1;
                        } else {
                            $anc3Status = 0;
                        }
                        break;
                    case 4:
                        if ($tempAncDataDeatil) {
                            $anc4Status = 1;
                        } else {
                            $anc4Status = 0;
                        }
                        break;
                }
            } else {
                switch ($ancCodeTilldate[$i]) {
                    case 1:
                        if ($tempAncDataDeatil) {
                            $anc1Status = 1;
                        } else {
                            $anc1Status = 2;
                        }
                        break;
                    case 2:
                        if ($tempAncDataDeatil) {
                            $anc2Status = 1;
                        } else {
                            $anc2Status = 2;
                        }
                        break;
                    case 3:
                        if ($tempAncDataDeatil) {
                            $anc3Status = 1;
                        } else {
                            $anc3Status = 2;
                        }
                        break;
                    case 4:
                        if ($tempAncDataDeatil) {
                            $anc4Status = 1;
                        } else {
                            $anc4Status = 2;
                        }
                        break;
                }
            }
        }
        return array('anc1' => $anc1Status, 'anc2' => $anc2Status, 'anc3' => $anc3Status, 'anc4' => $anc4Status);
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function getAnmWorkSheetHRPModel($regionCode = NULL, $pageNumber = NULL, $perPageRow = NULL) {
        $tempRegionDetail = $this->getDataTable('master_area_create_by_super', array('region_code_super' => $regionCode, 'mapping_status' => 1));
        $tempRegionIds = $this->getMiraWorkerRegionId($tempRegionDetail);

        $tempWomenList = $this->getWomenListPregnant($tempRegionIds, $pageNumber, $perPageRow);
        for ($i = 0; $i < count($tempWomenList); $i++) {
            $tempWomenList[$i]['status'] = $this->getAnmHRPAttemptStatus($tempWomenList[$i]['pregnant_id']);
        }

        return $tempWomenList;
    }

    private function getAnmAlertStatus($pregnant_id) {
        $this->mdb->select('*');
        $this->mdb->from('master_asha_to_anm_alert');
        $this->mdb->where(array('pregnant_id' => $pregnant_id, 'alert' => 1));
        $this->mdb->order_by('alert_id', 'DESC');
        return $this->getData($this->mdb->get());
    }

    private function getAnmHRPAttemptStatus($pregnantId) {
        $tempMissed = 0;
        $tempPending = 0;
        $tempDone = 0;
        $referCount = array();
        $tempPendingFlag = FALSE;
        /* */$tempHRPRiskData = $this->getAnmAlertStatus($pregnantId);
        if ($tempHRPRiskData) {
            foreach ($tempHRPRiskData as $key => $value) {
                if ($value['anm_status']) {
                    $tempPendingFlag = TRUE;
                    $tempDone++;
                    if (count($referCount) < 5) {
                        $tempANMAnswer = $this->getDataTable('master_asha_anm_ans', array('alert_id' => $value['alert_id']));
                        $tempReferAnmAnswer = $tempANMAnswer[0]['anm_answer'];
                        $referCount[] = array('week' => $value['week_id'], 'refer_to' => $tempReferAnmAnswer, 'status' => 1); // done
                    }
                } else {
                    if ($tempPending or $tempPendingFlag) {
                        $tempMissed++;
                        if (count($referCount) < 5) {
                            $referCount[] = array('week' => $value['week_id'], 'refer_to' => 0, 'status' => 0); //misssed
                        }
                    } else {
                        $tempPending++;
                        if (count($referCount) < 5) {
                            $referCount[] = array('week' => $value['week_id'], 'refer_to' => 10, 'status' => 2); //pending
                        }
                    }
                }
            }
        }
        return array('done' => $tempDone, 'missed' => $tempMissed, 'pending' => $tempPending, 'referCount' => $referCount);
    }

    private function getMiraWorkerRegionId($regionCodeDetail) {
        $regionCodeIds = array();
        if ($regionCodeDetail) {
            foreach ($regionCodeDetail as $key => $value) {
                $regionCodeIds[] = $value['region_code'];
            }
            return $regionCodeIds;
        } else {

            return FALSE;
        }
    }

    private function getWomenListPregnant($regionIds, $pageNumber, $perPageData) {
        $this->mdb->select('*');
        $this->mdb->from('mira_house');
        $this->mdb->join('mira_women', 'mira_women.house_id=mira_house.auto_id', 'INNER');
        $this->mdb->join('mira_pregnant_women', 'mira_women.women_id=mira_pregnant_women.women_id', 'INNER');
        $this->mdb->where_in('mira_house.region_code', $regionIds);
        $this->mdb->where('mira_pregnant_women.pregnant_status', 1);
        if (isset($pageNumber) and $pageNumber != NULL) {
            $this->mdb->order_by('mira_women.women_id', 'asc');
            $this->mdb->limit($perPageData, ($pageNumber - 1) * $perPageData);
        }
        return $this->getData($this->mdb->get());
    }

    /**
     * 
     * @param type $_regionCode
     * @return boolean
     * 
     * 
     * 
     */
    public function getRegionUserDetailModel($_regionCode = NULL) {
        if ($_regionCode != NULL) {
            $this->mdb->select('*');
            $this->mdb->from('master_login_user');
            $this->mdb->join('master_user_details', 'master_login_user.user_login_id=master_user_details.user_login_id', 'INNER');
            $this->mdb->join('master_area_create_by_super', 'master_login_user.create_region_id=master_area_create_by_super.region_code', 'INNER');
            $this->mdb->where('master_login_user.create_region_id', $_regionCode);
            return $this->getData($this->mdb->get());
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function getANMWorkerTrackSheetModel($_app_id = NULL) {
        if ($_app_id != NULL) {
            $tempAnmWorkerData = FALSE;
            $tempApplicationDetail = $this->getDataTable('application_create', array('app_id' => $_app_id));
            if ($tempApplicationDetail) {

                $tempAnmWorkerData = $this->getAshaWorkerDetail($_app_id, ($tempApplicationDetail[0]['app_total_level'] - 1));
                if ($tempAnmWorkerData) {
                    for ($i = 0; $i < count($tempAnmWorkerData); $i++) {
                        $tempCountDonePendingMissed = $this->getRegionCodeBySuperRegionCode($tempAnmWorkerData[$i]['create_region_id']);
                        $tempAnmWorkerData[$i]['work_status_running'] = array('done' => $tempCountDonePendingMissed[0], 'missed' => $tempCountDonePendingMissed[1], 'pending' => $tempCountDonePendingMissed[2]);
                        $tempAnmWorkerData[$i]['anc_status_running'] = $this->getAncStatusDonePendingMissed($tempAnmWorkerData[$i]['create_region_id'], 1);
                        $tempAnmWorkerData[$i]['anc_status_close'] = $this->getAncStatusDoneMissed($tempAnmWorkerData[$i]['create_region_id'], 0);
                    }
                }
            }
            return $tempAnmWorkerData;
        } else {
            return FALSE;
        }
    }

    private function getAncStatusDoneMissed($_regionCode, $pregnant_status) {
        $tempRegionCodeArray = $this->getDataTable('master_area_create_by_super', array('region_code_super' => $_regionCode, 'mapping_status' => 1));
        if ($tempRegionCodeArray) {
            return $this->getPregnantWomenRegionCodeAnc($this->getIdArray($tempRegionCodeArray), $pregnant_status);
        } else {
            return FALSE;
        }
    }

    private function getAncStatusDonePendingMissed($_regionCode, $pregnant_status) {
        $tempRegionCodeArray = $this->getDataTable('master_area_create_by_super', array('region_code_super' => $_regionCode, 'mapping_status' => 1));
        if ($tempRegionCodeArray) {
            return $this->getPregnantWomenRegionCodeAnc($this->getIdArray($tempRegionCodeArray), $pregnant_status);
        } else {
            return FALSE;
        }
    }

    private function getPregnantWomenRegionCodeAnc($regionCodeArray, $pregnant_status) {


        $tempANC1Done = 0;
        $tempANC1Pending = 0;
        $tempANC1Missed = 0;

        $tempANC2Done = 0;
        $tempANC2Pending = 0;
        $tempANC2Missed = 0;

        $tempANC3Done = 0;
        $tempANC3Pending = 0;
        $tempANC3Missed = 0;

        $tempANC4Done = 0;
        $tempANC4Pending = 0;
        $tempANC4Missed = 0;
        $this->mdb->select('*');
        $this->mdb->from('mira_pregnant_women');
        $this->mdb->where_in('region_code', $regionCodeArray);
        $this->mdb->where('pregnant_status', $pregnant_status);
        $tempPregnantData = $this->getData($this->mdb->get());
        if ($tempPregnantData) {
            for ($i = 0; $i < count($tempPregnantData); $i++) {
                $tempPregnantAncStatus = $this->getPregnantANCAlert($tempPregnantData[$i]['pregnant_id'], $this->getWeek(floor((time() - strtotime($tempPregnantData[$i]['pregnant_date'])) / (60 * 60 * 24))), $pregnant_status);
                //print_r($tempPregnantAncStatus);
                if (!empty($tempPregnantAncStatus[0])) {
                    $tempANC1Done += $tempPregnantAncStatus[0][0];
                    $tempANC1Pending += $tempPregnantAncStatus[0][1];
                    $tempANC1Missed += $tempPregnantAncStatus[0][2];
                }
                if (!empty($tempPregnantAncStatus[1])) {
                    $tempANC2Done += $tempPregnantAncStatus[1][0];
                    $tempANC2Pending += $tempPregnantAncStatus[1][1];
                    $tempANC2Missed += $tempPregnantAncStatus[1][2];
                }
                if (!empty($tempPregnantAncStatus[2])) {
                    $tempANC3Done += $tempPregnantAncStatus[2][0];
                    $tempANC3Pending += $tempPregnantAncStatus[2][1];
                    $tempANC3Missed += $tempPregnantAncStatus[2][2];
                }
                if (!empty($tempPregnantAncStatus[3])) {
                    $tempANC4Done += $tempPregnantAncStatus[3][0];
                    $tempANC4Pending += $tempPregnantAncStatus[3][1];
                    $tempANC4Missed += $tempPregnantAncStatus[3][2];
                }

//
//
//                $tempANC3Done = $tempPregnantAncStatus[2]['done'];
//                $tempANC3Pending = $tempPregnantAncStatus[2]['pending'];
//                $tempANC3Missed = $tempPregnantAncStatus[2]['missed'];
//
//                $tempANC4Done = $tempPregnantAncStatus[3]['done'];
//                $tempANC4Pending = $tempPregnantAncStatus[3]['pending'];
//                $tempANC4Missed = $tempPregnantAncStatus[3]['missed'];
            }
        }
        return array(
            'anc1_status' => array('missed' => $tempANC1Missed, 'pending' => $tempANC1Pending, 'done' => $tempANC1Done),
            'anc2_status' => array('missed' => $tempANC2Missed, 'pending' => $tempANC2Pending, 'done' => $tempANC2Done),
            'anc3_status' => array('missed' => $tempANC3Missed, 'pending' => $tempANC3Pending, 'done' => $tempANC3Done),
            'anc4_status' => array('missed' => $tempANC4Missed, 'pending' => $tempANC4Pending, 'done' => $tempANC4Done)
        );
    }

    private function getPregnantANCAlert($pregnant_id, $currentweek, $pregnant_status) {
        $tempAncCompletCodeArray = $this->getAncCodeArray($currentweek);
        //print_r($tempAncCompletCodeArray);
        $anc1Status = array();
        $anc2Status = array();
        $anc3Status = array();
        $anc4Status = array();
        for ($i = 0; $i < count($tempAncCompletCodeArray); $i++) {
            switch ($tempAncCompletCodeArray[$i]) {
                case 1:
                    $anc1Status = $this->getAncStatus($tempAncCompletCodeArray[$i], $currentweek, $pregnant_id, $pregnant_status);
                    break;
                case 2:
                    $anc2Status = $this->getAncStatus($tempAncCompletCodeArray[$i], $currentweek, $pregnant_id, $pregnant_status);
                    break;
                case 3:
                    $anc3Status = $this->getAncStatus($tempAncCompletCodeArray[$i], $currentweek, $pregnant_id, $pregnant_status);
                    break;
                case 4:
                    $anc4Status = $this->getAncStatus($tempAncCompletCodeArray[$i], $currentweek, $pregnant_id, $pregnant_status);
                    break;
            }
        }
        return array($anc1Status, $anc2Status, $anc3Status, $anc4Status);
    }

    private function getAncCodeArray($currentWeekNumber) {
        $tempAncCode = array();
        if ($currentWeekNumber > 0) {
            $tempAncCode[] = 1;
        }
        if ($currentWeekNumber > 13) {
            $tempAncCode[] = 2;
        }
        if ($currentWeekNumber > 27) {
            $tempAncCode[] = 3;
        }
        if ($currentWeekNumber > 35) {
            $tempAncCode[] = 4;
        }
        return $tempAncCode;
    }

    private function getAncStatus($ancCode, $week_number, $pregnant_id, $pregnant_status) {
        $tempAncMissed = 0;
        $tempAncDone = 0;
        $tempAncPending = 0;
        $tempAncDataDeatil = $this->getDataTable('anm_anc_critical', array('pregnant_id' => $pregnant_id, 'anc_code' => $ancCode));
        if ($pregnant_status) {
            if ($tempAncDataDeatil) {
                $tempAncDone++;
            } else {
                $tempAncMissedPending = $this->getMissedPending($week_number, $ancCode);
                $tempAncMissed = $tempAncMissedPending[0];
                $tempAncPending = $tempAncMissedPending[1];
            }
        } else {
            if ($tempAncDataDeatil) {
                $tempAncDone++;
            } else {
                $tempAncMissed++;
            }
        }
        return array($tempAncDone, $tempAncPending, $tempAncMissed);
    }

    private function getMissedPending($week_number, $ancCode) {
        $tempAncMissed = 0;
        $tempAncPending = 0;
        switch ($ancCode) {
            case 1:
                if ($week_number > 14) {
                    $tempAncMissed++;
                } else {
                    $tempAncPending++;
                }
                break;
            case 2:
                if ($week_number > 26) {
                    $tempAncMissed++;
                } else {
                    $tempAncPending++;
                }
                break;
            case 3:
                if ($week_number > 34) {
                    $tempAncMissed++;
                } else {
                    $tempAncPending++;
                }
                break;
            case 4:
                $tempAncPending++;
                break;
        }
        return array($tempAncMissed, $tempAncPending);
    }

    private function getRegionCodeBySuperRegionCode($_regionCode) {
        $tempRegionCodeArray = $this->getDataTable('master_area_create_by_super', array('region_code_super' => $_regionCode, 'mapping_status' => 1));
        if ($tempRegionCodeArray) {
            return $this->getPregnantWomenRegionCode($this->getIdArray($tempRegionCodeArray));
        } else {
            return FALSE;
        }
    }

    private function getIdArray($dataArray) {
        $regionCode = array();
        for ($i = 0; $i < count($dataArray); $i++) {
            $regionCode[] = $dataArray[$i]['region_code'];
        }
        return $regionCode;
    }

    private function getPregnantWomenRegionCode($regionCodeArray) {
        $this->mdb->select('*');
        $this->mdb->from('mira_pregnant_women');
        $this->mdb->where_in('region_code', $regionCodeArray);
        $this->mdb->where('pregnant_status', 1);
        $tempPregnantData = $this->getData($this->mdb->get());
        if ($tempPregnantData) {
            return $this->getPregnantHRPAlert($tempPregnantData);
        }
    }

    private function getPregnantHRPAlert($_pregnantIdsArray) {
        $tempCountDone = 0;
        $tempCountPending = 0;
        $tempCountMissed = 0;
        for ($i = 0; $i < count($_pregnantIdsArray); $i++) {
            $tempPregnantAlertData = $this->getDataTable('master_asha_to_anm_alert', array('alert' => 1, 'pregnant_id' => $_pregnantIdsArray[$i]['pregnant_id']));
            if ($tempPregnantAlertData) {
                $tempCount = $this->getCountDonePendingMissed($tempPregnantAlertData);
                $tempCountDone += $tempCount[0];
                $tempCountPending += $tempCount[1];
                $tempCountMissed += $tempCount[2];
            }
        }
        return array($tempCountDone, $tempCountPending, $tempCountMissed);
    }

    private function getCountDonePendingMissed($_tempPregnantAlertData) {
        $tempCountDone = 0;
        $tempCountPending = 0;
        $tempCountMissed = 0;
        $pregnantPendingFlag = TRUE;
        for ($j = 0; $j < count($_tempPregnantAlertData); $j++) {
            if ($_tempPregnantAlertData[$j]['anm_status']) {
                $tempCountDone++;
            } else {
                if ($pregnantPendingFlag) {
                    $pregnantPendingFlag = FALSE;
                    $tempCountPending++;
                } else {
                    $tempCountMissed++;
                }
            }
        }
        return array($tempCountDone, $tempCountPending, $tempCountMissed);
    }

    /**
     * 
     * 
     * 
     */
    public function getAshaWorkerTrackSheetModel($_app_id = NULL,$ulevel=NULL,$tlevel=NULL,$region_code=NULL) {
        if ($_app_id != NULL) {
            $temp_asha_worker = $this->getDataTable('application_create', array('app_id' => $_app_id));
            if ($temp_asha_worker) {
                if(($tlevel-1)==$ulevel)
                {
                  $asha_worker_data = $this->anmAshaList($this->getAshaWorkerDetailV2($region_code)) ; 
                }
                else
                {
                     $asha_worker_data = $this->anmAshaList($this->getAshaWorkerDetail($_app_id, $temp_asha_worker[0]['app_total_level']));
                }
                if ($asha_worker_data) {

                    for ($i = 0; $i < count($asha_worker_data); $i++) {
                        $asha_worker_data[$i]['child'] = $this->getTotalChildUnder5Year($asha_worker_data[$i]['create_region_id']);
                        $asha_worker_data[$i]['transaction'] = $this->getHouseCountWomenCountPregnantCountChildCount($asha_worker_data[$i]['create_region_id']);
                        $asha_worker_data[$i]['work'] = $this->getAshaWorkDonePending($asha_worker_data[$i]['create_region_id']);

                        $asha_worker_data[$i]['work_last'] = $this->getAshaWorkDonePendingFromMondayToToday($asha_worker_data[$i]['create_region_id']);



                        $asha_worker_data[$i]['delivery_status'] = $this->getPregnantDeliveryStatus($asha_worker_data[$i]['create_region_id']);
                        $asha_worker_data[$i]['running_hrp'] = $this->getRunningPregnantWomenHRPPercentage($asha_worker_data[$i]['create_region_id']);
                        $asha_worker_data[$i]['close_hrp'] = $this->getClosePregnantWomenHRPPercentage($asha_worker_data[$i]['create_region_id']);
                        $asha_worker_data[$i]['screening'] = $this->getScreenViewPercentageTimeAverageRunning($asha_worker_data[$i]['create_region_id'], $_app_id);
                        $asha_worker_data[$i]['screeningclose'] = $this->getScreenViewPercentageTimeAverageClose($asha_worker_data[$i]['create_region_id'], $_app_id);
                    }
                    return $asha_worker_data;
                } else {
                    return FALSE;
                }
            }
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     */
    private function getTotalChildUnder5Year($regionId) {
        if ($regionId != NULL) {
            $tempVaccineDoneCount = 0;
            $tempVaccineMissedCount = 0;
            $this->mdb->select('*');
            $this->mdb->from('mira_child');
            $this->mdb->where('region_code', $regionId);
            $tempChilData = $this->getData($this->mdb->get());
            for ($i = 0; $i < count($tempChilData); $i++) {

                //$childRegistrationInDay = $this->getTotalDayBetweenTwoDate($tempChilData[$i]['create_date'], $tempChilData[$i]['dob']);
                //$tempMasterVaccine = $this->masterVaccineList($childRegistrationInDay, $this->session->userdata('app_id'));
                $tempVaccineDoneCount += $this->childVaccineListDone($tempChilData[$i]['create_date'], $tempChilData[$i]['child_id']);
                $tempVaccineMissedCount += $this->childVaccineListMissed($tempChilData[$i]['create_date'], $tempChilData[$i]['child_id']);
            }
            $this->drawGraphImage($regionId, $tempVaccineDoneCount, $tempVaccineMissedCount);
            return array('total' => count($tempChilData), 'missed' => $tempVaccineMissedCount, 'done' => $tempVaccineDoneCount, 'url' => 'graph/' . $regionId . '/piechart/1.png');
        } else {
            return FALSE;
        }
    }

    private function drawGraphImage($region_code, $done, $missed) {
        if (!is_dir('graph/' . $region_code . '/piechart')) {
            mkdir('./graph/' . $region_code . '/piechart', 0777, TRUE);
        }
        $chart = new PieChart(360, 200);
        $palette = new Palette();
        $palette->setBackgroundColor(array(new Color(110, 120, 130)));
        $dataSet = new XYDataSet();
        $dataSet->addPoint(new Point("Vaccine Done(" . $done . ")", $done));
        $dataSet->addPoint(new Point("Missed Vaccine (" . $missed . ")", $missed));

        $chart->setDataSet($dataSet);

        $chart->setTitle("Child Immunization");
        $chart->render('graph/' . $region_code . '/piechart/1.png');
    }

    private function getTotalDayBetweenTwoDate($new_date, $old_date) {
        $new_date_time = strtotime($new_date);
        $old_date_time = strtotime($old_date);
        if ($new_date_time > $old_date_time) {
            return floor(($new_date_time - $old_date_time) / (60 * 60 * 24));
        } else {
            return 0;
        }
    }

    private function masterVaccineList($childRegistrationDay, $app_id) {
        if ($childRegistrationDay != NULL and $app_id != NULL) {
            $this->mdb->select('mapping_child_vaccine_to_application.vaccine_id,master_vaccine_child.vaccine_name,master_vaccine_child.vaccine_code');
            $this->mdb->from('mapping_child_vaccine_to_application');
            $this->mdb->join('master_vaccine_child', 'mapping_child_vaccine_to_application.vaccine_id=master_vaccine_child.vaccine_id', 'INNER');
            $this->mdb->where(array('master_vaccine_child.from >' => $childRegistrationDay, 'mapping_child_vaccine_to_application.app_id' => $app_id, 'mapping_child_vaccine_to_application.running_status' => 1));
            return $this->getData($this->mdb->get());
        } else {
            return FALSE;
        }
    }

    private function childVaccineListDone($chilRegistrationDate, $child_id) {
        if ($chilRegistrationDate != NULL and $child_id != NULL) {
            $this->mdb->select('*');
            $this->mdb->from('master_child_immunization');
            $this->mdb->where(array('DATE_FORMAT(master_child_immunization.submit_date,"%Y-%m-%d") >=' => date('Y-m-d', strtotime($chilRegistrationDate)), 'master_child_immunization.child_id' => $child_id));
            $tempData = $this->getData($this->mdb->get());
            if ($tempData) {
                return count($tempData);
            } else {
                return 0;
            }
        } else {
            return FALSE;
        }
    }

    private function childVaccineListMissed($chilRegistrationDate, $child_id) {
        if ($chilRegistrationDate != NULL and $child_id != NULL) {
            $this->mdb->select('*');
            $this->mdb->from('master_child_immunization');
            $this->mdb->where(array('DATE_FORMAT(master_child_immunization.submit_date,"%Y-%m-%d") >=' => date('Y-m-d', strtotime($chilRegistrationDate)), 'master_child_immunization.child_id' => $child_id, 'master_child_immunization.vaccine_date' => "1900-01-01"));
            $tempData = $this->getData($this->mdb->get());
            if ($tempData) {
                return count($tempData);
            } else {
                return 0;
            }
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     */
    private function getScreenViewPercentageTimeAverageRunning($_region_code, $app_id) {
        $_temp_running_pregnant_women = $this->getDataTable('mira_pregnant_women', array('region_code' => $_region_code, 'pregnant_status' => 1));
        $data = array();
        $data_average_time = 0;
        $totalScreen = 0;
        $totalScreenView = 0;
        $totalScreeningCount = 0;


        for ($i = 0; $i < count($_temp_running_pregnant_women); $i++) {
            $current_week = $this->getWeek(floor((time() - strtotime($_temp_running_pregnant_women[$i]['registration_date'])) / (60 * 60 * 24)));
            $tempPregnatData = $this->getScreenViewTimeAverageByPregnantId($_temp_running_pregnant_women[$i]['pregnant_id'], $current_week);
            $data_average_time+= $tempPregnatData['temp_average_time'];
            $totalScreen += $tempPregnatData['total_screen'];
            $totalScreenView += $tempPregnatData['screen_view'];
            $totalScreeningCount+=$tempPregnatData['total_week_pregnant'];
        }
        if ($totalScreeningCount) {
            //$data['average_time'] = date('i:s', (int) ($data_average_time / $totalScreeningCount));
            $data['average_time'] = gmdate("H:i:s", $data_average_time); //date('Y-m-d H:i:s', strtotime($data_average_time));
        } else {
            $data['average_time'] = gmdate('H:i:s', 0);
        }
        if ($totalScreen) {
            $data['screen_view_ratio'] = (int) (($totalScreenView / $totalScreen) * 100);
        } else {
            $data['screen_view_ratio'] = 0;
        }
        return $data;
    }

    private function getScreenViewTimeAverageByPregnantId($pregnant_id, $current_week) {
        $temp_time = 0;
        $total_screen = 0;
        $total_screen_view = 0;
        $total_week_count = 0;
        $this->mdb->select('*');
        $this->mdb->from('common_module_tracker_pregnant');
        $this->mdb->join('common_module_tracker', 'common_module_tracker.comm_module_id=common_module_tracker_pregnant.common_module_id', 'INNER');
        $this->mdb->where(array('common_module_tracker_pregnant.pregnant_id' => $pregnant_id, 'common_module_tracker_pregnant.week_id' => $current_week));
        $temp_data = $this->getData($this->mdb->get());
        if ($temp_data) {
            $countLenght = count($temp_data);
            $total_screen = 5 * $countLenght;
            for ($i = 0; $i < $countLenght; $i++) {
                $temp_time+=(int) (strtotime($temp_data[$i]['end_time']) - strtotime($temp_data[$i]['start_time']));
                $tempDataScreenView = $this->getSubModeulSceenCountView($temp_data[$i]['common_module_id']);
                $total_week_count += $tempDataScreenView['totalWeek'];
                $total_screen +=$tempDataScreenView['total_screen'];
            }
        }

        return array('temp_average_time' => $temp_time, 'total_screen' => $total_screen, 'screen_view' => $total_screen_view, 'total_week_pregnant' => $total_week_count);
    }

    private function getSubModeulSceenCountView($_common_module_id) {
        $_temp_sub_module_data = $this->getDataTable('common_module_sub_menu_tracker', array('module_id' => $_common_module_id));
        $tempCountScreenView = 0;
        $i = 0;
        if ($_temp_sub_module_data) {
            for (; $i < count($_temp_sub_module_data); $i++) {
                if ($_temp_sub_module_data[$i]['scence_status']) {
                    $tempCountScreenView++;
                }
            }
        }
        return array('total_screen' => $tempCountScreenView, 'totalWeek' => $i);
    }

    /**
     * 
     * 
     * 
     */
    private function getScreenViewPercentageTimeAverageClose($_region_code, $_app_id) {
        $_temp_running_pregnant_women = $this->getDataTable('mira_pregnant_women', array('region_code' => $_region_code, 'pregnant_status' => 0));
        $data = array();
        $data_average_time = 0;
        $totalScreen = 0;
        $totalScreenView = 0;
        $totalScreeningCount = 0;
        for ($i = 0; $i < count($_temp_running_pregnant_women); $i++) {
            $tempPregnatData = $this->getScreenViewTimeAverageByPregnantId($_temp_running_pregnant_women[$i]['pregnant_id'], 0);
            $data_average_time+= $tempPregnatData['temp_average_time'];
            $totalScreen += $tempPregnatData['total_screen'];
            $totalScreenView += $tempPregnatData['screen_view'];
            $totalScreeningCount+=$tempPregnatData['total_week_pregnant'];
        }
        if ($totalScreeningCount) {
            $data['average_time'] = date('i:s', (int) ($data_average_time / $totalScreeningCount));
        } else {
            $data['average_time'] = date('i:s', 0);
        }
        if ($totalScreen) {
            $data['screen_view_ratio'] = (int) (($totalScreenView / $totalScreen) * 100);
        } else {
            $data['screen_view_ratio'] = 0;
        }
        return $data;
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function getClosePregnantWomenHRPPercentage($_region_code) {
        $_temp_running_pregnant_women = $this->getDataTable('mira_pregnant_women', array('region_code' => $_region_code, 'pregnant_status' => 0));
        $total_week = 0;
        $total_week_done = 0;
        for ($i = 0; $i < count($_temp_running_pregnant_women); $i++) {
            $_temp_week_done = $this->getDataTable('master_asha_to_anm_alert', array('pregnant_id' => $_temp_running_pregnant_women[$i]['pregnant_id']));
            if ($_temp_week_done) {
                $total_week_done = $total_week_done + count($_temp_week_done);
            }
            $total_week += $this->getWeek(floor((strtotime($_temp_running_pregnant_women[$i]['closing_date']) - strtotime($_temp_running_pregnant_women[$i]['registration_date'])) / (60 * 60 * 24)));
        }
        return $this->getPercentage($total_week_done, $total_week);
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function getRunningPregnantWomenHRPPercentage($_region_code) {
        $_temp_running_pregnant_women = $this->getDataTable('mira_pregnant_women', array('region_code' => $_region_code, 'pregnant_status' => 1));
        $total_week = 0;
        $total_week_done = 0;
        for ($i = 0; $i < count($_temp_running_pregnant_women); $i++) {
            $_temp_week_done = $this->getDataTable('master_asha_to_anm_alert', array('pregnant_id' => $_temp_running_pregnant_women[$i]['pregnant_id']));
            if ($_temp_week_done) {
                $total_week_done = $total_week_done + count($_temp_week_done);
            }
            $total_week += $this->getWeek(floor((time() - strtotime($_temp_running_pregnant_women[$i]['registration_date'])) / (60 * 60 * 24)));
        }
        return $this->getPercentage($total_week_done, $total_week);
    }

    private function getPercentage($nominator, $denmonetar) {
        if ($denmonetar > 0) {
            $temp_ratio = $nominator / $denmonetar;
            return (int) ($temp_ratio * 100);
        } else {
            return 0;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function getAshaWorkerDetail($_app_id, $_level) {
        $this->mdb->select('*');
        $this->mdb->from('master_login_user');
        $this->mdb->join('master_user_details', 'master_user_details.user_login_id=master_login_user.user_login_id', 'INNER');
        $this->mdb->join('master_area_create_by_super', 'master_area_create_by_super.region_code=master_login_user.create_region_id', 'INNER');
        $this->mdb->where(array('master_login_user.app_id' => $_app_id, 'master_login_user.user_level' => $_level));
        return $this->getData($this->mdb->get());
    }



     private function getAshaWorkerDetailV2($region_code) {
       
        $this->mdb->select('*');
        $this->mdb->from('master_login_user');
        $this->mdb->join('master_user_details', 'master_user_details.user_login_id=master_login_user.user_login_id', 'INNER');
        $this->mdb->join('master_area_create_by_super', 'master_area_create_by_super.region_code=master_login_user.create_region_id', 'INNER');
        $this->mdb->where(array('master_area_create_by_super.region_code_super' => $region_code));
        return $this->getData($this->mdb->get());
    }

    /**
     * 
     * 
     * 
     */
    private function anmAshaList($ashaList) {
        for ($i = 0; $i < count($ashaList); $i++) {

            $this->mdb->select('*');
            $this->mdb->from('master_area_create_by_super');
            $this->mdb->join('master_login_user', 'master_area_create_by_super.region_code=master_login_user.create_region_id', 'INNER');
            $this->mdb->join('master_user_details', 'master_user_details.user_login_id=master_login_user.user_login_id', 'INNER');
            $this->mdb->where(array('master_area_create_by_super.region_code' => $ashaList[$i]['region_code_super']));
            $tempData = $this->getData($this->mdb->get());
            if ($tempData) {
                $ashaList[$i]['anm_detail'] = $tempData[0];
            }
        }
        return $ashaList;
    }

    /**
     * 
     *      
     * 
     * 
     * 
     */
    private function getPregnantDeliveryStatus($_region_code) {
        $_temp_running_pregnant_women = $this->getDataTable('mira_pregnant_women', array('region_code' => $_region_code, 'pregnant_status' => 0));
        $temp_count_success = 0;
        $temp_count_died = 0;
        $temp_count_migrated = 0;
        $temp_count_aborted = 0;
        $temp_count_other = 0;

        for ($j = 0; $j < count($_temp_running_pregnant_women); $j++) {
            switch ($_temp_running_pregnant_women[$j]['delivery_status']) {
                case 1:
                    $temp_count_success++;
                    break;
                case 2:
                    $temp_count_aborted++;
                    break;
                case 3:
                    $temp_count_died++;
                    break;
                case 4:
                    $temp_count_migrated++;
                    break;
                case 5:
                    $temp_count_other++;
                    break;
            }
        }
        return array('success' => $temp_count_success, 'died' => $temp_count_died, 'aborted' => $temp_count_aborted, 'migrated' => $temp_count_migrated, 'other' => $temp_count_other);
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function getAshaWorkDonePending($_region_code) {
        $_temp_running_pregnant_women = $this->getDataTable('mira_pregnant_women', array('region_code' => $_region_code, 'pregnant_status' => 1));
        $temp_count_done = 0;
        $temp_count_pending = 0;
        $temp_high_total_high_alert = 0;
        $temp_high_met_high_alert = 0;
        for ($j = 0; $j < count($_temp_running_pregnant_women); $j++) {

            $temp_asha_work_status = $this->getDataTable('master_asha_to_anm_alert', array('pregnant_id' => $_temp_running_pregnant_women[$j]['pregnant_id'], 'week_id' => $this->getWeek(floor((time() - strtotime($_temp_running_pregnant_women[$j]['pregnant_date'])) / (60 * 60 * 24)))));

            if ($temp_asha_work_status) {
                if ($temp_asha_work_status[0]['alert']) {
                    $temp_high_total_high_alert++;
                    if ($temp_asha_work_status[0]['anm_status']) {
                        $temp_high_met_high_alert++;
                    }
                }
                $temp_count_done++;
            } else {
                $temp_count_pending++;
            }
        }
        return array('pending' => $temp_count_pending, 'done' => $temp_count_done, 'total_hrp' => $temp_high_total_high_alert, 'met_hrp' => $temp_high_met_high_alert, 'pending_hrp' => ($temp_high_total_high_alert - $temp_high_met_high_alert));
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function getAshaWorkDonePendingFromMondayToToday($_region_code) {
        $_temp_running_pregnant_women = $this->getDataTable('mira_pregnant_women', array('region_code' => $_region_code, 'pregnant_status' => 1));
        $temp_count_done = 0;
        $temp_count_pending = 0;
        $temp_high_total_high_alert = 0;
        $temp_high_met_high_alert = 0;
        for ($j = 0; $j < count($_temp_running_pregnant_women); $j++) {
            $tenp_week_array = $this->getWeekLastSunday($_temp_running_pregnant_women[$j]['pregnant_date']);
            for ($k = 0; $k < count($tenp_week_array); $k++) {
                $temp_asha_work_status = $this->getDataTable('master_asha_to_anm_alert', array('pregnant_id' => $_temp_running_pregnant_women[$j]['pregnant_id'], 'week_id' =>$tenp_week_array[$k]));
                if ($temp_asha_work_status) {
                    if ($temp_asha_work_status[0]['alert']) {
                        $temp_high_total_high_alert++;
                        if ($temp_asha_work_status[0]['anm_status']) {
                            $temp_high_met_high_alert++;
                        }
                    }
                    $temp_count_done++;
                } else {
                    $temp_count_pending++;
                }
            }
        }
        return array('toady'=>date('l',  strtotime('-1 day')),'pending_last' => $temp_count_pending, 'done_last' => $temp_count_done, 'total_hrp_last' => $temp_high_total_high_alert, 'met_hrp_last' => $temp_high_met_high_alert, 'pending_hrp_last' => ($temp_high_total_high_alert - $temp_high_met_high_alert));
    }

    private function getWeekLastSunday($registration_date) {
        $number_of_day = date('N');


        $week_array = array();
        switch ($number_of_day) {
            case 1 :
                $week_array[] = $this->getWeek(floor((strtotime(date('Y-m-d', strtotime('-1 day'))) - strtotime($registration_date)) / (60 * 60 * 24)));
                break;
            case 2 :
                for ($i = 0; $i < $number_of_day; $i++) {
                    $temp_week = $this->getWeek(floor((strtotime(date('Y-m-d', strtotime(($i + 1) . 'day'))) - strtotime($registration_date)) / (60 * 60 * 24)));
                    if (!in_array($temp_week, $week_array)) {
                        $week_array[] = $temp_week;
                    }
                }
                break;
            case 3 :
                for ($i = 0; $i < $number_of_day; $i++) {
                    $temp_week = $this->getWeek(floor((strtotime(date('Y-m-d', strtotime(($i + 1) . 'day'))) - strtotime($registration_date)) / (60 * 60 * 24)));
                    if (!in_array($temp_week, $week_array)) {
                        $week_array[] = $temp_week;
                    }
                }
                break;
            case 4 :
                for ($i = 0; $i < $number_of_day; $i++) {
                    $temp_week = $this->getWeek(floor((strtotime(date('Y-m-d', strtotime(($i + 1) . 'day'))) - strtotime($registration_date)) / (60 * 60 * 24)));
                    if (!in_array($temp_week, $week_array)) {
                        $week_array[] = $temp_week;
                    }
                }
                break;
            case 5 :
                for ($i = 0; $i < $number_of_day; $i++) {
                    $temp_week = $this->getWeek(floor((strtotime(date('Y-m-d', strtotime(($i + 1) . 'day'))) - strtotime($registration_date)) / (60 * 60 * 24)));
                    if (!in_array($temp_week, $week_array)) {
                        $week_array[] = $temp_week;
                    }
                }
                break;
            case 6 :
                for ($i = 0; $i < $number_of_day; $i++) {
                    $temp_week = $this->getWeek(floor((strtotime(date('Y-m-d', strtotime(($i + 1) . 'day'))) - strtotime($registration_date)) / (60 * 60 * 24)));
                    if (!in_array($temp_week, $week_array)) {
                        $week_array[] = $temp_week;
                    }
                }
                break;
            case 7 :
                for ($i = 0; $i < $number_of_day; $i++) {
                    $temp_week = $this->getWeek(floor((strtotime(date('Y-m-d', strtotime(($i + 1) . 'day'))) - strtotime($registration_date)) / (60 * 60 * 24)));
                    if (!in_array($temp_week, $week_array)) {
                        $week_array[] = $temp_week;
                    }
                }
                break;
        }
        return $week_array;
    }

    private function getMasetrAnmData($pregnant_id) {
        $this->mdb->select('*');
        $this->mdb->from('master_asha_to_anm_alert');
        $this->mdb->where(array('master_asha_to_anm_alert.pregnant_id' => $pregnant_id, 'DATE_FORMAT(master_asha_to_anm_alert.create_date,"%Y-%m-%d") >=' => date('Y-m-d', strtotime('last Sunday')), 'DATE_FORMAT(master_asha_to_anm_alert.create_date,"%Y-%m-%d") <' => date('Y-m-d')));
        return $this->getData($this->mdb->get());
    }

    /**
     * 
     * 
     * 
     */
    private function getHouseCountWomenCountPregnantCountChildCount($_region_code) {
        $this->mdb->select('*');
        $this->mdb->from('mira_house');
        $this->mdb->where('region_code', $_region_code);
        $data['tran_hid'] = $this->mdb->get()->num_rows();

        $this->mdb->select('*');
        $this->mdb->from('mira_women');
        $this->mdb->where('region_code', $_region_code);
        $data['tran_wid'] = $this->mdb->get()->num_rows();

        $this->mdb->select('*');
        $this->mdb->from('mira_pregnant_women');
        $this->mdb->where('region_code', $_region_code);
        $data['tran_pid'] = $this->mdb->get()->num_rows();

        $this->mdb->select('*');
        $this->mdb->from('mira_child');
        $this->mdb->where('region_code', $_region_code);

        $data['tran_cid'] = $this->mdb->get()->num_rows();
        return $data;
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function getDataTable($_table_name = NULL, $_conditio_array = NULL) {
        $this->mdb->select('*');
        $this->mdb->from($_table_name);
        if ($_conditio_array != NULL) {
            $this->mdb->where($_conditio_array);
        }
        return $this->getData($this->mdb->get());
    }

    /**
     * 
     * 
     * 
     */
    private function getData($_query = NULL) {
        if ($_query != NULL and $_query->num_rows() > 0) {
            return $_query->result_array();
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function getWeek($_number_of_days = NULL) {
        if ($_number_of_days != NULL) {
            $num_week = (int) ($_number_of_days / 7);
            if ($_number_of_days % 7) {
                $num_week++;
            }
            return $num_week;
        }
    }

}
