<?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 Mira_service_model
 *
 * @author zmq163
 */
class Mira_service_asha_model extends CI_Model {

    //put your code here
    var $mdb;
    var $vdb;

    public function __construct() {
        parent::__construct();
        $this->mdb = $this->load->database('mdb', TRUE);
        $this->load->model('Registration_house_women_child_model');
    }
    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function getChildVaccineMasterPlannerAppId($appId=NULL){
        if($appId!=NULL){
        $this->mdb->select('ca.app_id as appId,pl.Id as vaccineId,pl.vaccinecode as vaccineName,pl.dependentId as dependentVaccineId,pl.startday as doseStartDayFrom,pl.endday as doseEndDayTo,pl.plannername as plannerId');
        $this->mdb->from('connectm_mira_update.application_create as ca');
        $this->mdb->join('connectm_vaccine_planner.submit_final_dependency_planner as pl','ca.plannerId=pl.plannername','INNER');
        $this->mdb->where('app_id',$appId);
        return $this->getData($this->mdb->get());
        
        }  else {
            return FALSE;    
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function getMasterChildVaccineDetail($_app_id = NULL) {
        if ($_app_id != NULL) {
            $this->mdb->select('*');
            $this->mdb->from('mapping_child_vaccine_to_application');
            $this->mdb->join('master_vaccine_child', 'master_vaccine_child.vaccine_id=mapping_child_vaccine_to_application.vaccine_id', 'INNER');
            $this->mdb->where(array('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;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function ashaChildUpdateModel($_childId = NULL, $_childObject = NULL) {
        if ($_childId != NULL and $_childObject) {
            $this->mdb->trans_begin();
            $this->mdb->where('child_id', $_childId);
            $this->mdb->update('mira_child', $_childObject);
            if ($this->mdb->trans_status() === FALSE) {
                $this->mdb->trans_rollback();
                return array('status' => FALSE, 'childId' => $_childId);
            } else {
                $this->mdb->trans_commit();
                return array('status' => TRUE, 'childId' => $_childId);
            }
        } else {
            return array('status' => TRUE, 'childId' => NULL);
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function miraWorkerTrackSheetUpdateModel1($_data_tracking_screen = NULL) {
        if ($_data_tracking_screen != NULL) {
            $this->mdb->trans_begin();
            if (isset($_data_tracking_screen['modulecommon'])) {
                $this->mainModuleCommon($_data_tracking_screen['asha_id'], $_data_tracking_screen['modulecommon']);
            }
            if (isset($_data_tracking_screen['pregnantModule'])) {
                $this->mainModulePregnant($_data_tracking_screen['asha_id'], $_data_tracking_screen['pregnantModule']);
            }
            if (isset($_data_tracking_screen['childModule'])) {
                $this->mainModuleChild($_data_tracking_screen['asha_id'], $_data_tracking_screen['childModule']);
            }
            if ($this->mdb->trans_status() === FALSE) {
                $this->mdb->trans_rollback();
                return FALSE;
            } else {
                $this->mdb->trans_commit();
                return TRUE;
            }
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     */
    private function mainModuleChild($_asha_id = NULL, $_module_data = NULL) {
        for ($i = 0; $i < count($_module_data['module_data']); $i++) {
            $module_data = array(
                'asha_id' => $_asha_id,
                'module_id' => $_module_data['module_id'],
                'start_time' => date('Y-m-d H:i:s', strtotime($_module_data['module_data'][$i]['StartTimeStamp'])),
                'end_time' => date('Y-m-d H:i:s', strtotime($_module_data['module_data'][$i]['EndTimeStamp']))
            );
            $this->mdb->insert('common_module_tracker', $module_data);
            $last_module_id = $this->mdb->insert_id();
            $this->mdb->insert('common_module_child_tracker', array(
                'module_id' => $last_module_id,
                'child_id' => $_module_data['module_data'][$i]['childID'],
                'vaccine_id' => $_module_data['module_data'][$i]['vaccName']
                    )
            );
            $this->subMainModule($last_module_id, $_module_data['module_data'][$i]['subModule']);
        }
    }

    /**
     * 
     * 
     */
    private function mainModulePregnant($_asha_id = NULL, $_module_data = NULL) {
        for ($i = 0; $i < count($_module_data['module_data']); $i++) {
            $module_data = array(
                'asha_id' => $_asha_id,
                'module_id' => $_module_data['module_id'],
                'start_time' => date('Y-m-d H:i:s', strtotime($_module_data['module_data'][$i]['StartTimeStamp'])),
                'end_time' => date('Y-m-d H:i:s', strtotime($_module_data['module_data'][$i]['EndTimeStamp']))
            );
            $this->mdb->insert('common_module_tracker', $module_data);
            $last_module_id = $this->mdb->insert_id();
            $this->mdb->insert('common_module_child_tracker', array(
                'module_id' => $last_module_id,
                'child_id' => $_module_data['module_data'][$i]['womenId'],
                'vaccine_id' => $_module_data['module_data'][$i]['WeekNo']
                    )
            );
            $this->subMainModule($last_module_id, $_module_data['module_data'][$i]['subModule']);
        }
    }

    /**
     * 
     * 
     */
    private function mainModuleCommon($_asha_id = NULL, $_module_data = NULL) {
        for ($i = 0; $i < count($_module_data['modulecommon']); $i++) {
            for ($j = 0; $j < count($_module_data['modulecommon'][$i]['module_data']); $j++) {
                $module_data = array(
                    'asha_id' => $_asha_id,
                    'module_id' => $_module_data['modulecommon'][$i]['module_id'],
                    'start_time' => date('Y-m-d H:i:s', strtotime($_module_data['modulecommon'][$i]['module_data'][$j]['StartTimeStamp'])),
                    'end_time' => date('Y-m-d H:i:s', strtotime($_module_data['modulecommon'][$i]['module_data'][$j]['EndTimeStamp']))
                );
                $this->mdb->insert('common_module_tracker', $module_data);
                $this->subMainModule($this->mdb->insert_id(), $_module_data['modulecommon'][$i]['module_data'][$j]['subModule']);
            }
        }
    }

    /**
     * 
     * 
     * 
     */
    private function subMainModule($_main_module_id = NULL, $_sub_module_data = NULL) {
        $sub_module_data = NULL;
        for ($i = 0; $i < count($_sub_module_data); $i++) {
            $sub_module_data[] = array('module_id' => $_main_module_id, 'scence_id' => $_sub_module_data[$i]['screen'], 'scence_status' => $_sub_module_data[$i]['value']);
        }
        $this->mdb->insert_batch('common_module_sub_menu_tracker', $sub_module_data);
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function miraWorkerTrackSheetUpdateModel($_data_tracking_screen = NULL) {

        if ($_data_tracking_screen != NULL) {
            $this->mdb->trans_begin();
            $sub_module_data = NULL;
            $module_data = NULL;
            if (isset($_data_tracking_screen['modulecommon'])) {
                for ($i = 0; $i < count($_data_tracking_screen['modulecommon']); $i++) {
                    for ($j = 0; $j < count($_data_tracking_screen['modulecommon'][$i]['module_data']); $j++) {
                        $_data_tracking_screen['modulecommon'][$i]['module_data'][$j];
                        $module_data = array(
                            'asha_id' => $_data_tracking_screen['asha_id'],
                            'module_id' => $_data_tracking_screen['modulecommon'][$i]['module_id'],
                            'start_time' => DateTime::createFromFormat('d-m-Y H:i:s', str_replace('/', '-', $_data_tracking_screen['modulecommon'][$i]['module_data'][$j]['StartTimeStamp']))->format('Y-m-d H:i:s'),
                            'end_time' => DateTime::createFromFormat('d-m-Y H:i:s', str_replace('/', '-', $_data_tracking_screen['modulecommon'][$i]['module_data'][$j]['EndTimeStamp']))->format('Y-m-d H:i:s')
                        );
                        $this->mdb->insert('common_module_tracker', $module_data);
                        $last_insert_module_id = $this->mdb->insert_id();
                        for ($k = 0; $k < count($_data_tracking_screen['modulecommon'][$i]['module_data'][$j]['subModule']); $k++) {
                            $sub_module_data[] = array('module_id' => $last_insert_module_id, 'scence_id' => $_data_tracking_screen['modulecommon'][$i]['module_data'][$j]['subModule'][$k]['screen'], 'scence_status' => $_data_tracking_screen['modulecommon'][$i]['module_data'][$j]['subModule'][$k]['value']);
                        }
                    }
                }
            }
            if (isset($_data_tracking_screen['pregnantModule'])) {
                for ($i = 0; $i < count($_data_tracking_screen['pregnantModule']['module_data']); $i++) {
                    $module_data = array(
                        'asha_id' => $_data_tracking_screen['asha_id'],
                        'module_id' => $_data_tracking_screen['pregnantModule']['module_id'],
                        'start_time' => DateTime::createFromFormat('d-m-Y H:i:s', str_replace('/', '-', $_data_tracking_screen['pregnantModule']['module_data'][$i]['StartTimeStamp']))->format('Y-m-d H:i:s'),
                        'end_time' => DateTime::createFromFormat('d-m-Y H:i:s', str_replace('/', '-', $_data_tracking_screen['pregnantModule']['module_data'][$i]['EndTimeStamp']))->format('Y-m-d H:i:s')
                    );

                    $this->mdb->insert('common_module_tracker', $module_data);
                    $last_insert_module_id = $this->mdb->insert_id();
                    $this->mdb->insert('common_module_tracker_pregnant', array('common_module_id' => $last_insert_module_id,
                        'pregnant_id' => $_data_tracking_screen['pregnantModule']['module_data'][$i]['womenId'],
                        'week_id' => $_data_tracking_screen['pregnantModule']['module_data'][$i]['WeekNo']));
                    for ($j = 0; $j < count($_data_tracking_screen['pregnantModule']['module_data'][$i]['subModule']); $j++) {
                        $sub_module_data[] = array('module_id' => $last_insert_module_id, 'scence_id' => $_data_tracking_screen['pregnantModule']['module_data'][$i]['subModule'][$j]['screen'], 'scence_status' => $_data_tracking_screen['pregnantModule']['module_data'][$i]['subModule'][$j]['value']);
                    }
                }
            }

            if (isset($_data_tracking_screen['childModule'])) {
                for ($i = 0; $i < count($_data_tracking_screen['childModule']['module_data']); $i++) {
                    $module_data = array(
                        'asha_id' => $_data_tracking_screen['asha_id'],
                        'module_id' => $_data_tracking_screen['childModule']['module_id'],
                        'start_time' => DateTime::createFromFormat('d-m-Y H:i:s', str_replace('/', '-', $_data_tracking_screen['childModule']['module_data'][$i]['StartTimeStamp']))->format('Y-m-d H:i:s'),
                        'end_time' => DateTime::createFromFormat('d-m-Y H:i:s', str_replace('/', '-', $_data_tracking_screen['childModule']['module_data'][$i]['EndTimeStamp']))->format('Y-m-d H:i:s')
                    );

                    $this->mdb->insert('common_module_tracker', $module_data);
                    $last_insert_module_id = $this->mdb->insert_id();
                    $this->mdb->insert('common_module_child_tracker', array('module_id' => $last_insert_module_id, 'child_id' => $_data_tracking_screen['childModule']['module_data'][$i]['childID'], 'vaccine_id' => $_data_tracking_screen['childModule']['module_data'][$i]['vaccName']));

                    for ($j = 0; $j < count($_data_tracking_screen['childModule']['module_data'][$i]['subModule']); $j++) {
                        $sub_module_data[] = array('module_id' => $last_insert_module_id, 'scence_id' => $_data_tracking_screen['childModule']['module_data'][$i]['subModule'][$j]['screen'], 'scence_status' => $_data_tracking_screen['childModule']['module_data'][$i]['subModule'][$j]['value']);
                    }
                }
            }


            $this->mdb->insert_batch('common_module_sub_menu_tracker', $sub_module_data);

            if ($this->mdb->trans_status() === FALSE) {
                $this->mdb->trans_rollback();
                return FALSE;
            } else {
                $this->mdb->trans_commit();
                return TRUE;
            }
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function refreshAshaQusAnsListModel($_asha_id = NULL) {
        if ($_asha_id != NULL) {
            $return_data['houseList'] = $this->getHouseListByRegionCodeModel($_asha_id);
            $return_data['womenList'] = $this->getWomenListByHouseId($return_data['houseList']);
            $return_data['childList'] = $this->getChildListByWomenId($return_data['womenList']);
            $return_data['pregnantList'] = $this->getPrgnantListByWomenId($return_data['womenList']);
            $return_data['pregnantAncList'] = $this->getAnmAncStatusByPregnantId($return_data['pregnantList']);
            $return_data['criticalWeek'] = $this->getCriticalWeekPregnantWomen($return_data['pregnantList']);
            $return_data['criticalWeekAnswer'] = $this->getAshaAnmAnswer($return_data['criticalWeek']);
            return $return_data;
        } else {
            return $return_data;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function getAshaAnmAnswer($_criticat_week_data_array = NULL) {
        if ($_criticat_week_data_array != NULL and $_criticat_week_data_array) {
            $critical_week_answer = NULL;
            for ($i = 0; $i < count($_criticat_week_data_array); $i++) {
                for ($j = 0; $j < count($_criticat_week_data_array[$i]); $j++) {
                    $this->mdb->select('*');
                    $this->mdb->from('master_asha_anm_ans');
                    $this->mdb->join('master_asha_to_anm_alert', 'master_asha_to_anm_alert.alert_id=master_asha_anm_ans.alert_id', 'INNER');
                    $this->mdb->where('master_asha_anm_ans.alert_id', $_criticat_week_data_array[$i][$j]['alert_id']);
                    $temp_critical_week_answer = $this->getData($this->mdb->get());
                    if ($temp_critical_week_answer) {
                        $critical_week_answer[] = $temp_critical_week_answer;
                    }
                }
            }
            return $critical_week_answer;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function getCriticalWeekPregnantWomen($_pregnant_data_array = NULL) {
        if ($_pregnant_data_array != NULL and $_pregnant_data_array) {
            $critical_week = NULL;
            for ($i = 0; $i < count($_pregnant_data_array); $i++) {
                for ($j = 0; $j < count($_pregnant_data_array[$i]); $j++) {
                    $this->mdb->select('*');
                    $this->mdb->from('master_asha_to_anm_alert');
                    $this->mdb->where(array('pregnant_id' => $_pregnant_data_array[$i][$j]['pregnant_id'], 'alert' => 1));
                    $temp_critical_week = $this->getData($this->mdb->get());
                    if ($temp_critical_week) {
                        $critical_week[] = $temp_critical_week;
                    }
                }
            }
            return $critical_week;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * @param type $pregnant_id
     * @return type
     * 
     * 
     * 
     * 
     */
    public function getAnmAncStatusByPregnantId($_pregnant_list = NULL) {
        if ($_pregnant_list != NULL and $_pregnant_list) {
            $anm_anc = NULL;
            for ($i = 0; $i < count($_pregnant_list); $i++) {
                for ($j = 0; $j < count($_pregnant_list[$i]); $j++) {
                    $this->mdb->select('*');
                    $this->mdb->from('anm_anc_critical');
                    $this->mdb->where('pregnant_id', $_pregnant_list[$i][$j]['pregnant_id']);
                    $temp_anc = $this->getData($this->mdb->get());
                    if ($temp_anc) {
                        $anm_anc[] = $temp_anc;
                    }
                }
            }
            return $anm_anc;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * @param type $pregnant_id
     * @return type
     * 
     * 
     * 
     * 
     */
    public function getAnmUpdateAnswerByMasterId($master_id) {
        $obj = &get_instance();
        $obj->load->database();
        $query = $obj->db->get_where('asha_qus_ans', array('asha_master_id' => $master_id));
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $qus_id_answer[] = array(
                    'q_id' => $row->question_id, 'ans' => $row->anm_answer
                );
            }
            return $qus_id_answer;
        } else {
            return FALSE;
        }
    }

    public function getCriticalWeek($pregnant_id) {
        $obj = &get_instance();
        $obj->load->database();
        $query = $obj->db->get_where('asha_master', array('preg_id' => $pregnant_id, 'alert' => 1));
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $data) {
                $critical_data[] = array('asha_master_id' => $data->asha_master_id, 'week_id' => $data->week_id);
            }
            return $critical_data;
        } else {
            return NULL;
        }
    }

    public function getAnmCriticalByPregnantId($pregnant_id) {
        $obj = &get_instance();
        $obj->load->database();
        $query = $obj->db->get_where('anm_critical', array('pregnant_id' => $pregnant_id));
        if ($query->num_rows() > 0) {
            $critical = NULL;
            foreach ($query->result() as $value) {
                $critical[] = array('pregnant_id' => $value->pregnant_id, 'anc_code' => $value->anc_code, 'critical_status' => $value->critical);
            }
            return $critical;
        } else {
            return NULL;
        }
    }

    /**
     * 
     * @param type $asha_id
     * @return type
     * 
     * 
     * 
     */
    private function getUpdateAnmAnswer($asha_id) {
        $anm_update_data = NULL;
        $anc_status = NULL;
        $house_data_temp = $this->getHouseByAshaid($asha_id);
        if ($house_data_temp != NULL) {
            for ($i = 0; $i < count($house_data_temp); $i++) {
                $women_data_temp = $this->getWomenByHouseId($house_data_temp[$i]['house_id']);
                if ($women_data_temp != NULL) {
                    for ($j = 0; $j < count($women_data_temp); $j++) {
                        $pregnant_data_temp = $this->getPregnantWomenByWomenId($women_data_temp[$j]['women_id']);





                        if ($pregnant_data_temp != NULL) {
                            for ($k = 0; $k < count($pregnant_data_temp); $k++) {
                                $anc_status_temp = $this->getANCStatusByPregnantId($pregnant_data_temp[$k]['pregnant_id']);
                                if ($anc_status_temp != NULL) {
                                    $anc_status[] = $anc_status_temp;
                                }

                                $crtical_week_temp = $this->getCriticalWeekByPregnantId($pregnant_data_temp[$k]['pregnant_id']);
                                if ($crtical_week_temp != NULL) {


                                    for ($l = 0; $l < count($crtical_week_temp); $l++) {
                                        $anm_answer_temp = $this->getAnmAnswer($crtical_week_temp[$l]['asha_master_id']);
                                        $anm_ans = NULL;
                                        for ($m = 0; $m < count($anm_answer_temp); $m++) {
                                            if ($anm_answer_temp[$m]['ans'] != 0) {
                                                $anm_ans[] = $anm_answer_temp[$m];
                                            }
                                        }
                                        if (isset($anm_ans) && $anm_ans != NULL) {
                                            $anm_update_data[] = array('pregnant_id' => $pregnant_data_temp[$k]['pregnant_id'], 'week_id' => $crtical_week_temp[$l]['week_id'], 'qus_id_ans' => $anm_ans);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }



        //  if(isset($anc_status)){
        //  for($i=0;$i<count($anc_status);$i++){
        //      print_r($anc_status[$i]);
        //  }
        // }

        if (isset($anm_update_data)) {
            return array('anc_status' => $anc_status, 'anm_answer' => $anm_update_data);
        } else {
            return NULL;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function miraHouseRegistrationModel($_house_data = NULL) {
        if ($_house_data != NULL ) {
            $this->mdb->insert('mira_house', $_house_data);
            return ($this->mdb->affected_rows() != 1) ? FALSE : array('house_id' => $_house_data['auto_id'], 'house_number' => $_house_data['house_number']);
        } else {
            return FALSE;
        }
    }

 public function updateWomenTracking($_women_data=NULL)
     {
         if ($_women_data != NULL and $this->checkRowData('women_tracking', array('pregnant_id'=>$_women_data['pregnant_id'])))
        {
          $this->mdb->insert('women_tracking', $_women_data);
          return $this->mdb->insert_id();
        }
    }
    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function checkHouseExistenceModel($_house_number = NULL, $_region_code = NULL) {
        if ($_house_number != NULL and $_region_code != NULL) {
            $this->mdb->select('*');
            $this->mdb->from('mira_house');
            $this->mdb->where(array('auto_id' => $_house_number, 'region_code' => $_region_code,'delete_status'=>0));
            return $this->getData($this->mdb->get());
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function miraWomenRegistrationModel($_women_id = NULL) {
        if ($_women_id != NULL and $this->checkRowData('mira_women', array('region_code' => $_women_id['region_code'], 'name' => $_women_id['name'],'husband' => $_women_id['husband'],'house_id'=>$_women_id['house_id'],'age'=>$_women_id['age']))) {
            $this->mdb->insert('mira_women', $_women_id);
            return ($this->mdb->affected_rows() != 1) ? FALSE : array('women_id' => $this->mdb->insert_id(), 'update_tran_status' => $this->updateTransactionId(array('tran_wid' => $this->getTransactionId('mira_women', 'tran_wid', array('region_code' => $_women_id['region_code']))), array('region_code' => $_women_id['region_code'])));
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function miraPregnantRegistrationModel($_pregnant_data = NULL) {
        if ($_pregnant_data != NULL and $this->checkRowData('mira_pregnant_women', array('region_code' => $_pregnant_data['region_code'], 'women_id' => $_pregnant_data['women_id'],'pregnant_date'=>$_pregnant_data['pregnant_date']))) {
            $this->mdb->insert('mira_pregnant_women', $_pregnant_data);
            return ($this->mdb->affected_rows() != 1) ? FALSE : array('pregnant_id' => $this->mdb->insert_id(), 'lmc_date' => $_pregnant_data['pregnant_date'], 'update_tran_status' => $this->updateTransactionId(array('tran_pid' => $this->getTransactionId('mira_pregnant_women', 'tran_pid', array('region_code' => $_pregnant_data['region_code']))), array('region_code' => $_pregnant_data['region_code'])));
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function miraChildRegistrationModel_old($_child_data = NULL) {
        if ($_child_data != NULL and $this->checkRowData('mira_child', array('region_code' => $_child_data['region_code'], 'women_id' => $_child_data['women_id'],'dob' => $_child_data['dob'],'child_name' => $_child_data['child_name']))) {
            $this->mdb->insert('mira_child', $_child_data);
            
            return ($this->mdb->affected_rows() != 1) ? FALSE : array('child_id' => $child_id, 'update_tran_status' => $this->updateTransactionId(array('tran_cid' => $this->getTransactionId('mira_child', 'tran_cid', array('region_code' => $_child_data['region_code']))), array('region_code' => $_child_data['region_code'])));
        } else {
            return FALSE;
        }
    }


 /*  public function miraChildRegistrationModel_old($_child_data = NULL) {
    $mother_id = 0;
    $child_id = 0;

    if ($_child_data != NULL) {
        // Check if mother not exists
        $mother_result = $this->checkRowData('mira_women', [
            'women_id' => $_child_data['women_id']
        ]);

        if ($mother_result) {
            $mother_data = array(
                'women_id'             => $_child_data['women_id'],
                'name'                 => $_child_data['name'],
                'husband'              => $_child_data['husband'],
                'house_id'             => $_child_data['house_id'],
                'region_code'          => $_child_data['region_code'],
                'volunter_id'          => $_child_data['volunter_id'],
                'mobile_date'          => $_child_data['mobile_date'],
                'actual_register_date' => $_child_data['actual_register_date']
            );
           // if($_child_data['name']=!'')
            $this->mdb->insert('mira_women', $mother_data);
            if ($this->mdb->affected_rows() == 1) {
                $mother_id = 1;
            }
        } else {
            $mother_id = 0;
        }

        // Check if child not exists
        $child_exists = $this->checkRowData('mira_child', [
            'child_id' => $_child_data['child_id']
        ]);

        if ($child_exists) {
            $child_data = array(
                'child_id'             => $_child_data['child_id'],
                'women_id'             => $_child_data['women_id'],
                'gender'               => $_child_data['gender'],
                'region_code'          => $_child_data['region_code'],
                'volunter_id'          => $_child_data['volunter_id'],
                'child_name'           => $_child_data['child_name'],
                'dob'                  => $_child_data['dob'],
                'mobile_date'          => $_child_data['mobile_date'],
                'actual_register_date' => $_child_data['actual_register_date'],
                'child_category'       => $_child_data['child_category'],
                'mcp_card'       => $_child_data['mcp_card'],
                'why_not_vaccinated'       => $_child_data['why_not_vaccinated'],
                'other_reason'       => $_child_data['other_reason'],
                'birth_place'       => $_child_data['birth_place'],
            );

            $this->mdb->insert('mira_child', $child_data);
             $child_id = $this->mdb->insert_id();
            if((int)$child_id>0)
            {
           $reasons   = array_map('trim', explode(',', $_child_data['why_not_vaccinated']));
           $reasonsid = array_map('trim', explode(',', $_child_data['reason_id']));

foreach ($reasons as $key => $reason) {

    // optional safety check
    if (empty($reason)) {
        continue;
    }

    $insertData = [
        'c_id'         => $child_id,
        'child_id'     => $_child_data['child_id'],
        'reason_id'    => isset($reasonsid[$key]) ? $reasonsid[$key] : null,
        'region_code'  => $_child_data['region_code'],
        'volunter_id'  => $_child_data['volunter_id'],
        'reason'       => $reason,
    ];

    $this->mdb->insert('child_register_reasons', $insertData);
}
            
            
            }
           
            
            if ($this->mdb->affected_rows() == 1) {
                
              $this->create_first_followup($_child_data['child_id'],$_child_data['actual_register_date'],$_child_data['region_code'],$_child_data['volunter_id']);
                
                $child_id = 1;
            }
        }
    }

    return array(
        'child_id'  => $child_id,
        'women_id'  => $mother_id
    );
}

  */
  
  public function miraChildRegistrationModel($_child_data = NULL)
 {
    $mother_id = 0;
    $child_id  = 0;
    $response  = array();

    if ($_child_data != NULL) {

        // Check mother name blank
        if (
            !isset($_child_data['name']) ||
            trim($_child_data['name']) == ''
        ) {

            return array(
                'status'        => false,
                'message'       => 'Mother name is blank',
                'mother_blank'  => true,
                'child_id'      => 0,
                'women_id'      => 0
            );
        }

        // Check if mother already exists
        $mother_result = $this->checkRowData('mira_women', [
            'women_id' => $_child_data['women_id']
        ]);

        if ($mother_result) {

            $mother_data = array(
                'women_id'             => $_child_data['women_id'],
                'name'                 => $_child_data['name'],
                'husband'              => $_child_data['husband'],
                'house_id'             => $_child_data['house_id'],
                'region_code'          => $_child_data['region_code'],
                'volunter_id'          => $_child_data['volunter_id'],
                'mobile_date'          => $_child_data['mobile_date'],
                'actual_register_date' => $_child_data['actual_register_date']
            );

            $this->mdb->insert('mira_women', $mother_data);

            if ($this->mdb->affected_rows() == 1) {
                $mother_id = 1;
            }
        } else {
            $mother_id = 0;
        }

        // Check if child already exists
        $child_exists = $this->checkRowData('mira_child', [
            'child_id' => $_child_data['child_id']
        ]);

        if ($child_exists) {

            $child_data = array(
                'child_id'             => $_child_data['child_id'],
                'women_id'             => $_child_data['women_id'],
                'gender'               => $_child_data['gender'],
                'region_code'          => $_child_data['region_code'],
                'volunter_id'          => $_child_data['volunter_id'],
                'child_name'           => $_child_data['child_name'],
                'dob'                  => $_child_data['dob'],
                'mobile_date'          => $_child_data['mobile_date'],
                'actual_register_date' => $_child_data['actual_register_date'],
                'child_category'       => $_child_data['child_category'],
                'mcp_card'             => $_child_data['mcp_card'],
                'why_not_vaccinated'   => $_child_data['why_not_vaccinated'],
                'other_reason'         => $_child_data['other_reason'],
                'birth_place'          => $_child_data['birth_place'],
            );

            $this->mdb->insert('mira_child', $child_data);

            $insert_child_id = $this->mdb->insert_id();

            if ((int)$insert_child_id > 0) {

                $reasons   = array_map('trim', explode(',', $_child_data['why_not_vaccinated']));
                $reasonsid = array_map('trim', explode(',', $_child_data['reason_id']));

                foreach ($reasons as $key => $reason) {

                    if (empty($reason)) {
                        continue;
                    }

                    $insertData = [
                        'c_id'        => $insert_child_id,
                        'child_id'    => $_child_data['child_id'],
                        'reason_id'   => isset($reasonsid[$key]) ? $reasonsid[$key] : null,
                        'region_code' => $_child_data['region_code'],
                        'volunter_id' => $_child_data['volunter_id'],
                        'reason'      => $reason,
                    ];

                    $this->mdb->insert('child_register_reasons', $insertData);
                }

                $this->create_first_followup(
                    $_child_data['child_id'],
                    $_child_data['actual_register_date'],
                    $_child_data['region_code'],
                    $_child_data['volunter_id']
                );

                $child_id = 1;
            }
        }
    }

    return array(
        'mother_blank' => false,
        'child_id'     => $child_id,
        'women_id'     => $mother_id
    );
}
    public function create_first_followup($child_id, $registration_date,$region_code,$volunter_id)
    {
    $first_date = date('Y-m-d', strtotime($registration_date.' +15 days'));

     $this->mdb->insert('followup_schedule',[
        'child_id'=>$child_id,
        'followup_number'=>1,
        'scheduled_date'=>$first_date,
        'status'=>'pending',
        'region_code'=>$region_code,
        'volunter_id'=>$volunter_id
    ]);
    }


     private function create_followup_schedule($child_id, $registration_date,$region_code,$volunter_id)
     {
        $first = date('Y-m-d', strtotime($registration_date . ' +15 days'));
        $second = date('Y-m-d', strtotime($first . ' +15 days'));
        $third = date('Y-m-d', strtotime($second . ' +15 days'));
        $fourth = date('Y-m-d', strtotime($third . ' +15 days'));
        $fifth = date('Y-m-d', strtotime($fourth . ' +15 days'));
        $sixth = date('Y-m-d', strtotime($fifth . ' +15 days'));

        $data = [
            ['child_id'=>$child_id,'followup_number'=>1,'scheduled_date'=>$first,'region_code'=>$region_code,'volunter_id'=>$volunter_id],
            ['child_id'=>$child_id,'followup_number'=>2,'scheduled_date'=>$second,'region_code'=>$region_code,'volunter_id'=>$volunter_id],
            ['child_id'=>$child_id,'followup_number'=>3,'scheduled_date'=>$third,'region_code'=>$region_code,'volunter_id'=>$volunter_id],
            ['child_id'=>$child_id,'followup_number'=>4,'scheduled_date'=>$fourth,'region_code'=>$region_code,'volunter_id'=>$volunter_id],
            ['child_id'=>$child_id,'followup_number'=>5,'scheduled_date'=>$fifth,'region_code'=>$region_code,'volunter_id'=>$volunter_id],
            ['child_id'=>$child_id,'followup_number'=>6,'scheduled_date'=>$sixth,'region_code'=>$region_code,'volunter_id'=>$volunter_id],
        ];

        $this->mdb->insert_batch('followup_schedule',$data);
    }
    
    public function get_mohter_data_by_childId($childid)
    {
       // if ($childid != NULL) {
             $this->mdb->select('c.child_id, w.women_id, w.name');
$this->mdb->from('mira_child c');
$this->mdb->join('mira_women w', 'w.women_id = c.women_id');
$this->mdb->where(['c.child_id' => $childid]);

$query = $this->mdb->get();
$mother = $query->row();
return $childid;
       // } else {
           // return FALSE;
       // }
        
    }
    
    
    public function miraWomenUpdateModel($_women_id = NULL) {
        if ($_women_id != NULL) {
            $this->mdb->where('women_id', $_women_id);
            $this->mdb->update('mira_women', array('pregnant_status' => 1));
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function miraUpdateWomenPregnancyModel($_pregnant_update_data = NULL) {

        if ($_pregnant_update_data != NULL) {

            $this->mdb->trans_begin();
            $this->mdb->where('pregnant_id', $_pregnant_update_data['pregnant_id']);

            $this->mdb->update('mira_pregnant_women', array('closing_date' => date('Y-m-d', strtotime(str_replace('/', '-', $_pregnant_update_data['closing_date']))), 'delivery_status' => $_pregnant_update_data['close_status'], 'pregnant_status' => 0, 'delivery_location' => $_pregnant_update_data['location_area'], 'delivered_baby_status' => $_pregnant_update_data['second_status']));
            $this->mdb->select('mira_pregnant_women.women_id');
            $this->mdb->from('mira_pregnant_women');
            $this->mdb->where('pregnant_id', $_pregnant_update_data['pregnant_id']);
            $women_id = $this->getData($this->mdb->get());
            $this->mdb->where('women_id', $women_id[0]['women_id']);
            $this->mdb->update('mira_women', array('pregnant_status' => 0));
            
             $this->mdb->where('pregnant_id', $_pregnant_update_data['pregnant_id']);
            $this->mdb->update('women_tracking', array('closing_status' => 0,'close_date'=>date('Y-m-d', strtotime(str_replace('/', '-', $_pregnant_update_data['closing_date'])))));
            
            if ($this->mdb->trans_status() === FALSE) {
                $this->mdb->trans_rollback();
                return FALSE;
            } else {
                $this->mdb->trans_commit();
                return TRUE;
            }
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function miraChildImmunizationModel($_child_array = NULL) {
       if ($_child_array != NULL  and $this->checkRowData('master_child_immunization', array('child_id' => $_child_array['child_id'], 'vaccine_id' => $_child_array['vaccine_id'])) ) {
    $this->mdb->insert('master_child_immunization', $_child_array);
    
     $current_value = $this->mdb->get_where('mira_child', array('child_id' => $_child_array['child_id']))->row()->total_vaccine;

  // Increment the value
   $new_value = $current_value + 1;
    
    $this->mdb->where('child_id', $_child_array['child_id']);
    $this->mdb->update('mira_child', array('total_vaccine' =>$new_value));
    
    return ($this->mdb->affected_rows() != 1) ? FALSE : TRUE;
        } else {
    return FALSE;
    }
    }

    /**
     * 
     * 
     * 
     * 
     */
     
     /* 
     // Old function
    public function miraUpdateAshaQusAnsAlert0Model($_alert0_data = NULL) {
        if ($_alert0_data != NULL) {
            $this->mdb->insert('master_asha_to_anm_alert', $_alert0_data);
            
           
            
            $current_value = $this->mdb->get_where('women_tracking', array('pregnant_id' => $_alert0_data['pregnant_id']));
            
            if ($current_value->num_rows() > 0) {
             $value= $current_value->row()->total_hrp  ;
           // Increment the value
             $new_value = $value + 1;
            
            $this->mdb->where('pregnant_id', $_alert0_data['pregnant_id']);
            $this->mdb->update('women_tracking', array('total_hrp' =>$new_value,'last_hrp_week_no'=>$_alert0_data['week_id']));
           }
            
            return ($this->mdb->affected_rows() != 1) ? FALSE : TRUE;
        } else {
            return FALSE;
        }
    }
    */
    
    public function miraUpdateAshaQusAnsAlert0Model($_alert0_data = NULL) {
        if ($_alert0_data != NULL   and $this->checkRowData('master_asha_to_anm_alert', array('pregnant_id' => $_alert0_data['pregnant_id'], 'week_id' => $_alert0_data['week_id'])) ) {
            $this->mdb->insert('master_asha_to_anm_alert', $_alert0_data);
            
            $current_value = $this->mdb->get_where('women_tracking', array('pregnant_id' => $_alert0_data['pregnant_id']));
           if ($current_value->num_rows() > 0) {
             $value= $current_value->row()->total_hrp  ;
           // Increment the value
             $new_value = $value + 1;
            
            $this->mdb->where('pregnant_id', $_alert0_data['pregnant_id']);
            $this->mdb->update('women_tracking', array('total_hrp' =>$new_value,'last_hrp_week_no'=>$_alert0_data['week_id']));
           }
            return ($this->mdb->affected_rows() != 1) ? FALSE : TRUE;
        } else {
            return FALSE;
        }
    }
    
    /**
     * 
     * 
     */
    public function miraUpdateAshaQusAnsAlert1Model($_alert1_data = NULL, $_qust_ans_data = NULL ) {
        if ($_alert1_data != NULL and $_qust_ans_data != NULL and $this->checkRowData('master_asha_to_anm_alert', array('pregnant_id' => $_alert1_data['pregnant_id'], 'week_id' => $_alert1_data['week_id'])) ) {
            $this->mdb->trans_begin();
            $this->mdb->insert('master_asha_to_anm_alert', $_alert1_data);
            $alert_id = $this->mdb->insert_id();
            for ($i = 0; $i < count($_qust_ans_data); $i++) {
                $_qust_ans_data[$i]['alert_id'] = $alert_id;
            }
            $this->mdb->insert_batch('master_asha_anm_ans', $_qust_ans_data);
           
          $current_value = $this->mdb->get_where('women_tracking', array('pregnant_id' => $_alert1_data['pregnant_id']));
           if ($current_value->num_rows() > 0) {
             $value= $current_value->row()->total_hrp  ;
           // Increment the value
             $new_value = $value + 1;
            
            $this->mdb->where('pregnant_id', $_alert1_data['pregnant_id']);
            $this->mdb->update('women_tracking', array('total_hrp' =>$new_value,'last_hrp_week_no'=>$_alert1_data['week_id']));
           }
           
            if ($this->mdb->trans_status() === FALSE) {
                $this->mdb->trans_rollback();
                return FALSE;
            } else {
                $this->mdb->trans_commit();
                return TRUE;
            }

            return ($this->mdb->affected_rows() != 1) ? FALSE : TRUE;
        } else {
            return FALSE;
        }
    }

   

    /**
     * 
     * 
     * 
     * 
     */
    public function asahAuthonticationModel($_user_id = NULL, $_password = NULL) {
        if ($_user_id != NULL and $_password != NULL) {
            $this->mdb->select('master_login_user.*,master_user_details.user_name');
            $this->mdb->from('master_login_user');
            $this->mdb->join('application_create', 'application_create.app_total_level=master_login_user.user_level', 'INNER');
            $this->mdb->join('master_user_details', 'master_login_user.user_login_id=master_user_details.user_login_id', 'INNER');
            $this->mdb->where(array('master_login_user.user_login_id' => $_user_id, 'master_login_user.user_password' => $_password, 'user_activation_status' => 1));
            $return_data['user'] = $this->getData($this->mdb->get());

            if ($return_data['user']) {

                $return_data['vaccine_details'] = $this->getMasterChildVaccineDetail($return_data['user'][0]['app_id']);
                //$return_data['masterVaccine'] = $this->getChildVaccineMasterPlannerAppId($return_data['user'][0]['app_id']);
               // $return_data['masterVaccine'] = $this->getChildVaccineMasterPlannerAppId(2);
                $return_data['houseList'] = $this->getHouseListByRegionCodeModel($return_data['user'][0]['create_region_id']);

                $return_data['womenList'] = $this->getWomenListByHouseId($return_data['houseList']);

                $return_data['childList'] = $this->getChildListByWomenId($return_data['womenList']);

             //   $return_data['pregnantList'] = $this->getPrgnantListByWomenId($return_data['womenList']);

                $return_data['childImmuniList'] = $this->getChildImmunization($return_data['childList']);

             //   $return_data['pregnantImmuniList'] = $this->getPregnantImmunization($return_data['pregnantList']);

              //  $return_data['pregnantAncStatus'] = $this->getAncStatusByPregnantIdModel($return_data['pregnantList']);
                $return_data['folowupvisits'] = $this->getFolowupVisits($return_data['user'][0]['create_region_id']);
            }
            return $return_data;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
     
     
     
  private function getFolowupVisits($_region_code = NULL)
   {
    if ($_region_code === NULL) {
        return FALSE;
    }

    $this->mdb->select('child_id, followup_no,mobile_followup_id,status,remark,followup_visit_date,attempt_number,volunter_id,region_code');
    $this->mdb->from('mira_followup');
    $this->mdb->where('region_code', $_region_code);
    $query = $this->mdb->get();

    if ($query->num_rows() === 0) {
        return [];
    }

    $result = [];
    foreach ($query->result_array() as $row) {
        $child_id = $row['child_id'];
        if (!isset($result[$child_id])) {
            $result[$child_id] = [];
        }
        $result[$child_id][] = [
            'followup_no' => $row['followup_no'],
            'attempt_number' => $row['attempt_number'],
            'mobile_followup_id' => $row['mobile_followup_id'],
            'status'      => $row['status'],
            'remark'      => $row['remark'],
            'followup_visit_date'=>date('d/m/Y', strtotime($row['followup_visit_date'])),
            'region_code' => $row['region_code'],
            'volunter_id' => $row['volunter_id'],
        ];
    }

    // Optional: if you want the exact format you described
    $formatted = [];
    foreach ($result as $child_id => $followups) {
        $formatted[] = [
            'child_id'  => $child_id,
            'followups' => $followups
        ];
    }

    return $formatted;
}

     
     
     
     /**
     * 
     * 
     * 
     * 
     * 
     */
    private function getHouseListByRegionCodeModel($_region_code = NULL) {
        if ($_region_code != NULL) {
            $this->mdb->select('*');
            $this->mdb->from('mira_house');
            $this->mdb->where(array('region_code' => $_region_code, 'delete_status' => 0));
            return $this->getData($this->mdb->get());
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function getWomenListByHouseId($_house_list = NULL) {
        if ($_house_list != NULL and $_house_list) {
            $return_house = NULL;
            for ($i = 0; $i < count($_house_list); $i++) {
                $this->mdb->select('mira_women.*,mira_house.house_number,mira_house.house_head_name');
                $this->mdb->from('mira_women');
                $this->mdb->join('mira_house', 'mira_house.auto_id=mira_women.house_id', 'INNER');
                $this->mdb->where(array('mira_house.auto_id' => $_house_list[$i]['auto_id'], 'mira_women.delete_status' => 0));
                $temp_house = $this->getData($this->mdb->get());
                if ($temp_house) {
                    $return_house[] = $temp_house;
                }
            }
            return $return_house;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function getChildListByWomenId($_women_list = NULL) {
        if ($_women_list != NULL and $_women_list) {
            $return_child = NULL;
            for ($i = 0; $i < count($_women_list); $i++) {
                for ($j = 0; $j < count($_women_list[$i]); $j++) {
                    $this->mdb->select('mira_child.*,mira_women.name');
                    $this->mdb->from('mira_child');
                    $this->mdb->join('mira_women', 'mira_women.women_id=mira_child.women_id', 'INNER');
                    $this->mdb->where(array('mira_child.women_id' => $_women_list[$i][$j]['women_id'], 'mira_child.delete_status' => 0));
                    $temp_child = $this->getData($this->mdb->get());
                    if ($temp_child) {
                        $return_child[] = $temp_child;
                    }
                }
            }
            return $return_child;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function getPrgnantListByWomenId($_women_list = NULL) {
        if ($_women_list != NULL and $_women_list) {
            $return_pregnant = NULL;
            for ($i = 0; $i < count($_women_list); $i++) {
                for ($j = 0; $j < count($_women_list[$i]); $j++) {
                    $this->mdb->select('mira_pregnant_women.pregnant_id,mira_pregnant_women.women_id,mira_pregnant_women.pregnant_date,mira_pregnant_women.create_date as registration_date,mira_pregnant_women.mobile_date,mira_pregnant_women.actual_register_date,mira_pregnant_women.pregnant_status,mira_pregnant_women.delivery_status,mira_pregnant_women.closing_date,mira_pregnant_women.delivery_location,mira_pregnant_women.delivered_baby_status,mira_pregnant_women.delivered_women_status,mira_pregnant_women.tran_pid,mira_pregnant_women.region_code,mira_pregnant_women.delete_status,mira_women.women_id,mira_women.name');
                    $this->mdb->from('mira_pregnant_women');
                    $this->mdb->join('mira_women', 'mira_women.women_id=mira_pregnant_women.women_id', 'INNER');
                    $this->mdb->where(array('mira_pregnant_women.women_id' => $_women_list[$i][$j]['women_id'], 'mira_pregnant_women.delete_status' => 0));
                    $temp_pregnant = $this->getData($this->mdb->get());
                    if ($temp_pregnant) {
                        $return_pregnant[] = $temp_pregnant;
                    }
                }
            }
            return $return_pregnant;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function getChildImmunization($_child_list = NULL) {
        if ($_child_list != NULL and $_child_list) {
            $return_child_immunization = NULL;
            for ($i = 0; $i < count($_child_list); $i++) {
                for ($j = 0; $j < count($_child_list[$i]); $j++) {
                    $this->mdb->select('master_child_immunization.*,master_vaccine_child.vaccine_name');
                    $this->mdb->from('master_child_immunization');
                    $this->mdb->join('master_vaccine_child', 'master_vaccine_child.vaccine_id=master_child_immunization.vaccine_id', 'INNER');
                    $this->mdb->where('master_child_immunization.child_id', $_child_list[$i][$j]['child_id']);
                    $temp_child_immunization = $this->getData($this->mdb->get());
                    if ($temp_child_immunization) {
                        $return_child_immunization[] = $temp_child_immunization;
                    }
                }
            }
            return $return_child_immunization;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function getPregnantImmunization($_pregnant_data_array = NULL) {
        if ($_pregnant_data_array != NULL and $_pregnant_data_array) {
            $return_pregnant_immunization = NULL;
            for ($i = 0; $i < count($_pregnant_data_array); $i++) {
                for ($j = 0; $j < count($_pregnant_data_array[$i]); $j++) {

                    $this->mdb->select('master_asha_to_anm_alert.*');
                    $this->mdb->from('master_asha_to_anm_alert');

                    $this->mdb->where('pregnant_id', $_pregnant_data_array[$i][$j]['pregnant_id']);
                    $temp_pregnant_immunization = $this->getData($this->mdb->get());

                    if ($temp_pregnant_immunization) {

                        $temp_alert0 = NULL;
                        $temp_alert1 = NULL;
                        $l = 0;
                        for ($k = 0; $k < count($temp_pregnant_immunization); $k++) {
                            if ($temp_pregnant_immunization[$k]['alert'] == 1) {
                                $temp_alert1[$l] = $temp_pregnant_immunization[$k];
                                $this->mdb->select('master_asha_anm_ans.*');
                                $this->mdb->from('master_asha_anm_ans');
                                $this->mdb->where('alert_id', $temp_pregnant_immunization[$k]['alert_id']);
                                $temp_alert1[$l]['qus_id_ans'] = $this->getData($this->mdb->get());
                                $l++;
                            } else {
                                $temp_alert0[] = $temp_pregnant_immunization[$k];
                            }
                        }
                        $return_pregnant_immunization[] = array('alert0' => $temp_alert0, 'alert1' => $temp_alert1);
                    }
                }
            }
            return $return_pregnant_immunization;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function getAncStatusByPregnantIdModel($_pregnant_data_array = NULL) {
        if ($_pregnant_data_array != NULL and $_pregnant_data_array) {
            $anc_status_data = NULL;
            for ($i = 0; $i < count($_pregnant_data_array); $i++) {
                $temp_data_anc = $this->getAncDataByPregnantId($_pregnant_data_array[$i]);
                if ($temp_data_anc) {
                    $anc_status_data[] = $temp_data_anc;
                }
            }
            return $anc_status_data;
        } {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     */
    private function getAncDataByPregnantId($_pregnant_data = NULL) {
        for ($i = 0; $i < count($_pregnant_data); $i++) {
            $this->mdb->select('anm_anc_critical.*');
            $this->mdb->from('anm_anc_critical');
            $this->mdb->where('pregnant_id', $_pregnant_data[$i]['pregnant_id']);
            return $this->getData($this->mdb->get());
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function getTransactionIds($_column_name = NULL, $_condition = NULL) {
        $this->mdb->select($_column_name);
        $this->mdb->from('mira_transaction_ids');
        $this->mdb->where($_condition);
        $data = $this->getData($this->mdb->get());
        return $data[0][$_column_name];
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function getTransactionId($_table_name = NULL, $_column_name = NULL, $_condition = NULL) {
        $this->mdb->select_max($_column_name);
        $this->mdb->where($_condition);
        $this->mdb->from($_table_name);
        $data = $this->getData($this->mdb->get());
        return $data[0][$_column_name];
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function updateTransactionId($_updated_data = NULL, $_condition = NULL) {
        $this->mdb->where($_condition);
        $this->mdb->update('mira_transaction_ids', $_updated_data);
        return ($this->mdb->affected_rows() != 1) ? FALSE : TRUE;
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function checkRowData($_table_name = NULL, $_conditio_array = NULL) {
        $this->mdb->select('*');
        $this->mdb->from($_table_name);
        $this->mdb->where($_conditio_array);
        $query = $this->mdb->get();
        if ($query->num_rows() > 0) {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
     
     public function checkPregnentWomenExistenceModel($women_id = NULL) {
        if ($women_id != NULL) {
            $this->mdb->select('*');
            $this->mdb->from('mira_pregnant_women');
            $this->mdb->where(array('women_id' => $women_id, 'pregnant_status' => 1));
            return $this->getData($this->mdb->get());
        } else {
            return FALSE;
        }
    }
     
     
     
     public function getWomenDetailByWomenId($women_id = NULL)
    {
       if ($women_id != NULL) {
            $this->mdb->select('mira_women.*,mira_pregnant_women.pregnant_date');
            $this->mdb->from('mira_women');
            $this->mdb->join('mira_pregnant_women','mira_pregnant_women.women_id=mira_women.women_id', 'INNER');
            $this->mdb->where(array('mira_women.women_id' => $women_id));
            return $this->getData($this->mdb->get());
        } else {
            return FALSE;
        } 
    }
     
     
     
    public  function  getStatedataforDMC()
    {
        $query="SELECT state_auto_id  as Sid,state_name as Sname FROM `master_state` WHERE state_actvation_status=1 order by state_auto_id  ";
        $q1=$this->mdb->query($query);
          
        $this->result= $q1->result_array(); 
        return $this->result;   
        
    }
    
    
    public  function  getDistrictdataforDMC()
    {
        $query="SELECT district_auto_id  as Did,district_name as Dname,state_id as Sid FROM `master_district` WHERE district_activation_status=1 order by state_id  ";
        $q1=$this->mdb->query($query);
          
        $this->result= $q1->result_array(); 
        return $this->result;   
        
    }
    
    
    public  function  getBlockdataforDMC()
    {
      
        $query="SELECT `block_id` as Bid,`name`as Bname,`district_id` as Did FROM `master_block` WHERE `isActive`=1   order by district_id";
          $q1=$this->mdb->query($query);
          $this->result= $q1->result_array(); 
            return $this->result;
            
        
    }
     
     public function saveUserInfo($userData){
        
          if ($userData != NULL && $this->checkRowData('userRegistr', array('session_id' => $userData['session_id'])) ) {
            $this->mdb->insert('userRegistr', $userData);
            return ($this->mdb->affected_rows() != 1) ? FALSE : array('user_id' => $this->mdb->insert_id(), 'name' => $userData['name'],'session_id'=>$userData['session_id']);
        } else {
            return FALSE;
        }

        

    }
     
     
     public function totalHouses($uid= NULL,$sd= NULL,$ed= NULL)
    {
     //$data['uid']= NULL,$data['stdate']= NULL,$data['endate']= NULL   
      $this->mdb->select('*');
      $this->mdb->from('mira_house');
      $this->mdb->where(array('region_code' => $uid));
      $this->mdb->where('DATE(create_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }

    public function totalChildren($uid= NULL,$sd= NULL,$ed= NULL)
    { 
      $this->mdb->select('*');
      $this->mdb->from('mira_child');
      $this->mdb->where(array('region_code' => $uid));
      $this->mdb->where('DATE(create_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }

    public function totalWomen($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('mira_women');
      $this->mdb->where(array('region_code' => $uid));
      $this->mdb->where('DATE(create_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }

     public function totalNonPgWomen($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('mira_women');
      $this->mdb->where(array('region_code' => $uid,'pregnant_status'=>0));
      $this->mdb->where('DATE(create_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }
    
    public function totalPgWomen($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('mira_pregnant_women');
      $this->mdb->where(array('region_code' => $uid,'pregnant_status'=>1));
      $this->mdb->where('DATE(create_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }

    public function totalPgWomenClosed($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('mira_pregnant_women');
      $this->mdb->where(array('region_code' => $uid,'pregnant_status'=>0));
      $this->mdb->where('DATE(closing_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }
    
    public function totalChildClosed($uid= NULL,$sd= NULL,$ed= NULL)
    {
         // ===== Total Closed Children =====
    $this->mdb->select("
    SUM(CASE WHEN running_status>0 THEN 1 ELSE 0 END) as closedchild
    ");
   $this->mdb->from('mira_child');
   $this->mdb->where('region_code',$uid );
   $this->mdb->where('DATE(create_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
   $closedchildData = $this->mdb->get()->row();
   $closedchild = $closedchildData->closedchild ?? 0; 
        
        
      
      return $closedchild;
    }
    
    public function totalzerodosechild($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('mira_child');
      $this->mdb->where(array('region_code' => $uid,'child_category'=>1));
      $this->mdb->where('DATE(create_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }
    
    public function totalpartiallyimmunizedchild($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('mira_child');
      $this->mdb->where(array('region_code' => $uid,'child_category'=>2));
      $this->mdb->where('DATE(create_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }
    
     public function totalfullyimmunizedchild($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('mira_child');
      $this->mdb->where(array('region_code' => $uid,'child_category'=>3));
      $this->mdb->where('DATE(create_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }
    
    
    public function totalHrp($uid= NULL,$sd= NULL,$ed= NULL)
    {
   
         $this->mdb->select('COUNT(*) as total'); // Select the count of records
         $this->mdb->from('master_asha_to_anm_alert ma'); // Alias for clarity
         $this->mdb->join('mira_pregnant_women mpw', 'ma.pregnant_id = mpw.pregnant_id'); // Join on pregnant_id
         $this->mdb->where(array('mpw.region_code' => $uid)); // Ensure to reference region_code from mira_pregnant_women
         $this->mdb->where("DATE(ma.create_date) BETWEEN " . $this->mdb->escape($sd) . " AND " . $this->mdb->escape($ed), NULL, FALSE);
         $result = $this->mdb->get()->row(); // Execute and retrieve the row
         $data8 = ($result && isset($result->total)) ? $result->total : 0; // Return 0 if no results found

    return $data8;
    }
    
    public function totalVaccinations($uid= NULL,$sd= NULL,$ed= NULL)
    {
        
     // ===== Total Vaccination =====
   $this->mdb->select("COUNT(*) as total_vaccination");
   $this->mdb->from('master_child_immunization');
   $this->mdb->where('region_code',$uid );
    $this->mdb->where('DATE(submit_date) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
   $totalvaccineData = $this->mdb->get()->row();
   $total_vaccination = $totalvaccineData->total_vaccination ?? 0;
   return  $total_vaccination;

    }

    public function totalmira_theater_activity($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('mira_theater_activity');
      $this->mdb->where(array('region_code' => $uid));
      $this->mdb->where('DATE(server_date_time) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }
    
    
    public function totalkiosk_activity($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('kiosk_activity');
      $this->mdb->where(array('region_code' => $uid));
      $this->mdb->where('DATE(server_date_time) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }

    public function totalposter_compaign_activity($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('poster_compaign_activity');
      $this->mdb->where(array('region_code' => $uid));
      $this->mdb->where('DATE(server_date_time) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }
    
    public function totalstakeholder_meeting_activity($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('stakeholder_meeting_activity');
      $this->mdb->where(array('region_code' => $uid));
      $this->mdb->where('DATE(server_date_time) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }
    
    public function totaltraining_activity($uid= NULL,$sd= NULL,$ed= NULL)
    {
      $this->mdb->select('*');
      $this->mdb->from('training_activity');
      $this->mdb->where(array('region_code' => $uid));
      $this->mdb->where('DATE(server_date_time) BETWEEN "'. date('Y-m-d', strtotime($sd)). '" and "'. date('Y-m-d', strtotime($ed)).'"');
      $query= $this->mdb->get();
      return $query->num_rows();
    }
    
   public function centre_detail_old($id)
  {
    $this->mdb->select('region_code  as id, region_name as name');
    $this->mdb->where('region_code', $id);
    $healthcenters = $this->mdb->get('master_area_create_by_super')->result_array();

    if (!empty($healthcenters)) {
        // Get all mohallas
        $this->mdb->select('moh_id as mohid, name as mohallaname, health_centre_id as hcid');
        $mohallas = $this->mdb->get('mohalla')->result_array();

        // Group mohallas by health_centre_id
        $mohallaGrouped = [];
        foreach ($mohallas as $mohalla) {
            $mohallaGrouped[$mohalla['hcid']][] = [
                'mid' => $mohalla['mohid'],
                'mname' => $mohalla['mohallaname']
            ];
        }

        // Attach mohallas under each health center
        foreach ($healthcenters as &$healthcenter) {  // <-- see the &
            $healthcenter['mohalla'] = isset($mohallaGrouped[$healthcenter['id']]) ? $mohallaGrouped[$healthcenter['id']] : [];
        }
    }

    return $healthcenters;
}

    public function centre_detail()
  {
    $this->mdb->select('*');
    $this->mdb->from('health_centre');
    $this->mdb->where('is_active',1);
    $centres = $this->mdb->get()->result_array();

    $final = [];

    foreach ($centres as $centre) {

        // Get mohalla (subareas) for this centre
        $this->mdb->select('moh_id as mid, name as mname');
        $this->mdb->from('mohalla');
        $this->mdb->where('health_centre_id', $centre['id']);
        $this->mdb->where('isactive', 1);
        $mohalla = $this->mdb->get()->result_array();

        $final[] = [
            'id' => $centre['id'],
            'name' => $centre['name'],
            'mohalla' => $mohalla
        ];
    }

    return $final;

    
}





    public function modulePlayStatus($_house_data = NULL) {
        if ($_house_data != NULL and $this->checkRowData('user_module_tracking', array('session_id' => $_house_data['session_id'], 'module_code' => $_house_data['module_code']))) {
            
            $current_value = $this->mdb->get_where('userRegistr', array('session_id' => $_house_data['session_id']))->row()->played_module;

  // Increment the value
   $new_value = $current_value + 1;
    
    $this->mdb->where('session_id', $_house_data['session_id']);
    $this->mdb->update('userRegistr', array('played_module' =>$new_value));
            
            $this->mdb->insert('user_module_tracking', $_house_data);
        
            
            
            
            return ($this->mdb->affected_rows() != 1) ? FALSE : array('module_id' => $this->mdb->insert_id(),'session_id' => $_house_data['session_id'] ,'module_code' => $_house_data['module_code'] );
        } else {
            return FALSE;
        }
    }




    public function checkModuleExistenceModel($_session_id = NULL, $_module_code = NULL) {
        if ($_session_id != NULL and $_module_code != NULL) {
            $this->mdb->select('*');
            $this->mdb->from('user_module_tracking');
            $this->mdb->where(array('session_id' => $_session_id, 'module_code' => $_module_code));
            return $this->getData($this->mdb->get());
        } else {
            return FALSE;
        }
    }

   
    //new work
    
    public function selfRegistrationModel($module_tran_data = NULL) {
      /*  if ($module_tran_data != NULL) {
            
            $this->shgdb->insert('selfregisteration', $module_tran_data);
            return ($this->shgdb->affected_rows() != 1) ? FALSE : array('session_id' => $module_tran_data['sessionId'], 'inserted_id' => $this->shgdb->insert_id());
        } else {
            return FALSE;
        }
        */
        
         if ($module_tran_data != NULL && $module_tran_data['sessoinType']!=0) {
           
            $query ="SELECT * FROM self_group_registeration WHERE sessionId= '".$module_tran_data['sessionId']."'";   
            $q = $this->mdb->query($query);   
             if($q->num_rows()== 0)
             {
            $this->mdb->insert('self_group_registeration', $module_tran_data);
            return ($this->mdb->affected_rows() != 1) ? FALSE : array('session_id' => $module_tran_data['sessionId'], 'server_id' => $this->mdb->insert_id(),'inserted_status'=>1);
             }
             else
             {
                 return array('session_id' => $module_tran_data['sessionId'], 'server_id' =>$q->result()[0]->Id,'inserted_status'=>0);  
             }
        } else {
            return FALSE;
        }
    }
    public function addModuleTrackingDataModel($module_tran_data = NULL) {
      /*  if ($module_tran_data != NULL) {
            
            $this->shgdb->insert('selfregisteration', $module_tran_data);
            return ($this->shgdb->affected_rows() != 1) ? FALSE : array('session_id' => $module_tran_data['sessionId'], 'inserted_id' => $this->shgdb->insert_id());
        } else {
            return FALSE;
        }
        */
        
         if ($module_tran_data != NULL && $module_tran_data['sessionId']!=0) {
           
            $query ="SELECT * FROM self_group_registeration WHERE sessionId= '".$module_tran_data['sessionId']."'";   
            $q = $this->mdb->query($query);   
           if($q->num_rows()== 1)
             {
            $query ="SELECT * FROM self_group_modules_tracking WHERE sessionId= '".$module_tran_data['sessionId']."'";   
            $q = $this->mdb->query($query);  
            if($q->num_rows()== 0)
            {
            $this->mdb->insert('self_group_modules_tracking', $module_tran_data);
            return ($this->mdb->affected_rows() != 1) ? FALSE : array('session_id' => $module_tran_data['sessionId'], 'server_id' => $this->mdb->insert_id(),'inserted_status'=>1);
            }
            else
             {
                 return array('session_id' => $module_tran_data['sessionId'], 'server_id' =>$q->result()[0]->Id,'inserted_status'=>0);  
             }
             }
             else
             {
                 return array('session_id' => $module_tran_data['sessionId'], 'server_id' =>0,'inserted_status'=>0);  
             }
        } else {
            return FALSE;
        }
    } 
    public function insertImage($image_data = NULL) {
       if ($image_data != NULL) {
            // 0 means database error,1 inserted,2 means alerady inserted, 3 means sessionId not exist, 4 means data not found 
            $query ="SELECT * FROM self_group_registeration WHERE sessionId= '".$image_data['sessionId']."'";   
            $q = $this->mdb->query($query);   
           if($q->num_rows()== 1)
             {
            $query ="SELECT * FROM image WHERE sessionId= '".$image_data['sessionId']."'";   
            $q = $this->mdb->query($query);   
             if($q->num_rows()== 0)
             {
            $this->mdb->insert('image', $image_data);
            return $this->mdb->affected_rows() >0 ? 1 : 0;
             }
             else
             {
               return 2;  
             }
             }
         else {
            return 3;   
         }
        } else {
            return 4;
        }
    }
    
    ///// 
   
   
   public function child_followup_data($records = null) {
    $results = [];

    if (!is_array($records) || empty($records)) {
        return [[
            'status' => FALSE,
            'message' => 'No records to process',
            'server_followup_id' => 0,
            'mobile_followup_id' => 0
        ]];
    }

    foreach ($records as $record) {
        if (empty($record['mobile_followup_id'])) {
            $results[] = [
                'status' => FALSE,
                'message' => 'Missing mobile_followup_id',
                'server_followup_id' => 0,
                'mobile_followup_id' => $record['mobile_followup_id'] ?? 0
            ];
            continue;
        }

       

      /*  $this->mdb->where('mobile_followup_id', $record['mobile_followup_id']);
        $query = $this->mdb->get('mira_followup');

        if ($query->num_rows() > 0) {
            $existing = $query->row();
            $results[] = [
                'status' => FALSE,
                'message' => 'Already exists',
                'server_followup_id' => $existing->id,
                'mobile_followup_id' => $existing->mobile_followup_id
            ];
        } 
        */
     // else {
            // Insert
              $record['followup_visit_date']=date('Y-m-d', strtotime(str_replace('/', '-', $record['followup_visit_date'])));
            if (!$this->mdb->insert('mira_followup', $record)) {
                $error = $this->mdb->error();
                $results[] = [
                    'status' => FALSE,
                    'message' => 'Insert failed: ' . $error['message'],
                    'server_followup_id' => 0,
                    'mobile_followup_id' => $record['mobile_followup_id']
                ];
                continue;
            }

            $id = $this->mdb->insert_id();
            $results[] = [
                'status' => TRUE,
                'message' => 'Inserted',
                'server_followup_id' => $id,
                'mobile_followup_id' => $record['mobile_followup_id']
            ];
       // }
    }

    return $results;
}
   
   
    //
    public function saveStorySessions_old($cdata,$sdata = null){
     

            if($this->checkRowData('all_chld_screening', array('session_uid' => $sdata['session_uid'],'child_uid'=>$cdata['child_uid'],'storyid'=>$sdata['storyid'])) ){
             $this->mdb->insert('all_chld_screening', $sdata);
             $screeningid=$this->mdb->insert_id();
             return array('status' => TRUE, 'child_id'=>$cdata['child_uid'], 'session_uid'=>$sdata['session_uid'],'session_serverid' => $screeningid,);
            }
            
            else
            {
                 return array('status' => FALSE, 'child_id'=>$cdata['child_uid'],  'session_uid'=>$sdata['session_uid'],'session_serverid' => -1,);
            }
           
        }
    
     public function saveStorySessions($cdata, $sdata)
    {
    $exists = $this->mdb
        ->where([
            'session_uid' => $sdata['session_uid'],
            'child_uid'   => $cdata['child_uid'],
            'storyid'     => $sdata['storyid']
        ])
        ->limit(1)
        ->get('all_chld_screening')
        ->num_rows();

    if ($exists == 0) {

        $this->mdb->insert('all_chld_screening', $sdata);

        return [
            'status' => TRUE,
            'child_uid' => $cdata['child_uid'],
            'session_uid' => $sdata['session_uid'],
            'storyid' => $sdata['storyid'],
            'session_serverid' => $this->mdb->insert_id()
        ];
    }

    return [
        'status' => FALSE,
        'child_uid' => $cdata['child_uid'],
        'session_uid' => $sdata['session_uid'],
        'storyid' => $sdata['storyid'],
        'message' => 'Record already exists'
    ];
}



    
    
    
   public function volunterAuthonticationModel($loginId, $password)
   {
    $this->mdb->select("
        ml.user_login_id,
        mu.user_name,
        mac.region_code as volunter_id,
        mac.region_name
 
    ");
    $this->mdb->from('master_login_user ml');
    $this->mdb->join(
        'master_user_details mu',
        'mu.user_login_id = ml.user_login_id',
        'INNER'
    );
    $this->mdb->join(
        'master_area_create_by_super mac',
        'mac.region_code = ml.create_region_id',
        'INNER'
    );
    $this->mdb->where('ml.user_login_id', $loginId);
    $this->mdb->where('ml.user_password', $password); // 🔐 hash recommended

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

    return ($query->num_rows() === 1)
        ? $query->row_array()
        : false;
}

   public function getUsersUnderSuperRegion($regionCodeSuper)
   {
    $this->mdb->select("
        ml.user_login_id,
        ml.user_password,
        mu.user_name,
        mac.region_code,
        mac.region_name
    ");
    $this->mdb->from('master_login_user ml');
    $this->mdb->join(
        'master_user_details mu',
        'mu.user_login_id = ml.user_login_id',
        'INNER'
    );
    $this->mdb->join(
        'master_area_create_by_super mac',
        'mac.region_code = ml.create_region_id',
        'INNER'
    );
    $this->mdb->where('mac.region_code_super', $regionCodeSuper);

    return $this->mdb->get()->result_array();
}

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

}
