<?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 mobile
 *
 * @author zmq163
 * 
 */
class Service extends CI_Controller {

    //put your code here

    var $mdb;

    public function __construct() {
        parent::__construct();
        $this->mdb = $this->load->database('mdb', TRUE);
        $this->load->library('excel');
        $this->load->model('Master_universal_user');
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->library('date_conversion');
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function getPregnantWomenDataWithHRP() {
        $atLeastWeekHRP=  $this->input->get('atLeastWeekHrp');
        $this->mdb->select('master_area_create_by_super.region_name as VillageName,mira_pregnant_women.pregnant_id as PregnantId,'
                . 'mira_pregnant_women.pregnant_date as LMCDate,'
                . 'mira_women.name as WomenName,'
                . 'mira_pregnant_women.delivery_status as OutComeStatus');
        $this->mdb->from('mira_pregnant_women');
        $this->mdb->join('mira_women', 'mira_women.women_id=mira_pregnant_women.women_id', 'INNER');
        $this->mdb->join('mira_house', 'mira_house.auto_id=mira_women.house_id', 'INNER');
        $this->mdb->join('master_area_create_by_super', 'master_area_create_by_super.region_code=mira_house.region_id', 'INNER');
        $this->mdb->where(array('master_area_create_by_super.app_id' => 4, 'mira_pregnant_women.pregnant_status' => 0));
        $this->mdb->order_by('mira_pregnant_women.pregnant_id', 'desc');

        $query = $this->mdb->get();
        





        $excel_data_head = NULL;
        $excel_data = NULL;
        $i = 0;
        foreach ($query->result_array() as $key => $row) {
            if ($i == 0) {
                foreach ($row as $key => $value) {
                    $excel_data_head[$key] = $key;
                }
                for ($j = 0; $j < 40; $j++) {
                    $excel_data_head['WeekId_' . ($j + 1)] = 'WeekId_' . ($j + 1);
                }
                $excel_data[] = $excel_data_head;
                $i++;
            } else {

                $this->mdb->select('*');
                $this->mdb->from('master_asha_to_anm_alert');
                $this->mdb->where(array('master_asha_to_anm_alert.pregnant_id' => $row['PregnantId'], 'master_asha_to_anm_alert.week_id >' => 0));
                $query = $this->mdb->get();
                $tempPregnantIdWeek = array();
                foreach ($query->result_array() as $key => $value) {
                    $tempPregnantIdWeek[] = $value['week_id'];
                }
                if (count($tempPregnantIdWeek) > $atLeastWeekHRP and count($excel_data) < 502) {
                    $tempData = $row;

                    for ($j = 0; $j < 40; $j++) {
                        if(in_array(($j+1), $tempPregnantIdWeek)){
                            $tempData['WeekId_' . ($j + 1)] = 1;
                        }  else {
                            $tempData['WeekId_' . ($j + 1)] = "0";
                        }
                        
                    }
                    $excel_data[] = $tempData;
                }
                
            }
        }
        //print_r($excel_data);

        $this->load->library('excel');
        //activate worksheet number 1
        $this->excel->setActiveSheetIndex(0);
        //name the worksheet
        $this->excel->getActiveSheet()->setTitle('Pregnant Women List');

        $this->excel->getActiveSheet()->fromArray($excel_data);

        $filename = 'PregnantWomenHRP.xls'; //save our workbook as this file name

        header('Content-Type: application/vnd.ms-excel'); //mime type

        header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name

        header('Cache-Control: max-age=0'); //no cache
        //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
        //if you want to save it as .XLSX Excel 2007 format

        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');

        //force user to download the Excel file without writing it to server's HD
        $objWriter->save('php://output');


//        $query2 = "select * from mira_pregnant_women 
//            
//                   inner join mira_women on mira_women.women_id=mira_pregnant_women.women_id
//                   inner join mira_house on mira_house.auto_id=mira_women.house_id
//                   inner join master_area_create_by_super on master_area_create_by_super.region_code=mira_house.region_id
//                   WHERE master_area_create_by_super.app_id=4 
//                   and mira_pregnant_women.pregnant_status=0 
//                   and mira_house.delete_status=0
//                   and mira_pregnant_women.delete_status=0
//                   and mira_women.delete_status=0";
//
//        $query1 = "select mira_women.`name`,master_asha_to_anm_alert.* from master_asha_to_anm_alert 
//                  inner join  mira_pregnant_women on mira_pregnant_women.pregnant_id=master_asha_to_anm_alert.pregnant_id
//                  inner join mira_women on mira_women.women_id=mira_pregnant_women.women_id WHERE 
//                  mira_pregnant_women.pregnant_status=0 and master_asha_to_anm_alert.week_id >0";
    }

    public function testChild() {
        $a = array('a', 'b', 'c');
        print_r($a[1]);
        unset($a[1]);
        print_r(array_values($a));
        $selectedTime = "09:15:00";
        $endTime = strtotime("-16 minutes", strtotime($selectedTime));
        // echo date('h:i:s', $endTime);
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function dateConversionToEnglishDate($dariFormatDate) {
        $tempData = explode('/', $dariFormatDate);
        if (isset($tempData[0]) and isset($tempData[1]) and isset($tempData[2])) {
            return date('Y-m-d', strtotime(str_replace('/', '-', $this->date_conversion->jalali_to_gregorian(trim($tempData[0]), trim($tempData[1]), trim($tempData[2]), 'Y/m/d'))));
        }
    }

    public function getIds() {

        $this->mdb->select('*');
        $this->mdb->from('master_area_create_by_super');
        $this->mdb->where(array('app_id' => 5, 'region_level' => 7));
        $query = $this->mdb->get();
        $updateData = NULL;
        foreach ($query->result_array() as $key => $value) {

            $updateData[] = array('region_code' => $value['region_code'], 'region_level' => $value['region_level'], 'app_id' => $value['app_id']);
        }

        //$this->mdb->insert_batch('mira_transaction_ids',$updateData);
        print_r($updateData);
    }

    public function miraWomenUpload() {
        $region_code = $_GET['id'];
        $file_number = $_GET['no'];
        $file_women = './resources/upload/women/w_' . $file_number . '.xls';
        $this->load->library('excel');
        $objPHPExcel = NULL;
        $cell_collection = NULL;
        $arr_data = NULL;
        $objPHPExcel = PHPExcel_IOFactory::load($file_women);
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
        foreach ($cell_collection as $cell) {
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
            $arr_data[$row][$column] = $data_value;
        }
        $data_women = array();
        $tempId = $this->getWomenTransId($region_code);
        foreach ($arr_data as $key => $value) {
            $data = NULL;
            foreach ($value as $key => $value) {
                switch ($key) {

                    case "B":
                        $data['house_number'] = $value;
                        break;
                    case "C":
                        $data['name'] = $value;
                        break;
                    case "D":
                        $data['husband'] = $value;
                        break;
                    case "E":
                        $data['age'] = $value;
                    case "F":
                        $data['pregnant_status'] = 1;
                        break;
                    case "I":

                        $data['pregnant_date'] = $this->dateConversionToEnglishDate((string) $value);
                        break;
                    case "G":
                        $data['number_of_child'] = $value;
                        break;
                    case "H":
                        $data['no_of_week'] = $value;
                        break;
                }
            }

            $data['region_code'] = $region_code;
            $data['tran_wid'] = $tempId;
            $data_women[] = $data;
            $tempId ++;
        }

        array_shift($data_women);
        //print_r($data_women);
//        $pregnantWomenData=array();
//        $pregnantTempTranId=  $this->getPregnantWomenTransId($region_code);
//        for($i=0;$i<count($data_women);$i++){
//            $tempWomenId=$this->insertWomenData($data_women[$i]);
//            $pregnantWomenData[]=array(
//                'women_id'=>$tempWomenId,
//                'pregnant_date'=>date('Y-m-d',  strtotime($data_women[$i]['pregnant_date'])),
//                'pregnant_status'=>1,
//                'tran_pid'=>$pregnantTempTranId,
//                'region_code'=>$region_code
//                
//            );
//            $pregnantTempTranId++;
//           
//        }
//        $this->mdb->insert_batch('mira_pregnant_women',$pregnantWomenData);
//        $this->mdb->set('tran_wid',$tempId);
//        $this->mdb->set('tran_pid',$pregnantTempTranId);
//        $this->mdb->where('region_code',$region_code);
//        $this->mdb->update('mira_transaction_ids');
//        print_r(json_encode(array('region_code'=>$region_code,'message'=>'success')));
//        
    }

    private function insertWomenData($postData) {
        $tempHouseAutoId = $this->getHouseAutoId($postData['house_number'], $postData['region_code']);
        $tempArrayData = array(
            'house_id' => $tempHouseAutoId,
            'name' => $postData['name'],
            'husband' => $postData['husband'],
            'pregnant_status' => $postData['pregnant_status'],
            'number_of_child' => $postData['number_of_child'],
            'region_code' => $postData['region_code'],
            'tran_wid' => $postData['tran_wid'],
            'age' => $postData['age']
        );
        $this->mdb->insert('mira_women', $tempArrayData);
        return ($this->mdb->affected_rows() > 0) ? $this->mdb->insert_id() : FALSE;
    }

    private function getHouseAutoId($house_number, $regionId) {
        return $this->mdb->select('*')
                        ->from('mira_house')
                        ->where(array('house_number' => $house_number, 'region_id' => $regionId, 'delete_status' => 0))
                        ->get()
                        ->result_array()[0]['auto_id'];
    }

    private function getPregnantWomenTransId($regionId) {
        return $this->mdb->select('*')
                        ->from('mira_transaction_ids')
                        ->where('region_code', $regionId)
                        ->get()
                        ->result_array()[0]['tran_pid'];
    }

    private function getWomenTransId($regionId) {
        return $this->mdb->select('*')
                        ->from('mira_transaction_ids')
                        ->where('region_code', $regionId)
                        ->get()
                        ->result_array()[0]['tran_wid'];
    }

    private function getHouseTransId($regionId) {
        return $this->mdb->select('*')
                        ->from('mira_transaction_ids')
                        ->where('region_code', $regionId)
                        ->get()
                        ->result_array()[0]['tran_hid'];
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function miraHouseUpload() {
        $region_code = $_GET['id'];
        $file_number = $_GET['no'];
        $file_house = './resources/upload/house/h_' . $file_number . '.xls';
        $this->load->library('excel');
        $objPHPExcel = NULL;
        $cell_collection = NULL;
        $arr_data = NULL;
        $objPHPExcel = PHPExcel_IOFactory::load($file_house);
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
        foreach ($cell_collection as $cell) {
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
            $arr_data[$row][$column] = $data_value;
        }
        $data_house = array();
        $tempId = $this->getHouseTransId($region_code);
        foreach ($arr_data as $key => $value) {
            $data = NULL;
            foreach ($value as $key => $value) {
                switch ($key) {
                    case "B":
                        $data['house_number'] = $value;
                        break;
                    case "C":
                        $data['house_head_name'] = $value;
                        break;
                    case "D":
                        $data['total_family_member'] = $value;
                        break;
                    case "E":
                        $data['total_adolenc_girl'] = $value;
                        break;
                    case "F":
                        $data['married_women'] = $value;
                        break;
                    case "G":
                        $data['total_child'] = $value;
                        break;
                }
            }
            $data['unmarried_women'] = 0;
            $data['region_id'] = $region_code;
            $data['region_code'] = $region_code;
            $data['tran_hid'] = $tempId;
            $data_house[] = $data;
            $tempId ++;
        }

        array_shift($data_house);

//        $this->mdb->insert_batch('mira_house',$data_house);
//        $this->mdb->set('tran_hid',$tempId);
//        $this->mdb->where('region_code',$region_code);
//        $this->mdb->update('mira_transaction_ids');
        print_r('success');
//        echo '</br>';
//        print_r($region_code);
        // print_r($data_house);
        //print_r($data_women);
        //print_r($data_house);
//        for($i=0;$i<count($data_house);$i++){
//            $this->mdb->insert('mira_house',$data_house[$i]);
//            $house_id=$this->mdb->insert_id();
//            for($j=0;$j<count($data_women);$j++){
//                if($data_house[$i]['house_number']==$data_women[$j]['house_id']){
//                    $women_insert_data=array(
//                        'house_id'=>$house_id,
//                        'name'=>$data_women[$j]['name'],
//                        'husband'=>$data_women[$j]['husband'],
//                        'pregnant_status'=>1,
//                        'number_of_child'=>$data_women[$j]['number_of_child']
//                    );
//                    $this->mdb->insert('mira_women',$women_insert_data);
//                    $women_id=$this->mdb->insert_id();
//                    $pregnant_data_insert=array(
//                        'women_id'=>$women_id,
//                        'pregnant_date'=>$data_women[$j]['pregnant_date'],
//                        'delivery_status'=>-999,
//                        'pregnant_status'=>1
//                    );
//                    $this->mdb->insert('mira_pregnant_women',$pregnant_data_insert);
//                    $pregnant_id=$this->mdb->insert_id();
//                    print_r('pregnant_id:'.$pregnant_id);
//                    echo '<br>';
//                    print_r('women_id:'.$women_id);
//                    echo '<br>';
//                    print_r('house_id:'.$house_id);
//                    echo '<br>';echo '<br>';
//                    
//                }
//            }
//           
//        }
    }

    public function testCookiesSet() {
        //print_r('welcome');
        //$this->load->helper(array('url', 'form'));
        $this->load->helper('cookie');
        $cookie = array(
            'name' => 'venue_details',
            'value' => 'Hello',
            'expire' => time() + 86500,
            'path' => '/',
        );
        $this->input->set_cookies($cookie);
    }

    public function test() {
        //print_r('welcome');
        //$this->load->view('test');
        $this->load->view('test123');
    }

    public function testCookiesGet() {
        //print_r('welcome');
        $this->load->helper(array('url', 'form'));

        $this->load->helper('cookie');
        $this->input->cookie('venue_details', TRUE);
// this line is useless: the method returns a cookie, filtered for XSS, but you're 
// assigning it to nothing
        $cookie2 = get_cookie('venue_details');
// this your "real" cookie access method
        $data['venuedeets'] = $cookie2['value'];
        var_dump($data);
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function registerHouseByExcelSheet() {
        $_region_code = $_GET['region_code'];
        $_file_number = $_GET['number'];
        $file_house = './resources/excel/house/house' . $_file_number . '.xls';
        $file_women = './resources/excel/women/women' . $_file_number . '.xls';

        $this->load->library('excel');
        $objPHPExcel = NULL;
        $cell_collection = NULL;
        $arr_data = NULL;


        $objPHPExcel = PHPExcel_IOFactory::load($file_house);


        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();

        foreach ($cell_collection as $cell) {
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
            $arr_data[$row][$column] = $data_value;
        }


        $data_house = array();

        foreach ($arr_data as $key => $value) {
            $data = NULL;

            foreach ($value as $key => $value) {
                switch ($key) {
                    case "B":
                        $data['region_id'] = $value;
                        break;
                    case "C":
                        $data['house_number'] = $value;
                        break;
                    case "D":
                        $data['house_head_name'] = $value;
                        break;
                    case "E":
                        $data['total_family_member'] = $value;
                        break;
                    case "F":
                        $data['total_adolenc_girl'] = $value;
                        break;
                    case "G":
                        $data['married_women'] = $value;
                        break;
                    case "H":
                        $data['total_child'] = $value;
                        break;
                    case "I":
                        $data['land_mark'] = $value;
                        break;
                }
            }
            $data['unmarried_women'] = 0;
            $data['region_id'] = $_region_code;
            $data_house[] = $data;
        }
        array_shift($data_house);
        $arr_data = NULL;
        $objPHPExcel = PHPExcel_IOFactory::load($file_women);


        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();

        foreach ($cell_collection as $cell) {
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
            $arr_data[$row][$column] = $data_value;
        }


        $data_women = array();

        foreach ($arr_data as $key => $value) {
            $data = NULL;

            foreach ($value as $key => $value) {
                switch ($key) {
                    case "A":
                        $data['house_id'] = $value;
                        break;
                    case "B":
                        $data['name'] = $value;
                        break;
                    case "C":

                        $data['husband'] = $value;
                        break;
                    case "D":
                        $data['age'] = $value;
                        break;
                    case "E":
                        $data['pregnant_status'] = $value;
                        break;
                    case "F":
                        $data['number_of_child'] = $value;
                        break;
                    case "I":
                        $data['pregnant_date'] = date('Y-m-d', strtotime(str_replace('/', '-', trim($value))));

                        break;
                }
            }

            $data_women[] = $data;
        }

        array_shift($data_women);
        //print_r($data_women);
        //print_r($data_house);
//        for($i=0;$i<count($data_house);$i++){
//            $this->mdb->insert('mira_house',$data_house[$i]);
//            $house_id=$this->mdb->insert_id();
//            for($j=0;$j<count($data_women);$j++){
//                if($data_house[$i]['house_number']==$data_women[$j]['house_id']){
//                    $women_insert_data=array(
//                        'house_id'=>$house_id,
//                        'name'=>$data_women[$j]['name'],
//                        'husband'=>$data_women[$j]['husband'],
//                        'pregnant_status'=>1,
//                        'number_of_child'=>$data_women[$j]['number_of_child']
//                    );
//                    $this->mdb->insert('mira_women',$women_insert_data);
//                    $women_id=$this->mdb->insert_id();
//                    $pregnant_data_insert=array(
//                        'women_id'=>$women_id,
//                        'pregnant_date'=>$data_women[$j]['pregnant_date'],
//                        'delivery_status'=>-999,
//                        'pregnant_status'=>1
//                    );
//                    $this->mdb->insert('mira_pregnant_women',$pregnant_data_insert);
//                    $pregnant_id=$this->mdb->insert_id();
//                    print_r('pregnant_id:'.$pregnant_id);
//                    echo '<br>';
//                    print_r('women_id:'.$women_id);
//                    echo '<br>';
//                    print_r('house_id:'.$house_id);
//                    echo '<br>';echo '<br>';
//                    
//                }
//            }
//           
//        }
    }

    /**
     * 
     * 
     * 
     * 
     */
//    public function updateHistory() {
//        $auto_id_array = explode(',', $_GET['id']);
//        $this->db->where_in('autoId', $auto_id_array);
//        $this->db->update('master_patient_active_compliance_history', array('complianceMode' => 'dots', 'comlianceURL' => 'dots'));
//        echo 'success';
//    }
    /**
     * 
     * 
     * 
     * 
     */
    public function getPatientHistory() {

        $user = $this->session->userdata('loginDetails');
        $query = "SELECT `master_full_registration`.`patientName`,`master_patient_active_compliance_history`.`tbPatientId` ,`master_patient_active_compliance_history`.`complianceMode`,`master_patient_active_compliance_history`.`complianceDate`,`master_patient_active_compliance_history`.`comlianceURL`,`master_patient_active_compliance_history`.`complianceUpdateDate`
                  FROM  `master_patient_active_compliance_history` 
                  INNER JOIN  `master_full_registration` ON  `master_full_registration`.`tbPatientId` = `master_patient_active_compliance_history`.`tbPatientId` 
                  WHERE  `master_patient_active_compliance_history`.`tbPatientId` 
                  IN (
                      SELECT `master_patient_dots_planner`.`tbPatientId` FROM `master_patient_dots_planner` inner join `mapping_tb_unit_patient` on `mapping_tb_unit_patient`.`tbPatientId`= `master_patient_dots_planner`.`tbPatientId`WHERE `upadet_patient`=1 and `mapping_tb_unit_patient`.`tbUnitId` in(select `tbUnitId` from `mapping_district_tb_unit_dtu_tb_unit` where `districtTBUnitId`=(select `districtTBUnitId` from `mapping_district_tb_unit_staff` where `empId`=?))
                     )";
        $query_result = $this->db->query($query, $user['empId']);

        /* ............... */
        $excel_data_head = NULL;
        $excel_data = NULL;
        $i = 0;
        foreach ($query_result->result_array() as $key => $row) {
            if ($i == 0) {
                foreach ($row as $key => $value) {
                    $excel_data_head[$key] = $key;
                }
                $excel_data[] = $excel_data_head;
                $i++;
            }
            $excel_data[] = $row;
        }
        //print_r($excel_data);

        /* .............. */
        $this->load->library('excel');
        //activate worksheet number 1
        $this->excel->setActiveSheetIndex(0);
        //name the worksheet
        $this->excel->getActiveSheet()->setTitle('History List');

        $this->excel->getActiveSheet()->fromArray($excel_data);

        $filename = 'PatientHistory.xls'; //save our workbook as this file name

        header('Content-Type: application/vnd.ms-excel'); //mime type

        header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name

        header('Cache-Control: max-age=0'); //no cache
        //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
        //if you want to save it as .XLSX Excel 2007 format

        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');

        //force user to download the Excel file without writing it to server's HD
        $objWriter->save('php://output');
    }

    public function getChildDetail() {
        $region_code = $_GET['asha_id'];
        //$region_code=25;
//        $query = "select mira_child.child_id,mira_child.child_name,mira_child.gender,master_user_details.user_name from mira_child 
//                  inner join master_login_user on master_login_user.create_region_id=mira_child.region_code
//                  inner join master_user_details on master_user_details.user_login_id=master_login_user.user_login_id
//                   WHERE mira_child.region_code=? and mira_child.delete_status=0";
//       $query_result = $this->mdb->query($query, $region_code);
        // print_r($query_result->result_array());
        /* ............... */
        $excel_data_head = NULL;
        $excel_data = NULL;
        $i = 0;
        foreach ($query_result->result_array() as $key => $row) {
            if ($i == 0) {
                foreach ($row as $key => $value) {
                    $excel_data_head[$key] = $key;
                }
                $excel_data[] = $excel_data_head;
                $i++;
            }
            $excel_data[] = $row;
        }
        //print_r($excel_data);

        /* .............. */
        $this->load->library('excel');
        //activate worksheet number 1
        $this->excel->setActiveSheetIndex(0);
        //name the worksheet
        $this->excel->getActiveSheet()->setTitle('Child List Incorrect');

        $this->excel->getActiveSheet()->fromArray($excel_data);

        $filename = $region_code . '.xls'; //save our workbook as this file name

        header('Content-Type: application/vnd.ms-excel'); //mime type

        header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name

        header('Cache-Control: max-age=0'); //no cache
        //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
        //if you want to save it as .XLSX Excel 2007 format

        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');

        //force user to download the Excel file without writing it to server's HD
        //$objWriter->save('php://output');
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function download() {

        $this->db->select('*');
        $this->db->from('patientrecruitedandhilmisirpatient');
        $query = $this->db->get();
        $excel_data_head = NULL;
        $excel_data = NULL;
        $i = 0;
        foreach ($query->result_array() as $key => $row) {
            if ($i == 0) {
                foreach ($row as $key => $value) {
                    $excel_data_head[$key] = $key;
                }
                $excel_data[] = $excel_data_head;
                $i++;
            }
            $excel_data[] = $row;
        }

        $this->load->library('excel');
        //activate worksheet number 1
        $this->excel->setActiveSheetIndex(0);
        //name the worksheet
        $this->excel->getActiveSheet()->setTitle('History List');

        $this->excel->getActiveSheet()->fromArray($excel_data);

        $filename = 'TotalPatientList.xls'; //save our workbook as this file name

        header('Content-Type: application/vnd.ms-excel'); //mime type

        header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name

        header('Cache-Control: max-age=0'); //no cache
        //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
        //if you want to save it as .XLSX Excel 2007 format

        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');

        //force user to download the Excel file without writing it to server's HD
        $objWriter->save('php://output');
    }

    /**
     * 
     * 
     * 
     */
    public function getPatientVideo() {
        $active_compliance = array();
        $this->db->select('*');
        $this->db->from('master_patient_dots_planner');
        $this->db->join('master_full_registration', 'master_full_registration.tbPatientId=master_patient_dots_planner.tbPatientId', 'INNER');
        $this->db->where(array('upadet_patient' => 1));
        $query = $this->db->get();
        $query2 = "SELECT COUNT(tbPatientId) as count_video FROM master_patient_active_compliance_history WHERE tbPatientId = ? AND complianceMode= 'video'";
        $query3 = "SELECT COUNT(tbPatientId) as count_missed FROM master_patient_active_compliance_history WHERE tbPatientId = ? AND complianceMode= 'missed'";
        $query4 = "SELECT COUNT(tbPatientId) as count_dots FROM master_patient_active_compliance_history WHERE tbPatientId = ? AND complianceMode= 'dots'";
        foreach ($query->result_array() as $value) {
            /* .......... */
            $temp1 = $this->db->query($query2, array($value['tbPatientId']));
            $temp_query1 = $temp1->row_array();
            /* .......... */
            $temp2 = $this->db->query($query3, array($value['tbPatientId']));
            $temp_query2 = $temp2->row_array();
            /* .......... */
            $temp3 = $this->db->query($query4, array($value['tbPatientId']));
            $temp_query3 = $temp3->row_array();
            /* .......... */
            $active_compliance[] = array('total_dots' => $temp_query3['count_dots'], 'missed_dose' => $temp_query2['count_missed'], 'total_video' => $temp_query1['count_video'], 'tbPatientId' => $value['tbPatientId'], 'patientName' => $value['patientName'], 'patientDoseStartDate' => $value['patientDoseStartDate'], 'patientCurrentPhase' => $value['patientCurrentPhase'], 'patientCategory' => $value['patientCategory']);
        }
        $data['history'] = $active_compliance;
        $this->load->view('dashboard/total_video_with_id', $data);
        //print_r($active_compliance);
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function getHistory() {

        $this->db->select('*');
        $this->db->from('master_patient_active_compliance_history');
        $this->db->where(array('complianceMode' => 'video', 'update' => 2, 'tbPatientId' => $_GET['id']));
        $this->db->order_by('autoId', 'asc');
        $query = $this->db->get();
        $this->load->library('excel');
        //activate worksheet number 1
        $this->excel->setActiveSheetIndex(0);
        //name the worksheet
        $this->excel->getActiveSheet()->setTitle('History List');

        $this->excel->getActiveSheet()->fromArray($query->result_array());

        $filename = $_GET['id'] . '.xls'; //save our workbook as this file name

        header('Content-Type: application/vnd.ms-excel'); //mime type

        header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name

        header('Cache-Control: max-age=0'); //no cache
        //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
        //if you want to save it as .XLSX Excel 2007 format

        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');

        //force user to download the Excel file without writing it to server's HD
        $objWriter->save('php://output');
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function getHistoryExcel() {
        $this->db->select('*');
        $this->db->from('master_patient_active_compliance_history');
        $this->db->where(array('complianceMode' => 'video', 'update' => 2));
        $this->db->order_by('tbPatientId', 'asc');
        $query = $this->db->get();

        $this->load->library('excel');
        //activate worksheet number 1
        $this->excel->setActiveSheetIndex(0);
        //name the worksheet
        $this->excel->getActiveSheet()->setTitle('History List');

        $this->excel->getActiveSheet()->fromArray($query->result_array());

        $filename = 'hilmi_sir_patient_history_list.xls'; //save our workbook as this file name

        header('Content-Type: application/vnd.ms-excel'); //mime type

        header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name

        header('Cache-Control: max-age=0'); //no cache
        //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
        //if you want to save it as .XLSX Excel 2007 format

        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');

        //force user to download the Excel file without writing it to server's HD
        $objWriter->save('php://output');




//        $this->load->library('excel');
//        $this->excel->setActiveSheetIndex(0);
//        $this->excel->getActiveSheet()->setTitle('Users list');
//        $this->excel->getActiveSheet()->fromArray($query->result_array());
//        $filename = 'HilmiSirHistory.xls'; //save our workbook as this file name
//
//        header('Content-Type: application/vnd.ms-excel'); //mime type
//
//        header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name
//
//        header('Cache-Control: max-age=0'); //no cache
//        //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
//        //if you want to save it as .XLSX Excel 2007 format
//
//        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
//
//        //force user to download the Excel file without writing it to server's HD
//        $objWriter->save('./complianceMode/102/video/'.$filename);
    }

    public function readExcelFile() {
        $file = './assets/sgmlogin.xls';

//load the excel library
        $this->load->library('excel');

//read file from path
        $objPHPExcel = PHPExcel_IOFactory::load($file);

//get only the Cell Collection
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();

//extract to a PHP readable array format
        foreach ($cell_collection as $cell) {
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
            $arr_data[$row][$column] = $data_value;
            //header will/should be in row 1 only. of course this can be modified to suit your need.
        }



        foreach ($arr_data as $key => $value) {
            $data = NULL;
            foreach ($value as $key => $value) {

                switch ($key) {
                    case "A":
                        $data['empId'] = $value;
                        break;
                    case "B":

                        $data['empName'] = $value;
                        break;
                    case "C":

                        $data['username'] = $value;
                        break;
                    case "D":
                        $data['password'] = $value;
                        break;
                    case "E":

                        $data['isActive'] = $value;

                        break;
                    case "F":
                        $data['hirarchyId'] = $value;
                        break;
                    case "G":
                        $data['createdBy'] = $value;
                        break;
                    case "H":
                        $data['createdDate'] = $value;
                        break;
                    case "I":
                        $data['isLogin'] = $value;
                        break;
                    case "J":
                        $data['subHirarchyId'] = $value;
                        break;
                    case "K":
                        $data['blockId'] = $value;
                        break;
                    case "L":
                        $data['VillageId'] = $value;
                        break;
                    case "M":
                        $data['villageName'] = $value;
                        break;
                    case "N":
                        $data['subvillage'] = $value;
                        break;
                    case "O":
                        $data['ashaId'] = $value;
                        break;
                    case "P":
                        $data['StateId'] = $value;
                        break;
                    case "Q":
                        $data['DistrictId'] = $value;
                        break;
                    case "R":
                        $data['Countryid'] = $value;
                        break;
                    case "S":
                        $data['Attendance'] = $value;
                        break;
                }
            }
            //$this->db->insert('master_login',$data);
            // print_r($data);
            echo '</br>';
        }
//send the data in an array format
        //print_r($arr_data);
        //$UNIX_DATE = ($arr_data[2]['C'] - 25569) * 86400;
        //print_r(date("d-m-Y H:i:s", $UNIX_DATE));
        //print_r(date('Y-m-d H:m:d'));
        // $data['values'] = $arr_data;
        //print_r($data);
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function uploadFile() {
        $_patient_id = 'IND.HR.MWT.TBU5.1';
        $this->db->select('*');
        $this->db->from('master_patient_active_compliance_history');
        $this->db->where(array('tbPatientId' => $_patient_id, 'complianceMode' => 'video'));
        $query = $this->db->get();
        $file_name = NULL;
        foreach ($query->result_array() as $value) {
            $file_name[] = $value['comlianceURL'];
        }
    }

//    /**
//     * 
//     * This function used for excel download
//     * 
//     * 
//     */
    public function downloadExcel() {
        $this->load->library('excel');
        //activate worksheet number 1
        $this->excel->setActiveSheetIndex(0);
        //name the worksheet
        $this->excel->getActiveSheet()->setTitle('Users list');

        // load database
        $active_compliance = array();
        $this->db->select('*');
        $this->db->from('master_patient_dots_planner');
        $this->db->join('master_full_registration', 'master_full_registration.tbPatientId=master_patient_dots_planner.tbPatientId', 'INNER');
        $this->db->where(array('upadet_patient' => 1));
        $query = $this->db->get();
        $query2 = "SELECT COUNT(tbPatientId) as count_video FROM master_patient_active_compliance_history WHERE tbPatientId = ? AND complianceMode= 'video'";
        $query3 = "SELECT COUNT(tbPatientId) as count_missed FROM master_patient_active_compliance_history WHERE tbPatientId = ? AND complianceMode= 'missed'";
        $query4 = "SELECT COUNT(tbPatientId) as count_dots FROM master_patient_active_compliance_history WHERE tbPatientId = ? AND complianceMode= 'dots'";
        foreach ($query->result_array() as $value) {
            /* .......... */
            $temp1 = $this->db->query($query2, array($value['tbPatientId']));
            $temp_query1 = $temp1->row_array();
            /* .......... */
            $temp2 = $this->db->query($query3, array($value['tbPatientId']));
            $temp_query2 = $temp2->row_array();
            /* .......... */
            $temp3 = $this->db->query($query4, array($value['tbPatientId']));
            $temp_query3 = $temp3->row_array();
            /* .......... */
            $active_compliance[] = array('total_dots' => $temp_query3['count_dots'], 'missed_dose' => $temp_query2['count_missed'], 'total_video' => $temp_query1['count_video'], 'tbPatientId' => $value['tbPatientId'], 'patientName' => $value['patientName'], 'patientDoseStartDate' => $value['patientDoseStartDate'], 'patientCurrentPhase' => $value['patientCurrentPhase'], 'patientCategory' => $value['patientCategory']);
        }



        // read data to active sheet
        $this->excel->getActiveSheet()->fromArray($active_compliance);

        $filename = 'test.xls'; //save our workbook as this file name

        header('Content-Type: application/vnd.ms-excel'); //mime type

        header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name

        header('Cache-Control: max-age=0'); //no cache
        //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
        //if you want to save it as .XLSX Excel 2007 format

        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');

        //force user to download the Excel file without writing it to server's HD
        $objWriter->save('./complianceMode/102/video/' . $filename);
    }

    /**
     * 
     * This function update dot planner master 
     * 
     * 
     */
    public function updateDotPlanner() {
        $update = array();
        $this->load->model('mophi_model');
        $old_date = date('Y-m-d', strtotime($_GET['date']));
        $new_date = date('Y-m-d');
        $patient_type = 'MWF';
        $next_follow_up_date = NULL;
        $update['patientNextDoseTakenDate'] = $this->mophi_model->nextDoseDate($patient_type, date('N', strtotime($new_date)), $new_date);
        $update['patientLastDoseTakenDate'] = date("Y-m-d", strtotime($update['patientNextDoseTakenDate'] . "-1 day"));
        $total_dose = $this->mophi_model->getTotalDoseBetweenDate($_GET['date'], $new_date, 'MWF');
        $update['patientPhaseIStartDate'] = date('Y-m-d', strtotime($old_date));
        $update['patientTotalMissDoses'] = 0;
        $update['patient_current_status'] = 1;
        $update['patientCategory'] = 'cat i';
        $registration_date = date('Y-m-d', strtotime($_GET['date'] . "-1 day"));
        $update['patientTotalDoseInPhaseI'] = 24;
        $update['patient_dose_start_date_outside'] = $old_date;
        if ($total_dose <= 24) {
            $update['patientTotalDoseInPhaseII'] = 0;
            $update['patientTotalDoseTakenInPhaseII'] = 0;
            $update['phase2_status'] = 0;
            $update['firstExtensionStatus'] = 'NULL';
            $update['groupStatus'] = 1;
            $update['nextFollowUpDate'] = $this->mophi_model->getSputumDate(22, $old_date);
            $update['patientTotalDoseTakenInPhaseI'] = $total_dose;
            $next_follow_up_date = $this->mophi_model->getSputumDate(22, $old_date);
            $update['patientDoseStartDate'] = date('Y-m-d', strtotime($old_date));
            $update['complianceMethod'] = 1;
            $update['patientNextDoseMode'] = 'video';
        } else {
            $update['groupStatus'] = 0;
            $update['patientTotalDoseInPhaseII'] = 54;
            $update['patientCurrentPhase'] = 'phase2';
            $update['phase2_status'] = 1;
            $update['firstExtensionStatus'] = 0;
            $update['nextFollowUpDate'] = $this->mophi_model->getSputumDate(46, $old_date);
            $update['patientTotalDoseTakenInPhaseI'] = 24;
            $update['patientTotalDoseTakenInPhaseII'] = $total_dose - 24;
            $update['patientDoseStartDate'] = $this->mophi_model->getSputumDate(25, $old_date);
            $update['patientPhaseIIStartDate'] = $this->mophi_model->getSputumDate(25, $old_date);
            $update['patientNextDoseMode'] = 'dots';
            $update['compliance_method_phase2'] = 3;
        }

        $active_complianc_data = $this->updateActiveComplianceHistory($total_dose, $old_date, $_GET['patient_id']);
        $this->db->trans_begin();

        $this->db->where('tbPatientId', $_GET['patient_id']);
        $this->db->update('master_full_registration', array('dateOfRegistration' => $registration_date, 'patient_dose_start_date_outside' => $old_date));
        /**/
        $this->db->where('tbPatientId', $_GET['patient_id']);
        $this->db->update('master_patient_dots_planner', $update);
        /* This query upadte the master history table */
        $this->db->where(array('tbPatientId' => $_GET['patient_id']));
        $this->db->update('master_patient_active_compliance_history', array('update' => 1));
        /* This query update batch file in master active compliance history */
        $this->db->insert_batch('master_patient_active_compliance_history', $active_complianc_data);
        /* if all query run successfully then data is comited oterwise is rollback */
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
            echo 'success';
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function updateActiveComplianceHistory($_total_dose = NULL, $_dose_start_date = NULL, $_patient_id = NULL) {
        $this->load->model('mophi_model');
        $compliance_history_date = NULL;
        $url = NULL;
        if ($_total_dose <= 24) {
            for ($i = 1; $i <= $_total_dose; $i++) {
                if ($i == 1) {
                    $url = "complianceMode/" . $_patient_id . "/video/" . $_patient_id . "_" . $_dose_start_date . "_XBC.mp4";
                    $compliance_history_date[] = array('complianceMode' => 'video', 'tbPatientId' => $_patient_id, 'complianceDate' => $_dose_start_date, 'comlianceURL' => $url, 'update' => 2);
                } else {
                    $compliance_date = $this->mophi_model->getSputumDate($i, $_dose_start_date);
                    $url = "complianceMode/" . $_patient_id . "/video/" . $_patient_id . "_" . $compliance_date . "_XBC.mp4";
                    $compliance_history_date[] = array('complianceMode' => 'video', 'tbPatientId' => $_patient_id, 'complianceDate' => $compliance_date, 'comlianceURL' => $url, 'update' => 2);
                }
            }
        } else {
            for ($i = 1; $i <= 24; $i++) {
                if ($i == 1) {
                    $url = "complianceMode/" . $_patient_id . "/video/" . $_patient_id . "_" . $_dose_start_date . "_XBC.mp4";
                    $compliance_history_date[] = array('complianceMode' => 'video', 'tbPatientId' => $_patient_id, 'complianceDate' => $_dose_start_date, 'comlianceURL' => $url, 'update' => 2);
                } else {
                    $compliance_date = $this->mophi_model->getSputumDate($i, $_dose_start_date);
                    $url = "complianceMode/" . $_patient_id . "/video/" . $_patient_id . "_" . $compliance_date . "_XBC.mp4";
                    $compliance_history_date[] = array('complianceMode' => 'video', 'tbPatientId' => $_patient_id, 'complianceDate' => $compliance_date, 'comlianceURL' => $url, 'update' => 2);
                }
            }
            for ($i = 0; $i < $_total_dose - 24; $i++) {

                $compliance_date = $this->mophi_model->getSputumDate(($i + 25), $_dose_start_date);
                $compliance_history_date[] = array('complianceMode' => 'dots', 'tbPatientId' => $_patient_id, 'complianceDate' => $compliance_date, 'comlianceURL' => 'NULL', 'update' => 2);
            }
        }

        return $compliance_history_date;
    }

    /**
     * 
     * 
     * This function upadte active compliance history.
     * Removr all duplicate data from the history table.
     * 
     */
    public function updateActiveHistoryPlan() {
        $this->db->select('*');
        $this->db->from('master_patient_active_compliance_history');
        $this->db->where('tbPatientId', $_GET['patient_id']);
        $query = $this->db->get();
        $delete_array = NULL;
        //print_r($query->result_array()[0]);
        $patent_histry_array = NULL;
        if ($query->num_rows() > 0) {
            $patent_histry_array = $query->result_array();
            for ($i = 0; $i < count($patent_histry_array); $i++) {
                for ($j = $i; $j < count($patent_histry_array); $j++) {
                    if ($patent_histry_array[$i]['complianceDate'] == $patent_histry_array[$j]['complianceDate'] and $i != $j) {
                        if ($patent_histry_array[$i]['complianceMode'] == 'missed') {
                            $delete_array[] = $patent_histry_array[$i];
                        } elseif ($patent_histry_array[$j]['complianceMode'] == 'missed') {
                            $delete_array[] = $patent_histry_array[$j];
                        } elseif ($patent_histry_array[$i]['complianceMode'] == 'dots') {
                            $delete_array[] = $patent_histry_array[$i];
                        } elseif ($patent_histry_array[$j]['complianceMode'] == 'dots') {
                            $delete_array[] = $patent_histry_array[$j];
                        } else {
                            $delete_array[] = $patent_histry_array[$i];
                        }
                    }
                }
            }
        }
        /*
         * this scrip are update active istory plan.
         */
        //print_r($delete_array);
        foreach ($delete_array as $value) {
            $this->db->where(array('autoId' => $value['autoId']));
            $this->db->update('master_patient_active_compliance_history', array('update' => 1));
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function getPatientId() {
        $this->db->select('tbPatientId');
        $this->db->from('master_patient_dots_planner');
        $this->db->where('upadet_patient', 1);
        $query = $this->db->get();

        foreach ($query->result_array() as $value) {

            $this->updateActiveHistoryPlanner($value['tbPatientId']);
        }
    }

    private function updateActiveHistoryPlanner($_patient_id = NULL) {
        $this->db->select('*');
        $this->db->from('master_patient_active_compliance_history');
        $this->db->where('tbPatientId', $_patient_id);
        $query = $this->db->get();
        $delete_array = NULL;
        //print_r($query->result_array()[0]);
        $patent_histry_array = NULL;
        if ($query->num_rows() > 0) {
            $patent_histry_array = $query->result_array();
            for ($i = 0; $i < count($patent_histry_array); $i++) {
                for ($j = $i; $j < count($patent_histry_array); $j++) {
                    if ($patent_histry_array[$i]['complianceDate'] == $patent_histry_array[$j]['complianceDate'] and $i != $j) {
                        if ($patent_histry_array[$i]['complianceMode'] == 'missed') {
                            $delete_array[] = $patent_histry_array[$i];
                        } elseif ($patent_histry_array[$j]['complianceMode'] == 'missed') {
                            $delete_array[] = $patent_histry_array[$j];
                        } elseif ($patent_histry_array[$i]['complianceMode'] == 'dots') {
                            $delete_array[] = $patent_histry_array[$i];
                        } elseif ($patent_histry_array[$j]['complianceMode'] == 'dots') {
                            $delete_array[] = $patent_histry_array[$j];
                        } else {
                            $delete_array[] = $patent_histry_array[$i];
                        }
                    }
                }
            }
        }
        /*
         * this scrip are update active istory plan.
         */

        if ($delete_array != NULL and count($delete_array) > 0) {
            foreach ($delete_array as $value) {
                $this->db->where(array('autoId' => $value['autoId']));
                $this->db->update('master_patient_active_compliance_history', array('update' => 1));
            }
        }
    }

    /**
     * 
     * This function authenticate the login user and 
     * return the authentication to mologin end.
     * @param int $iemi this number is uniquely define of mobile.
     * @param string $user_id this is user login id at mobile device.
     * @param string $password Description. 
     * @return boolean if user exist return true otherwise return false.
     * 
     */

    /**
     * 
     * 
     * 
     */
    public function get_compliance_patient1() {
        $error = NULL;
        $data = NULL;
        $request_data = $this->getRequestData($_SERVER);
        $query = $this->db->get_where('master_patient_dots_planner', array('dotsProviderId' => $request_data['empId'], 'complianceMethod' => $request_data['complianceMethod']));
//        $query=  $this->db->get_where('master_patient_dots_planner',array('observerId'=>616,'complianceMethod'=>1));
        if ($query->num_rows() > 0) {
            $array = ($query->result());
            foreach ($array as $value) {

                $query2 = $this->db->get_where('master_full_registration', array('tbPatientId' => $value->tbPatientId));
                $data[] = array('tbPatientId' => $query2->result()[0]->tbPatientId, 'name' => $query2->result()[0]->patientName, 'mode' => $value->patientNextDoseMode, 'startDate' => $value->patientDoseStartDate);
//              print_r($value);
            }
        }

        for ($i = 0; $i < 30; $i++) {
            if ($i % 2 == 0) {
                $data[] = array('tbPatientId' => 'IND.HR.MWT.TBU1.' . $i, 'name' => 'test2' . $i, 'mode' => 'video', 'startDate' => '2015-10-01');
            } else {
                $data[] = array('tbPatientId' => 'IND.HR.MWT.TBU1.' . $i, 'name' => 'test2' . $i, 'mode' => 'video', 'startDate' => '2015-10-01');
            }
        }



        print_r(json_encode(array('error' => $error, 'data' => $data)));
    }

    /**
     * @author Abdul Muttaliob <muttalib@zmq.in>.
     * @return array string This function return patient list list.

     * 
     * 
     */
    public function get_compliance_patient() {
        $error = NULL;
        $data = NULL;
        $request_data = $this->getRequestData($_SERVER);
        $query = $this->db->get_where('master_patient_dots_planner', array('dotsProviderId' => $request_data['empId'], 'complianceMethod' => $request_data['complianceMethod']));
//        $query=  $this->db->get_where('master_patient_dots_planner',array('observerId'=>616,'complianceMethod'=>1));
        if ($query->num_rows() > 0) {
            $array = ($query->result());
            foreach ($array as $value) {
                $query2 = $this->db->get_where('master_full_registration', array('tbPatientId' => $value->tbPatientId));
                $data[] = array('tbPatientId' => $query2->result()[0]->tbPatientId, 'name' => $query2->result()[0]->patientName, 'mode' => $value->patientNextDoseMode, 'startDate' => $value->patientDoseStartDate, 'patientDOTDays' => $value->patientDOTDays);
//              print_r($value);
            }
        }


        print_r(json_encode(array('error' => $error, 'data' => $data)));
    }

    /**
     * 
     * 
     */

    /**
     * 
     * 
     */
    public function dot_compliance_submit() {
        $response_data = NULL;
        $request_data = $this->getRequestData($_SERVER);
        /*
          $this->load->db();
          $this->db->insert();
          print_r($request_data);
         */


        foreach (json_decode($request_data['observerId'], TRUE) as $value) {
            $next_dose_date = $this->nextDoseDate($value['patientRegime'], date("N"), date('Y-m-d'));
            $temp_response = $this->patient_model->submitCompliance(array('nextPatientDoseTakenDate' => $next_dose_date, 'patientLastDoseTakenDate' => $value['patientLastDoseTakenDate'], 'tbPatientId' => $value['tbPatientId'], 'complianceMode' => $value['complianceMode']), $value['complianceMode']);
            if ($temp_response['success']) {
                // dot compliance method is updated.
                /*
                 * observerId is equal to status.
                 */

                $response_data[] = array('tbPatientId' => $value['tbPatientId'], 'observerId' => TRUE);
            } else {
                $response_data[] = array('tbPatientId' => $value['tbPatientId'], 'observerId' => FALSE);
                // compliance method id not updated.    
            }
            print_r(json_encode($response_data));
        }
    }

    public function dot_compliance_submit1() {
        $response_data = NULL;
        $request_data = $this->getRequestData($_SERVER);
        // $this->load->db();
        //$this->db->insert();
        //print_r($request_data['observerId']);
        // print_r(json_encode($request_data['observerId']));
        //print_r((array('error'=>NULL,'observerId'=>$request_data)));
        foreach (json_decode($request_data['observerId'], TRUE) as $value) {
            print_r($value);
        }
        //$next_dose_date =  $this->nextDoseDate($request_data['patientRegime'], date("N"), date('Y-m-d'));
        ///$request_data= $this->patient_model->submitCompliance(array('nextPatientDoseTakenDate'=>$next_dose_date,'patientLastDoseTakenDate'=>$request_data['patientLastDoseTakenDate'],'tbPatientId'=>$request_data['tbPatientId'],'complianceMode'=>$request_data['complianceMode']), $request_data['complianceMode']);
//        if($request_data['message']){
//            // dot compliance method is updated.
//        }  else {
//        // compliance method id not updated.    
//        }
//        
    }

    /**
     * 
     * This function return next dose date of the patient.
     * 
     */
    private function nextDoseDate($_patient_regime, $_now_day, $_today_date) {
        $nextPatientDoseDate = '';
        if ($_patient_regime == 'TTS') {
            if ($_now_day == '2' || $_now_day == '3') {

                $nextPatientDoseDate = date('Y-m-d', strtotime($_today_date . 'next thursday'));
            } elseif ($_now_day == '4' || $_now_day == '5') {

                $nextPatientDoseDate = date('Y-m-d', strtotime($_today_date . 'next saturday'));
            } else {

                $nextPatientDoseDate = date('Y-m-d', strtotime($_today_date . 'next tuesday'));
            }
        } elseif ($_patient_regime == 'MWF') {
            if ($_now_day == '1' || $_now_day == '2') {

                $nextPatientDoseDate = date('Y-m-d', strtotime($_today_date . 'next wednesday'));
            } elseif ($_now_day == '3' || $_now_day == '4') {

                $nextPatientDoseDate = date('Y-m-d', strtotime($_today_date . 'next friday'));
            } else {

                $nextPatientDoseDate = date('Y-m-d', strtotime($_today_date . 'next monday'));
            }
        }

        return $nextPatientDoseDate;
    }

    /**
     * this function return next date of dose taken date.
     */
    private function getUserName() {
        $user = NULL;
        $password = NULL;
        $name = NULL;
        $pincode = NULL;
    }

    private function getNextDoseDate($day_index = NULL) {
        if ($day_index != NULL) {
            switch ($day_index) {
                case 2:
                case 3:
                    $nextPatientDoseDate = date('Y-m-d', strtotime($todayDate . 'next thursday'));
                    break;
                case 4:
                case 5:
                    $nextPatientDoseDate = date('Y-m-d', strtotime($todayDate . 'next saturday'));
                    break;
                default :
                    $nextPatientDoseDate = date('Y-m-d', strtotime($todayDate . 'next tuesday'));
                    break;
            }
        }
    }

    /**
     * 
     * this function used fro as a testing purpose.
     * 
     */
    public function login() {
        $error = NULL;
        $data = NULL;
        $request_data = $this->getRequestData($_SERVER);

//        $query=  $this->db->get_where('master_login',array('username'=>'babita','password'=>1111,'subHirarchyId'=>6));
        $query = $this->db->get_where('master_login', array('username' => $request_data['username'], 'password' => $request_data['password'], 'hirarchyId' => $request_data['subHirarchyId']));

        $user = $query->result();

        if ($query->num_rows() > 0) {
            if ($user[0]->isActive == 1) {

                $query = $this->db->get_where('master_device', array('empId' => $user[0]->empId));

                $device = $query->result();

                if ($query->num_rows() > 0 && $device[0]->device_imei == $request_data['device_imei']) {
                    $data['ashaId'] = $user[0]->ashaId;
                    $data['observerId'] = $user[0]->empId;
                } else {
                    $error = "user exist,activate by the admin but user device are not match correctly.";
                    // user exist,activate by the admin but user device are not match correctly.
                }
            } else {
                $error = "user register but not actvate by the admin.";

                // user register but not actvate by the admin;
            }
        } else {
            $error = "user id not register.";
            //user id not register
        }
        print_r(json_encode(array('error' => $error, 'data' => $data)));
    }

    /**
     * 
     * @param array $server_data This data come from the mobile side.
     * @return array This function return the array of key value pair.
     * 
     * 
     */
    private function getRequestData($server) {
        $_request_data = NULL;
        switch ($server['REQUEST_METHOD']) {
            case "POST":
                if (isset($server['HTTP_JSON'])) {
                    $_request_data = $this->setRequestData(json_decode($server['HTTP_JSON'], TRUE));
                } else {
                    $_request_data = $this->setRequestData($_POST);
                }
                break;
            case "GET":
                if (isset($server['HTTP_JSON'])) {
                    $_request_data = $this->setRequestData(json_decode($server['HTTP_JSON'], TRUE));
                } else {
                    $_request_data = $this->setRequestData($_GET);
                }
                break;
            default :
                break;
        }
        return $_request_data;
    }

    /**
     * @param array $server_request_data Pass the data get from the server request or mobile request.
     * @return array This function return array data with in class.
     */
    private function setRequestData($request_data) {
        $req_data = NULL;
        foreach ($request_data as $key => $value) {
            $req_data[$key] = $value;
        }
        return $req_data;
    }

    /**
     * 
     * 
     * 
     */
    public function test123() {
        echo date("d-m-Y h:i:s", strtotime("+90 minutes"));
    }

    /**
     * 
     * 
     * 
     * 
     */
    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;
        }
    }

}
