<?php

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

/**
 * Description of ServiceAsha
 *
 * @author zmq163
 */
class MiraServiceAsha extends CI_Controller {

    //put your code here
    var $vdb;

    public function __construct() {
        parent::__construct();
        $this->load->model('Mira_service_asha_model');
    }

public function mytest()
{
    print_r("welcome home");
    
}
    public function test() {
        print_r($this->Mira_service_asha_model->getChildVaccineMasterPlannerAppId(2));

        $this->vdb = $this->load->database('mdb', TRUE);
        $this->vdb->select('ca.app_id as appId,pl.Id as vaccineId');
        $this->vdb->from('connectm_mira_update.application_create as ca');
        $this->vdb->join('connectm_vaccine_planner.submit_final_dependency_planner as pl', 'ca.plannerId=pl.plannername', 'LEFT');
        $this->vdb->where('app_id', 2);
        $query = $this->vdb->get()->result();
        // print_r($query);
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function miraWorkerTrackSheetUpdate() {
        $dataImmunization = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        if ($this->Mira_service_asha_model->miraWorkerTrackSheetUpdateModel($dataImmunization)) {
            print_r(json_encode(array('submited_status' => TRUE)));
        } else {
            print_r(json_encode(array('submited_status' => FALSE)));
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function refreshAshaQusAnsList() {
        $data = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        $parsing_data = $this->Mira_service_asha_model->refreshAshaQusAnsListModel($data['asha_id']);
        $return_data['anm_answer'] = $this->parsingAnmAshaAnswer($parsing_data['criticalWeekAnswer']);
        $return_data['anc_status'] = $this->parsingAncCritical($parsing_data['pregnantAncList']);
        print_r(json_encode($return_data));
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function parsingAncCritical($_anc_critical_data_array = NULL) {
        if ($_anc_critical_data_array != NULL and $_anc_critical_data_array) {
            $return_data = NULL;
            for ($i = 0; $i < count($_anc_critical_data_array); $i++) {
                for ($j = 0; $j < count($_anc_critical_data_array[$i]); $j++) {
                    //$return_data[] = $_anc_critical_data_array[$i][$j];
                    $return_data[$i][] = array('pregnant_id' => (int) $_anc_critical_data_array[$i][$j]['pregnant_id'], 'anc_code' => (int) $_anc_critical_data_array[$i][$j]['anc_code'], 'critical_status' => (int) $_anc_critical_data_array[$i][$j]['critical_status']);
                }
            }
            return $return_data;
        }
    }

    /**
     * 
     * @param type $_parsing_data
     * @return type
     * 
     * 
     * 
     */
    private function parsingAnmAshaAnswer($_parsing_data = NULL) {
        if ($_parsing_data != NULL and $_parsing_data) {
            $return_data = NULL;
            for ($i = 0; $i < count($_parsing_data); $i++) {
                $temp_pregnant_id = NULL;
                $temp_current_week = NULL;
                $temp_qus_ans = NULL;
                for ($j = 0; $j < count($_parsing_data[$i]); $j++) {
                    if ($_parsing_data[$i][$j]['anm_answer']) {
                        $temp_qus_ans[] = array('q_id' => $_parsing_data[$i][$j]['question_id'], 'ans' => $_parsing_data[$i][$j]['anm_answer']);
                    } else {
                        $temp_qus_ans[] = array('q_id' => $_parsing_data[$i][$j]['question_id'], 'ans' => $_parsing_data[$i][$j]['asha_answer']);
                    }

                    if ($j == 0) {
                        $temp_pregnant_id = $_parsing_data[$i][$j]['pregnant_id'];
                        $temp_current_week = $_parsing_data[$i][$j]['week_id'];
                    }
                }
                $return_data[] = array('pregnant_id' => $temp_pregnant_id, 'week_id' => $temp_current_week, 'qus_id_ans' => $temp_qus_ans);
            }
            return $return_data;
        }
    }


    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
     /*
    public function ashaHouseRegistration() {
        $datahouse = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        $newHouse = NULL;
        $existHouse = NULL;
        if (isset($datahouse) and $datahouse) {
            for ($i = 0; $i < count($datahouse['houseDetails']); $i++) {
                $existence_house_data = $this->Mira_service_asha_model->checkHouseExistenceModel($datahouse['houseDetails'][$i]['house_number'], $datahouse['user_id']);
                if ($existence_house_data) {
                    $existHouse[] = array('house_id' => $existence_house_data[0]['auto_id'], 'house_number' => $existence_house_data[0]['house_number']);
                } else if ($new_house_data = $this->Mira_service_asha_model->miraHouseRegistrationModel($this->getHouseDataTableFormat($datahouse['houseDetails'][$i], $datahouse['user_id']))) {
                    $newHouse[] = $new_house_data;
                }
            }
        }
        print_r(json_encode(array('newHouse' => $newHouse, 'existHouse' => $existHouse)));
    }
     */
     
     public function ashaHouseRegistration()
    {
    // ✅ Get raw JSON from BODY instead of HEADER
    $rawData = file_get_contents("php://input");
    $datahouse = json_decode($rawData, true);

    $newHouse = [];
    $existHouse = [];

    if (!empty($datahouse) && isset($datahouse['houseDetails'])) {

        for ($i = 0; $i < count($datahouse['houseDetails']); $i++) {

            $house = $datahouse['houseDetails'][$i];

            // ✅ Check existing house
            $existence_house_data = $this->Mira_service_asha_model
                ->checkHouseExistenceModel($house['house_uid'], $datahouse['user_id']);

            if (!empty($existence_house_data)) {

                $existHouse[] = array(
                    'house_id' => $existence_house_data[0]['auto_id'],
                    'house_number' => $existence_house_data[0]['house_number']
                );

            } else {

                // ✅ Insert new house
                $formattedData = $this->getHouseDataTableFormat($house, $datahouse['user_id']);

                if ($formattedData) {
                    $new_house_data = $this->Mira_service_asha_model
                        ->miraHouseRegistrationModel($formattedData);

                    if ($new_house_data) {
                        $newHouse[] = $new_house_data;
                    }
                }
            }
        }
    }

    // ✅ Proper JSON response
    echo json_encode([
        'status' => true,
        'newHouse' => $newHouse,
        'existHouse' => $existHouse
    ]);
}
     
    /**
     * 
     * 
     * 
     * 
     * 
     */
     /*
    private function getHouseDataTableFormat($_house_data = NULL, $_region_id = NULL) {
        if ($_house_data != NULL and $_region_id != NULL) {
            return array(
                
                'region_id' => 0,
                'auto_id'=>$_house_data['house_uid'],
                'health_center'=>$_house_data['health_center'],
                'mohalla'=>$_house_data['mohalla'],
                'house_number' => $_house_data['house_number'],
                'land_mark' => $_house_data['address'],
                
                'house_head_name' => $_house_data['family_head'],
                'mobile_number' => $_house_data['mobile_number'],
                'total_family_member' => $_house_data['family_members'],
                'total_child' => $_house_data['no_of_child'],
                'immunization_done_or_not' => $_house_data['immunization_status'], 
                
                'no_of_living_years' => $_house_data['no_of_living_years'],
                'monthly_income' => $_house_data['monthly_income'],
                'x_co_ordinate' => $_house_data['latitude'],
                'y_co_ordinate' => $_house_data['longitude'],
                'region_code' =>$_house_data['region_code'],
                'volunter_id'=>$_house_data['volunter_id'],
                'house_status'=>$_house_data['house_status'], // 0 for default, 1 for open ,2 for refuse and 3 for locked
               // 'tran_hid' => $_house_data['tran_hid'],
                'mobile_date' =>date('Y-m-d', strtotime(str_replace('/', '-', $_house_data['mobile_date']))),
                'actual_register_date' => date('Y-m-d', strtotime(str_replace('/', '-', $_house_data['actual_register_date'])))
   
            );
        } else {
            return FALSE;
        }
    }
    */
    private function getHouseDataTableFormat($_house_data = NULL, $_region_id = NULL)
   {
    if ($_house_data != NULL && $_region_id != NULL) {

        return array(

            'region_id' => 0,
            'auto_id' => $_house_data['house_uid'] ?? NULL,
            'health_center' => $_house_data['health_center'] ?? NULL,
            'mohalla' => $_house_data['mohalla'] ?? NULL,
            'house_number' => $_house_data['house_number'] ?? NULL,
            'land_mark' => $_house_data['address'] ?? NULL,

            'house_head_name' => $_house_data['family_head'] ?? NULL,
            'mobile_number' => $_house_data['mobile_number'] ?? NULL,
            'total_family_member' => $_house_data['family_members'] ?? 0,
            'total_child' => $_house_data['no_of_child'] ?? 0,
            'immunization_done_or_not' => $_house_data['immunization_status'] ?? NULL,

            'no_of_living_years' => $_house_data['no_of_living_years'] ?? NULL,
            'monthly_income' => $_house_data['monthly_income'] ?? NULL,
            'x_co_ordinate' => $_house_data['latitude'] ?? NULL,
            'y_co_ordinate' => $_house_data['longitude'] ?? NULL,

            'region_code' => $_house_data['region_code'] ?? NULL,
            'volunter_id' => $_house_data['volunter_id'] ?? NULL,
            'house_status' => $_house_data['house_status'] ?? 0,

            'mobile_date' => !empty($_house_data['mobile_date'])
                ? date('Y-m-d', strtotime(str_replace('/', '-', $_house_data['mobile_date'])))
                : NULL,

            'actual_register_date' => !empty($_house_data['actual_register_date'])
                ? date('Y-m-d', strtotime(str_replace('/', '-', $_house_data['actual_register_date'])))
                : NULL,
                'pregnant_woman_available' => $_house_data['pregnant_woman_available'] ?? 0,
                'pregnant_woman_name' => $_house_data['pregnant_woman_name'] ??  NULL,
        );
    }

    return FALSE;
}

    //Permutation and combination.
    function pc_array_power_set($array) {
        // initialize by adding the empty set
        $results = array(array());
        foreach ($array as $element)
            foreach ($results as $combination)
                array_push($results, array_merge(array($element), $combination));
        return $results;
    }




    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function ashaWomenRegistration() {
        //$dataWomenNew = array('user_id'=>21,
        // 'women_new_detail' => array(
        // array('tran_wid'=>30,'house_id' => 20, 'women_name' => "sher ali", 'husband' => "sher", 'pregnant_status' => 0, 'number_of_child' => "4", 'women_age' => 30),
        // array('tran_wid'=>31,'tran_pid'=>30,'house_id' => 20, 'women_name' => "sher1", 'husband' => "sher ali", 'pregnant_status' => 1, 'almc_date' => "20/09/2012", 'number_of_child' => "4", 'women_age' => 30)));
        $dataWomenNew = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        if (isset($dataWomenNew['women_new_detail']) and $dataWomenNew['women_new_detail']) {
            $new_women_pregnant = NULL;
            $new_women_not_pregnant = NULL;
            $exist_women_data = NULL;
            for ($i = 0; $i < count($dataWomenNew['women_new_detail']); $i++) {
                if ($dataWomenNew['women_new_detail'][$i]['pregnant_status'] == 1) {
                    $women_data = $this->Mira_service_asha_model->miraWomenRegistrationModel($this->getWomenDataTableFormat($dataWomenNew['women_new_detail'][$i], $dataWomenNew['user_id']));
                    if ($women_data) {
                        $pregnant_data = $this->Mira_service_asha_model->miraPregnantRegistrationModel($this->getPregnantDataTableFormat($dataWomenNew['women_new_detail'][$i], $women_data, $dataWomenNew['user_id']));
                        $new_women_pregnant[] = array('anmc_date' => $pregnant_data['lmc_date'], 'pregnant_id' => $pregnant_data['pregnant_id'], 'house_id' => $dataWomenNew['women_new_detail'][$i]['house_id'], 'women_id' => (string) $women_data['women_id'], 'women_name' => $dataWomenNew['women_new_detail'][$i]['women_name'], 'husband' => $dataWomenNew['women_new_detail'][$i]['husband']);
                        $this->Mira_service_asha_model->updateWomenTracking(array('women_id'=>$women_data['women_id'],'pregnant_id'=>$pregnant_data['pregnant_id'],'house_id'=>$dataWomenNew['women_new_detail'][$i]['house_id'],'lmc_date'=>$pregnant_data['lmc_date'],'region_code'=>$dataWomenNew['user_id']));
                        
                    } else {
                        $exist_women_data[] = $dataWomenNew['women_new_detail'][$i];
                    }
                } else {
                    $women_data = $this->Mira_service_asha_model->miraWomenRegistrationModel($this->getWomenDataTableFormat($dataWomenNew['women_new_detail'][$i], $dataWomenNew['user_id']));
                    if ($women_data) {
                        $new_women_not_pregnant[] = array('house_id' => $dataWomenNew['women_new_detail'][$i]['house_id'], 'women_id' => (string) $women_data['women_id'], 'women_name' => $dataWomenNew['women_new_detail'][$i]['women_name'], 'husband' => $dataWomenNew['women_new_detail'][$i]['husband']);
                    } else {
                        $exist_women_data[] = $dataWomenNew['women_new_detail'][$i];
                    }
                }
            }
        }
        print_r(json_encode(array(
            'exist_women_list' => $exist_women_data,
            'new_women_pregnant' => $new_women_pregnant,
            'new_women_not_pregnant' => $new_women_not_pregnant,
            'tran_pid' => $this->Mira_service_asha_model->getTransactionIds('tran_pid', array('region_code' => $dataWomenNew['user_id'])),
            'tran_wid' => $this->Mira_service_asha_model->getTransactionIds('tran_wid', array('region_code' => $dataWomenNew['user_id']))
        )));
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     */
    private function getWomenDataTableFormat($_women_data = NULL, $_region_code = NULL) {
        if ($_women_data != NULL) {
            return array(
                'house_id' => $_women_data['house_id'],
                'name' => $_women_data['women_name'],
                'husband' => $_women_data['husband'],
                'number_of_child' => $_women_data['number_of_child'],
                'age' => $_women_data['women_age'],
                'pregnant_status' => $_women_data['pregnant_status'],
                'region_code' => $_women_data['region_code'],
                'volunter_id'=>$_women_data['volunter_id'],
                'tran_wid' => $_women_data['tran_wid'],
                 'mobile_date' =>date('Y-m-d', strtotime(str_replace('/', '-', $_women_data['mobile_date']))),
                 'actual_register_date' => date('Y-m-d', strtotime(str_replace('/', '-', $_women_data['actual_register_date'])))
    
            );
        } else {
            return FALSE;
        }
    }

    private function getPregnantDataTableFormat($_women_data = NULL, $_women_id = NULL, $_region_code = NULL) {
        if ($_women_data != NULL and $_women_id != NULL) {
            return array(
                'women_id' => $_women_id['women_id'],
                'pregnant_date' => date('Y-m-d', strtotime(str_replace('/', '-', $_women_data['almc_date']))),
                'pregnant_status' => $_women_data['pregnant_status'],
                'tran_pid' => $_women_data['tran_pid'],
                'region_code' => $_region_code,
                'mobile_date' =>date('Y-m-d', strtotime(str_replace('/', '-', $_women_data['mobile_date']))),
                'actual_register_date' => date('Y-m-d', strtotime(str_replace('/', '-', $_women_data['actual_register_date'])))
            );
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
     /*
   public function ashaChildRegistration() {
    $dataChildNew = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
    $child_data = NULL;
    $exist_child = [];
    $child_data_temp = [];

    if (isset($dataChildNew['child_new_detail']) && $dataChildNew['child_new_detail']) {
        foreach ($dataChildNew['child_new_detail'] as $childDetail) {
            $formattedChildData = $this->getChildDataTableFormat($childDetail, $dataChildNew['user_id']);
            $temp_child_data = $this->Mira_service_asha_model->miraChildRegistrationModel($formattedChildData);

            // Optional: log intermediate result
            // log_message('debug', json_encode($temp_child_data));

            if ($temp_child_data['child_id'] != 0) {
                $child_data_temp[] = array(
                    'child_id'        => $childDetail['child_id'],
                    'child_dob'       => $childDetail['dob'],
                    'child_name'      => $childDetail['child_name'],
                    'women_id'        => $childDetail['women_id'], // corrected
                    'child_category'  => $childDetail['child_category']
                );
            } else {
                $exist_child[] = $childDetail;
            }
        }
    }

    $child_data = array(
        'child_data'   => $child_data_temp,
        'exist_child'  => $exist_child
    );

    echo json_encode($child_data);
}
    */
/*
public function ashaChildRegistration_old()
{
    // ✅ Read JSON from BODY
    $rawData = file_get_contents("php://input");
    $dataChildNew = json_decode($rawData, true);

    $child_data_temp = [];
    $exist_child = [];

    if (!empty($dataChildNew) && isset($dataChildNew['child_new_detail'])) {

        foreach ($dataChildNew['child_new_detail'] as $childDetail) {

            // ✅ Format data
            $formattedChildData = $this->getChildDataTableFormat(
                $childDetail,
                $dataChildNew['user_id'] ?? null
            );

            if ($formattedChildData) {

                // ✅ Insert child
                $temp_child_data = $this->Mira_service_asha_model
                    ->miraChildRegistrationModel($formattedChildData);

                if (!empty($temp_child_data) && $temp_child_data['child_id'] != 0) {

                    $child_data_temp[] = array(
                        'child_id'       => $childDetail['child_id'] ?? null,
                        'child_dob'      => $childDetail['dob'] ?? null,
                        'child_name'     => $childDetail['child_name'] ?? null,
                        'women_id'       => $childDetail['women_id'] ?? null,
                        'child_category' => $childDetail['child_category'] ?? null,mother_blank
                        
                    );

                } else {
                    $exist_child[] = $childDetail;
                }
            }
        }
    }

    // ✅ Final response
    echo json_encode([
        'status'       => true,
        'child_data'   => $child_data_temp,
        'exist_child'  => $exist_child
    ]);
}

*/


public function ashaChildRegistration()
{
    // ✅ Read JSON from BODY
    $rawData = file_get_contents("php://input");
    $dataChildNew = json_decode($rawData, true);

    $child_data_temp = [];
    $exist_child = [];
    $mother_name_blank = [];

    if (!empty($dataChildNew) && isset($dataChildNew['child_new_detail'])) {

        foreach ($dataChildNew['child_new_detail'] as $childDetail) {

            // ✅ Format data
            $formattedChildData = $this->getChildDataTableFormat(
                $childDetail,
                $dataChildNew['user_id'] ?? null
            );

            if ($formattedChildData) {

                // ✅ Insert child
                $temp_child_data = $this->Mira_service_asha_model
                    ->miraChildRegistrationModel($formattedChildData);

                // ✅ If mother name is blank
                if (
                    isset($temp_child_data['mother_blank']) &&
                    $temp_child_data['mother_blank'] == true
                ) {

                    $mother_name_blank[] = array(
                        'child_id'   => $childDetail['child_id'] ?? null,
                        'women_id'   => $childDetail['women_id'] ?? null,
                        'child_name' => $childDetail['child_name'] ?? null,
                        'message'    => 'Mother name is blank'
                    );

                    continue;
                }

                // ✅ Insert success
                if (!empty($temp_child_data) && $temp_child_data['child_id'] != 0) {

                    $child_data_temp[] = array(
                        'child_id'       => $childDetail['child_id'] ?? null,
                        'child_dob'      => $childDetail['dob'] ?? null,
                        'child_name'     => $childDetail['child_name'] ?? null,
                        'women_id'       => $childDetail['women_id'] ?? null,
                        'child_category' => $childDetail['child_category'] ?? null
                    );

                } else {

                    // ✅ Already exists or failed
                    $exist_child[] = $childDetail;
                }
            }
        }
    }

    // ✅ Final response
    echo json_encode([
        'status'              => true,
        'child_data'          => $child_data_temp,
        'exist_child'         => $exist_child,
        'mother_name_blank'   => $mother_name_blank
    ]);
}
    /**
     * 
     * 
     * 
     * 
     */
    public function ashaChildUpdate() {
        $postData = json_decode(file_get_contents('php://input'), TRUE);
        $postReturnData = array();
        for ($i = 0; $i < count($postData); $i++) {

            $postReturnData[] = $this->Mira_service_asha_model->ashaChildUpdateModel($postData[$i]['childId'], $this->childUpdateDataFormat($postData[$i]['updateData']));
        }
        print_r(json_encode($postReturnData));
    }

    private function childUpdateDataFormat($_childDataObject = NULL) {
        $returnChildObject = NULL;
        foreach ($_childDataObject as $key => $value) {
            switch ($key) {
                case "close_status":
                    $returnChildObject['running_status'] = $value;
                    break;
                case "date":
                    $returnChildObject['closing_date'] = date('Y-m-d', strtotime($value));
                    break;
            }
        }
        if (!isset($returnChildObject['closing_date'])) {
            $returnChildObject['closing_date'] = date('Y-m-d', strtotime('now'));
        }
        return $returnChildObject;
    }

    /**
     * 
     * @param type $_child_data
     * @return boolean
     * 
     * 
     * 
     */
     /*
    private function getChildDataTableFormat($_child_data = NULL, $_region_code = NULL) {
        if ($_child_data != NULL) {
            $data = array(
                'house_id' => $_child_data['house_id'],
                'women_id' => $_child_data['women_id'],
                'child_id'=>  $_child_data['child_id'],
                'child_name' => $_child_data['child_name'],
                'name'  =>   $_child_data['mother_name'],
                'husband'  =>   $_child_data['father_name'],
                'dob' => date('Y-m-d', strtotime(str_replace('/', '-', $_child_data['dob']))),
                'region_code' => $_child_data['region_code'],
                'volunter_id'=>$_child_data['volunter_id'],
                'mobile_date' =>date('Y-m-d', strtotime(str_replace('/', '-', $_child_data['mobile_date']))),
                'actual_register_date' => date('Y-m-d', strtotime(str_replace('/', '-', $_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'],
                'reason_id'=> $_child_data['reason_id'],
                'other_reason'=> $_child_data['other_reason'],
                
            );
            if ($_child_data['gender'] == 'Male') {
                $data['gender'] = 1;
            } else if($_child_data['gender'] == 'Female') {
                $data['gender'] = 2;
            }
            else
            {
                $data['gender'] = 3; 
            }
            return $data;
        } else {
            return FALSE;
        }
    }
     */
     private function getChildDataTableFormat($_child_data = NULL, $_region_code = NULL)
     {
    if ($_child_data != NULL) {

        $data = array(
            'house_id' => $_child_data['house_id'] ?? NULL,
            'women_id' => $_child_data['women_id'] ?? NULL,
            'child_id' => $_child_data['child_id'] ?? NULL,
            'child_name' => $_child_data['child_name'] ?? NULL,

            'name' => $_child_data['mother_name'] ?? NULL,
            'husband' => $_child_data['father_name'] ?? NULL,

            'dob' => !empty($_child_data['dob'])
                ? date('Y-m-d', strtotime(str_replace('/', '-', $_child_data['dob'])))
                : NULL,

            'region_code' => $_child_data['region_code'] ?? NULL,
            'volunter_id' => $_child_data['volunter_id'] ?? NULL,

            'mobile_date' => !empty($_child_data['mobile_date'])
                ? date('Y-m-d', strtotime(str_replace('/', '-', $_child_data['mobile_date'])))
                : NULL,

            'actual_register_date' => !empty($_child_data['actual_register_date'])
                ? date('Y-m-d', strtotime(str_replace('/', '-', $_child_data['actual_register_date'])))
                : NULL,

            'child_category' => $_child_data['child_category'] ?? NULL,
            'mcp_card' => $_child_data['mcp_card'] ?? NULL,
            'why_not_vaccinated' => $_child_data['why_not_vaccinated'] ?? NULL,
            'reason_id' => $_child_data['reason_id'] ?? NULL,
            'other_reason' => $_child_data['other_reason'] ?? NULL,
            'birth_place' => $_child_data['birth_place'] ?? NULL,
        );

        // ✅ Gender Mapping
        if (isset($_child_data['gender'])) {
            if ($_child_data['gender'] == 'Male') {
                $data['gender'] = 1;
            } elseif ($_child_data['gender'] == 'Female') {
                $data['gender'] = 2;
            } else {
                $data['gender'] = 3;
            }
        } else {
            $data['gender'] = 3;
        }

        return $data;
    }

    return FALSE;
}
     
    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function ashaPregnantRegistration() {

        $dataWomenUpdate = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);

        if (isset($dataWomenUpdate['women_update_detail']) and $dataWomenUpdate['women_update_detail']) {
            $update_women_pregnant = NULL;
            $existance_women_pregnant = NULL;
            for ($i = 0; $i < count($dataWomenUpdate['women_update_detail']); $i++) {
                
                    $existance_pregnent_data = $this->Mira_service_asha_model->checkPregnentWomenExistenceModel($dataWomenUpdate['women_update_detail'][$i]['women_id'] );
                    if ($existance_pregnent_data) {
                        $existance_women_pregnant[] = array('almc_date' => $existance_pregnent_data[0]['pregnant_date'], 'pregnant_id' => $existance_pregnent_data[0]['pregnant_id '], 'women_id' => (string) $existance_pregnent_data[0]['women_id'], 'women_name' => $existance_women_data[0]['name'], 'husband' => $existance_women_data[0]['husband'],'pregnant_status'=>$existance_women_data[0]['pregnant_status'] ,'number_of_child'=>$existance_women_data[0]['number_of_child']  ,'women_age'=> $existance_women_data[0]['age'] ,'anmid'=> $existance_women_data[0]['anmid'] ,'ashaid'=> $existance_women_data[0]['region_code']  ,'level'=>$existance_women_data[0]['level'] );
                    } 
                    else
                    {
                     $pregnant_data = $this->Mira_service_asha_model->miraPregnantRegistrationModel($this->getPregnantDataTableFormat($dataWomenUpdate['women_update_detail'][$i], $dataWomenUpdate['women_update_detail'][$i], $dataWomenUpdate['user_id']));
                     $this->Mira_service_asha_model->miraWomenUpdateModel($dataWomenUpdate['women_update_detail'][$i]['women_id']);
                     $update_women_pregnant[] = array('almc_date' => $dataWomenUpdate['women_update_detail'][$i]['almc_date'], 'pregnant_id' => $pregnant_data['pregnant_id'], 'women_id' => $dataWomenUpdate['women_update_detail'][$i]['women_id']);
                     
                     // new code added
                      $women_data = $this->Mira_service_asha_model->getWomenDetailByWomenId($dataWomenUpdate['women_update_detail'][$i]['women_id']);
                    
                    // print_r(json_encode($women_data[0]['women_id']));die();
                     $this->Mira_service_asha_model->updateWomenTracking(array('women_id'=>$women_data[0]['women_id'],'pregnant_id'=>$pregnant_data['pregnant_id'],'house_id'=>$women_data[0]['house_id'],'lmc_date'=>$women_data[0]['pregnant_date'],'region_code'=>$dataWomenUpdate['user_id']));
                     
                     //
                     
                    }
     
            }

            $pregnant_women_update_data = array(
                'update_women_pregnant' => $update_women_pregnant,
                'exist_women_pregnant' => $existance_women_pregnant,
                'tran_pid' => $this->Mira_service_asha_model->getTransactionIds('tran_pid', array('region_code' => $dataWomenUpdate['user_id']))
            );
            print_r(json_encode($pregnant_women_update_data));
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function ashaUpdateWomenPregnancy() {
        // This service shoud be change with according to faisal consult.
        // Date   
        //$update_pregnant_status = array('pregnant_update' => array(array('pregnant_id' => 1, 'close_status' => 7, 'closing_date' => "12/10/2014",'second_status'=>'live','location_area'=>1), array('pregnant_id' => 2, 'close_status' => 7, 'closing_date' => "12/10/2014",'second_status'=>'live','location_area'=>1)));
        $update_pregnant_status = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        $pregnant_data = NULL;
        if (isset($update_pregnant_status) and $update_pregnant_status) {
            for ($i = 0; $i < count($update_pregnant_status['pregnant_update']); $i++) {
                if ($this->Mira_service_asha_model->miraUpdateWomenPregnancyModel($update_pregnant_status['pregnant_update'][$i])) {
                    $pregnant_data[] = array(
                        'woman_name' => $update_pregnant_status['pregnant_update'][$i]['woman_name'],
                        'pregnant_id' => $update_pregnant_status['pregnant_update'][$i]['pregnant_id'],
                        'pregnant_status' => $update_pregnant_status['pregnant_update'][$i]['close_status']
                    );
                }
            }
        }
        print_r(json_encode($pregnant_data));
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
     /*
    public function ashaChildImmunization() {

        //$dataImmunization = array('user_id' => 1, 'immunization' => array(array('child_id' => 3, 'child_detail' => array(array('vaccine_date' => "12/09/14", 'vaccine_id' => 2,), array('vaccine_date' => "12/09/14", 'vaccine_id' => 3)),), array('child_id' => 2, 'child_detail' => array(array('vaccine_date' => "12/09/14", 'vaccine_id' => 2,), array('vaccine_date' => "12/09/14", 'vaccine_id' => 3)),)));
        $dataImmunization = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        if (isset($dataImmunization) and $dataImmunization) {
            for ($i = 0; $i < count($dataImmunization['immunization']); $i++) {
                $child_id = $dataImmunization['immunization'][$i]['child_id'];
                $volunter_id = $dataImmunization['immunization'][$i]['volunter_id'];
                $region_code = $dataImmunization['immunization'][$i]['region_code'];
                for ($j = 0; $j < count($dataImmunization['immunization'][$i]['child_detail']); $j++) {
                    if ($this->Mira_service_asha_model->miraChildImmunizationModel($this->parsingChildImmunizationFormat($dataImmunization['immunization'][$i]['child_detail'][$j], $child_id,$volunter_id,$region_code))) {
                        $vaccine_id = $this->getVaccineIdByVaccineName($dataImmunization['immunization'][$i]['child_detail'][$j]['vaccine_id']);
                        $immunizatio[] = array('child_id' => $child_id, 'vaccine_id' => $vaccine_id,'vaccine_code'=>$dataImmunization['immunization'][$i]['child_detail'][$j]['vaccine_id'],'status'=>1);
                    }
                    else
                    {
                         $vaccine_id = $this->getVaccineIdByVaccineName($dataImmunization['immunization'][$i]['child_detail'][$j]['vaccine_id']);
                      $immunizatio[] = array('child_id' => $child_id, 'vaccine_id' => $vaccine_id,'vaccine_code'=>$dataImmunization['immunization'][$i]['child_detail'][$j]['vaccine_id'],'status'=>0);  
                    }
                }
            }
        }
        print_r(json_encode($immunizatio));
    }
    */
    
    public function ashaChildImmunization()
    {
    // ✅ Read JSON from BODY
    $rawData = file_get_contents("php://input");
    $dataImmunization = json_decode($rawData, true);

    $immunizatio = []; // ✅ initialize array

    if (!empty($dataImmunization) && isset($dataImmunization['immunization'])) {

        foreach ($dataImmunization['immunization'] as $immunizationData) {

            $child_id    = $immunizationData['child_id'] ?? null;
            $volunter_id = $immunizationData['volunter_id'] ?? null;
            $region_code = $immunizationData['region_code'] ?? null;

            if (!empty($immunizationData['child_detail'])) {

                foreach ($immunizationData['child_detail'] as $vaccineDetail) {

                    $formattedData = $this->parsingChildImmunizationFormat(
                        $vaccineDetail,
                        $child_id,
                        $volunter_id,
                        $region_code
                    );

                    if ($formattedData) {

                        $result = $this->Mira_service_asha_model
                            ->miraChildImmunizationModel($formattedData);

                        $vaccine_id = $this->getVaccineIdByVaccineName(
                            $vaccineDetail['vaccine_id']
                        );

                        $immunizatio[] = array(
                            'child_id'     => $child_id,
                            'vaccine_id'   => $vaccine_id,
                            'vaccine_code' => $vaccineDetail['vaccine_id'],
                            'status'       => $result ? 1 : 0
                        );
                    }
                }
            }
        }
    }

    // ✅ Proper JSON response
    echo json_encode([
        'status' => true,
        'data'   => $immunizatio
    ]);
}
    
    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function ashaChildImmunizationNew() {

        //$dataImmunization = array('user_id' => 1, 'immunization' => array(array('child_id' => 3, 'child_detail' => array(array('vaccine_date' => "12/09/14", 'vaccine_id' => 2,plannerId=>1), array('vaccine_date' => "12/09/14", 'vaccine_id' => 3,plannerId=>1)),), array('child_id' => 2, 'child_detail' => array(array('vaccine_date' => "12/09/14", 'vaccine_id' => 2,plannerId=>1), array('vaccine_date' => "12/09/14", 'vaccine_id' => 3,plannerId=>1)),)));
        $dataImmunization = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        if (isset($dataImmunization) and $dataImmunization) {
            for ($i = 0; $i < count($dataImmunization['immunization']); $i++) {
                $child_id = $dataImmunization['immunization'][$i]['child_id'];
                for ($j = 0; $j < count($dataImmunization['immunization'][$i]['child_detail']); $j++) {
                    if ($this->Mira_service_asha_model->miraChildImmunizationModel($this->parsingChildImmunizationFormatNew($dataImmunization['immunization'][$i]['child_detail'][$j], $child_id))) {

                        $immunizatio[] = array('child_id' => $child_id, 'vaccine_id' => $dataImmunization['immunization'][$i]['child_detail'][$j]['vaccine_id']);
                    }
                }
            }
        }
        print_r(json_encode($immunizatio));
    }

//    public function getVaccineTest(){
//        $mdb1=$this->load->database('mdb',TRUE);
//        $mdb1->select('*');
//        $mdb1->from('master_vaccine_child');
//        $query=  $mdb1->get();
//        foreach ($query->result_array() as $key => $value) {
//            print_r($this->getVaccineIdByVaccineName($value['vaccine_name']));
//            echo '</br>';
//        }
//    }

    /**
     * 
     * @param type $_vaccine_details
     * @param type $_child_id
     * @return boolean
     * 
     * 
     */
    private function getVaccineIdByVaccineName($_vaccine_name = NULL) {
        $vaccine_id = NULL;
        switch ($_vaccine_name) {
            case 'Polio and BCG':
                $vaccine_id = 1;
                break;
            case 'Polio-1 DPT-Hep B + Hib 1, Pnemococcal 1':
                $vaccine_id = 2;
                break;
            case 'Polio-2 DPT-Heb B + Hib 2, Pnemococcal 2':
                $vaccine_id = 3;
                break;
            case 'Polio-3 DPT-Heb B + Hib 3, Pnemococcal 3':
                $vaccine_id = 4;
                break;
            case 'Measles':
                $vaccine_id = 5;
                break;
            case 'Vitamin-A':
                $vaccine_id = 6;
                break;
            case 'Deworming Tablets':
                $vaccine_id = 7;
                break;

            case 'Hepatitis B-0':
                $vaccine_id = 8;
                break;
            case 'OPV-0':
                $vaccine_id = 9;
                break;
            case 'BCG':
                $vaccine_id = 10;
                break;
            case 'Penta-1':case'Pentavalent-1':
                $vaccine_id = 11;
                break;
            case 'OPV-1':
                $vaccine_id = 12;
                break;
            case 'PCV-1':
                $vaccine_id = 13;
                break;
            case 'Penta-2':case'Pentavalent-2':
                $vaccine_id = 14;
                break;
            case 'OPV-2':
                $vaccine_id = 15;
                break;
            case 'PCV-2':
                $vaccine_id = 16;
                break;
            case 'Penta-3':case'Pentavalent-3':
                $vaccine_id = 17;
                break;
            case 'OPV-3':
                $vaccine_id = 18;
                break;
             case 'PCV-3': 
                $vaccine_id = 19;
                break;
            case 'IPV':
                $vaccine_id = 20;
                break;
            case 'Measles':
                $vaccine_id = 21;
                break;
            case 'OPV Booster':
                $vaccine_id = 22;
                break;
            case 'Measles Booster':
                $vaccine_id = 23;
                break;




            case 'Rotavirus-1':
                $vaccine_id = 24;
                break;
            case 'IPV-1':
                $vaccine_id = 27;
                break;
            case 'Rotavirus-2':
                $vaccine_id = 25;
                break;
            case 'Rotavirus-3':
                $vaccine_id = 26;
                break;
            case 'IPV-2':
                $vaccine_id = 28;
                break;

//            case '':
//                $vaccine_id = 8;
//                break;
//            case 'Pentavalent-3':
//                $vaccine_id = 9;
//                break;
//            case 'Measles':
//                $vaccine_id = 10;
//                break;

           case 'PCV Booster':
                $vaccine_id = 29;
               break;
            case 'DPT Booster':
                $vaccine_id = 30;
               break;
//            case 'OPV Booster':
//                $vaccine_id = 12;
//                break;
//            case 'Vitamin-A':
//                $vaccine_id = 13;
//                break;
//            case 'Measles Booster':
//                $vaccine_id = 14;
//                break;
        }
        return $vaccine_id;
    }
/*
    private function parsingChildImmunizationFormat($_vaccine_details = NULL, $_child_id = NULL,$volunter_id= NULL,$region_code=NULL) {
        if ($_vaccine_details != NULL and $_child_id != NULL) {
            $vaccine_id = $this->getVaccineIdByVaccineName($_vaccine_details['vaccine_id']);
            return array(
                'child_id' => $_child_id,
                'region_code' => $region_code,
                'volunter_id' => $volunter_id,
                'vaccine_id' => $vaccine_id,
                'vaccine_code'=>$_vaccine_details['vaccine_id'],
                'vaccine_date' => date('Y-m-d', strtotime(str_replace('/', '-', $_vaccine_details['vaccine_date'])))
            );
        } else {
            return FALSE;
        }
    }
*/

private function parsingChildImmunizationFormat(
    $_vaccine_details = NULL,
    $_child_id = NULL,
    $volunter_id = NULL,
    $region_code = NULL
) {
    if ($_vaccine_details != NULL && $_child_id != NULL) {

        $vaccine_id = $this->getVaccineIdByVaccineName(
            $_vaccine_details['vaccine_id']
        );

        return array(
            'child_id'     => $_child_id,
            'region_code'  => $region_code,
            'volunter_id'  => $volunter_id,
            'vaccine_id'   => $vaccine_id,
            'vaccine_code' => $_vaccine_details['vaccine_id'],
            'status' => $_vaccine_details['forced_selection'],
            'vaccine_date' => !empty($_vaccine_details['vaccine_date'])
                ? date(
                    'Y-m-d',
                    strtotime(str_replace('/', '-', $_vaccine_details['vaccine_date']))
                )
                : NULL
        );
    }

    return FALSE;
}
    private function parsingChildImmunizationFormatNew($_vaccine_details = NULL, $_child_id = NULL) {
        if ($_vaccine_details != NULL and $_child_id != NULL) {

            return array(
                'child_id' => $_child_id,
                 'region_code' => $_vaccine_details['region_code'],
                'volunter_id' => $_vaccine_details['volunter_id'],
                'vaccine_id' => $_vaccine_details['vaccine_id'],
                'plannerId' => $_vaccine_details['plannerId'],
                'vaccine_date' => date('Y-m-d', strtotime(str_replace('/', '-', $_vaccine_details['vaccine_date'])))
            );
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     */
    public function ashaUpdateAshaQusAns() {
        //$asha_qus_ans = array('alert0' => array(array('pregnant_id' => 6, 'week_id' => 10), array('pregnant_id' => 6, 'week_id' => 11)), 'alert1' => array(array('pregnant_id' => 9, 'week_id' => 12, 'qus_id_ans' => array(array('q_id' => 1, 'ans' => 1), array('q_id' => 2, 'ans' => 2), array('q_id' => 3, 'ans' => 1), array('q_id' => 4, 'ans' => 2), array('q_id' => 5, 'ans' => 2))), array('pregnant_id' => 1, 'week_id' => 13, 'qus_id_ans' => array(array('q_id' => 0, 'ans' => 0), array('q_id' => 1, 'ans' => 0), array('q_id' => 2, 'ans' => 0), array('q_id' => 3, 'ans' => 0), array('q_id' => 4, 'ans' => 2)))));
        $asha_qus_ans = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        if (isset($asha_qus_ans) and $asha_qus_ans) {
            //This block update only alert 0.
            if (isset($asha_qus_ans['alert0']) and $asha_qus_ans['alert0']) {
                for ($i = 0; $i < count($asha_qus_ans['alert0']); $i++) {
                    if ($this->Mira_service_asha_model->miraUpdateAshaQusAnsAlert0Model($this->alert0ParsingFormat($asha_qus_ans['alert0'][$i]))) {
                        $pregnant_women_track_data[] = array('pregnant_id' => $asha_qus_ans['alert0'][$i]['pregnant_id'], 'week_id' => $asha_qus_ans['alert0'][$i]['week_id'],'status'=>2);
                    }
                    
                    else {
                        $pregnant_women_track_data[] = array('pregnant_id' => $asha_qus_ans['alert0'][$i]['pregnant_id'], 'week_id' => $asha_qus_ans['alert0'][$i]['week_id'],'status'=>2);  
                      }
                }
            }
            // end alert 0.
            //This block update only alert 1.
            if (isset($asha_qus_ans['alert1']) and $asha_qus_ans['alert1']) {
                for ($i = 0; $i < count($asha_qus_ans['alert1']); $i++) {
                    $alert1_parse_format = $this->alert1ParsingFormat($asha_qus_ans['alert1'][$i]);
                    if ($this->Mira_service_asha_model->miraUpdateAshaQusAnsAlert1Model($alert1_parse_format[0], $alert1_parse_format[1])) {
                        $pregnant_women_track_data[] = array('pregnant_id' => $asha_qus_ans['alert1'][$i]['pregnant_id'], 'week_id' => $asha_qus_ans['alert1'][$i]['week_id'],'status'=>2);
                    }
                    
                    else {
                        $pregnant_women_track_data[] = array('pregnant_id' => $asha_qus_ans['alert1'][$i]['pregnant_id'], 'week_id' => $asha_qus_ans['alert1'][$i]['week_id'],'status'=>2);
                      }
                }
            }
            // end alert 1.
        }

        print_r(json_encode($pregnant_women_track_data));
    }

    private function alert0ParsingFormat($_alert0 = NULL) {
        if ($_alert0 != NULL) {
            return array(
                'pregnant_id' => $_alert0['pregnant_id'],
                'week_id' => $_alert0['week_id'],
                'asha_status' => 1,
                'alert' => 0
            );
        } else {
            return FALSE;
        }
    }

    private function alert1ParsingFormat($_alert1 = NULL) {
        if ($_alert1 != NULL) {
            $data_asha[0] = array(
                'pregnant_id' => $_alert1['pregnant_id'],
                'week_id' => $_alert1['week_id'],
                'asha_status' => 1,
                'alert' => 1
            );
            $temp_qus_ans = NULL;
            for ($i = 0; $i < count($_alert1['qus_id_ans']); $i++) {
                $temp_qus_ans[] = array('question_id' => $_alert1['qus_id_ans'][$i]['q_id'], 'asha_answer' => $_alert1['qus_id_ans'][$i]['ans']);
            }
            $data_asha[1] = $temp_qus_ans;
            return $data_asha;
        } else {
            return FALSE;
        }
    }

    /*     * ****************************************** */

    /**
     * This function authticate mobile user and send to data
     * 
     * 
     * 
     */
    public function test1() {
        print_r($this->Mira_service_asha_model->getMasterChildVaccineDetail(4));
    }

  

    /**
     * This function authticate mobile user and send to data
     * 
     * 
     * 
     */
    public function ashaUserAuthontication() {
        $data = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
       // $data=array('id'=>'afmira','pass'=>'zmq');
        $return_data = NULL;
        if (isset($data['id']) and $data['id'] != NULL and isset($data['pass']) and $data['pass'] != NULL) {
            $data_temp = $this->Mira_service_asha_model->asahAuthonticationModel($data['id'], $data['pass']);
            //$data_temp=$this->Mira_service_model->asahAuthonticationModel($data['id'],$data['pass']);
            if ($data_temp['user']) {
                $return_data['login_code'] = 7;
              /*  $return_data['transaction'] = array('tran_hid' => $this->Mira_service_asha_model->getTransactionIds('tran_hid', array('region_code' => $data_temp['user'][0]['create_region_id'])),
                    'tran_wid' => $this->Mira_service_asha_model->getTransactionIds('tran_wid', array('region_code' => $data_temp['user'][0]['create_region_id'])),
                    'tran_pid' => $this->Mira_service_asha_model->getTransactionIds('tran_pid', array('region_code' => $data_temp['user'][0]['create_region_id'])),
                    'tran_cid' => $this->Mira_service_asha_model->getTransactionIds('tran_cid', array('region_code' => $data_temp['user'][0]['create_region_id'])));
              */
                $return_data['user_detail'] = array('name' => $data_temp['user'][0]['user_name'], 'id' => $data_temp['user'][0]['create_region_id']);
                //This function return to master vaccine details.
                //// $return_data['total_data']['masterVaccine'] = $this->houseParsing($data_temp['masterVaccine']);
                // This block used for house parsing.
                $return_data['total_data']['house_data'] = $this->houseParsing($data_temp['houseList']);
                //This function block women detais parse accding to old data.
                $return_data['total_data']['women_data'] = $this->womenParsing($data_temp['womenList']);
                //This block used for child parsing.
                $return_data['total_data']['child_data'] = $this->childParsing($data_temp['childList']);
                //This block is working for pregnant women.
               // $return_data['total_data']['women_pregnant_data'] = $this->pregnantParsing($data_temp['pregnantList']);
                //This block is worhing for child immunization.
                $return_data['total_data']['immunization_data'] = $this->childImmuniParsing($data_temp['childImmuniList']);
                //This block is working for pregnant immunization.
              //  $return_data['total_data']['pregnant_track_data'] = $this->pregnantImmunizationParsing($data_temp['pregnantImmuniList']);
                //$data['user_detail']['total_data']['pregnant_track_data'] =$data_temp['pregnantImmuniList'];
              //  $return_data['total_data']['anc_status'] = $this->ancStatusParsing($data_temp['pregnantAncStatus']);
                //This block working for anc status.
                
                $return_data['centre_detail_with_mohalla'] = $this->Mira_service_asha_model->centre_detail($data_temp['user'][0]['create_region_id']);
                $return_data['vaccine_details'] = $data_temp['vaccine_details'];
                $return_data['folowupvisits'] = $data_temp['folowupvisits'];
            } else {
                $return_data['login_code'] = 0;
                $return_data['user_detail'] = NULL;
                $return_data['total_data'] = NULL;
            }
        } else {
            $return_data['login_code'] = 0;
            $return_data['user_detail'] = NULL;
            $return_data['total_data'] = NULL;
        }


        print_r(json_encode($return_data));
    }
    
    
    public function volunterLogin()
   {
   // header('Content-Type: application/json');

    $data = json_decode(urldecode($_SERVER['HTTP_JSON']), true);

    if (
        empty($data['id']) ||
        empty($data['pass'])
    ) {
        echo json_encode([
            'status' => false,
            'message' => 'Login ID and Password are required'
        ]);
        return;
    }

    $loginId = $data['id'];
    $password = $data['pass'];

    // 1. Authenticate volunteer
    $profile = $this->Mira_service_asha_model->volunterAuthonticationModel($loginId, $password);

    if (!$profile) {
        echo json_encode([
            'status' => false,
            'message' => 'Invalid credentials'
        ]);
        return;
    }

    // 2. Get users under same region_code_super
    $users = $this->Mira_service_asha_model->getUsersUnderSuperRegion(
        $profile['volunter_id']
    );

    echo json_encode([
        'status' => true,
        'message' => 'Login successful',
        'profile' => $profile,
        'users_under_region' => $users
    ]);
}

    
    
    /**
     * 
     * 
     * 
     * 
     */
    private function houseParsing($_house_array = NULL) {
        if ($_house_array != NULL and $_house_array) {
            $house_data = NULL;
            for ($i = 0; $i < count($_house_array); $i++) {
                $house_data[] = array('health_center'=>$_house_array[$i]['health_center'], 'mohalla'=>$_house_array[$i]['mohalla'],'house_id' => $_house_array[$i]['auto_id'] ,'house_number' => $_house_array[$i]['house_number'] ,'address' => $_house_array[$i]['land_mark'] , 'family_head' => $_house_array[$i]['house_head_name'], 'mobile_number' => $_house_array[$i]['mobile_number'] , 'family_members' => $_house_array[$i]['total_family_member'] , 'no_of_child' => $_house_array[$i]['total_child'], 'immunization_status' => $_house_array[$i]['immunization_done_or_not'], 'no_of_pregnents' => $_house_array[$i]['no_of_pregnents'] , 'no_of_living_years' => $_house_array[$i]['no_of_living_years'], 'monthly_income' => $_house_array[$i]['monthly_income'], 'latitude' => $_house_array[$i]['x_co_ordinate'], 'longitude' => $_house_array[$i]['y_co_ordinate'],'region_code' => $_house_array[$i]['region_code'],'volunter_id' => $_house_array[$i]['volunter_id'], 'register_date' => date('d/m/Y', strtotime($_house_array[$i]['actual_register_date'])),'house_status' => $_house_array[$i]['house_status'],'pregnant_woman_available' => $_house_array[$i]['pregnant_woman_available'],'pregnant_woman_name' => $_house_array[$i]['pregnant_woman_name']);
            }
            return $house_data;
        } else {
            return NULL;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    private function womenParsing($_women_array = NULL) {
        if ($_women_array != NULL and $_women_array) {
            $women_data = NULL;
            for ($j = 0; $j < count($_women_array); $j++) {
                for ($i = 0; $i < count($_women_array[$j]); $i++) {
                    $women_data[$j][$i] = array(
                        'house_id' => $_women_array[$j][$i]['house_id'],
                        'women_id' => $_women_array[$j][$i]['women_id'],
                        'women_name' => $_women_array[$j][$i]['name'],
                        'husband' => $_women_array[$j][$i]['husband'],
                        'number_of_child' => $_women_array[$j][$i]['number_of_child'],
                        'women_age' => $_women_array[$j][$i]['age'],
                        'region_code' => $_women_array[$j][$i]['region_code'],
                        'volunter_id' => $_women_array[$j][$i]['volunter_id'],
                        'register_date' => date('d/m/Y', strtotime($_women_array[$j][$i]['actual_register_date']))
                    );
                }
            }
            return $women_data;
        } else {
            return NULL;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    private function childParsing($_child_array = NULL) {
        if ($_child_array != NULL and $_child_array) {
            $child_data = NULL;
            for ($i = 0; $i < count($_child_array); $i++) {
                for ($j = 0; $j < count($_child_array[$i]); $j++) {
                    $child_data[$i][$j] = array(
                        'women_id' => $_child_array[$i][$j]['women_id'],
                        'child_id' => $_child_array[$i][$j]['child_id'],
                        'child_name' => $_child_array[$i][$j]['child_name'],
                        'dob' => date('d/m/Y', strtotime($_child_array[$i][$j]['dob'])),
                        'region_code' => $_child_array[$i][$j]['region_code'],
                        'volunter_id' => $_child_array[$i][$j]['volunter_id'],
                        'register_date' => date('d/m/Y', strtotime($_child_array[$i][$j]['actual_register_date'])),
                        'close_status' => $_child_array[$i][$j]['running_status'],
                        'child_category' => $_child_array[$i][$j]['child_category'],
                        'mcp_card' => $_child_array[$i][$j]['mcp_card'],
                        'why_not_vaccinated' => $_child_array[$i][$j]['why_not_vaccinated'],
                        'other_reason' => $_child_array[$i][$j]['other_reason']
                    );
                    if ($_child_array[$i][$j]['gender'] == 1) {
                        $child_data[$i][$j]['gender'] = 'Male';
                    } else if($_child_array[$i][$j]['gender'] == 2) {
                        $child_data[$i][$j]['gender'] = 'Female';
                    }
                    else
                    {
                         $child_data[$i][$j]['gender'] = 'Other';
                    }
                    
                    if ($_child_array[$i][$j]['birth_place'] == 1) {
                        $child_data[$i][$j]['birth_place'] = 'Government';
                    } else if($_child_array[$i][$j]['birth_place'] == 2) {
                        $child_data[$i][$j]['birth_place'] = 'Private';
                    }
                    else if($_child_array[$i][$j]['birth_place'] == 3)
                    {
                         $child_data[$i][$j]['birth_place'] = 'Home';
                    }
                    else
                    {
                       $child_data[$i][$j]['birth_place'] = 'NA'; 
                    }
                }
            }
            return $child_data;
        } else {
            return NULL;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function pregnantParsing($_pregnant_array = NULL) {
        if ($_pregnant_array != NULL and $_pregnant_array) {
            $pregnant_data = NULL;
            for ($i = 0; $i < count($_pregnant_array); $i++) {
                for ($j = 0; $j < count($_pregnant_array[$i]); $j++) {
                    $pregnant_data[$i][$j] = array(
                        'second_status' => $_pregnant_array[$i][$j]['delivered_baby_status'],
                        'woman_name' => $_pregnant_array[$i][$j]['name'],
                        'location_area' => $_pregnant_array[$i][$j]['delivery_location'],
                        'women_id' => $_pregnant_array[$i][$j]['women_id'],
                        'anmc_date' => date('d/m/Y', strtotime($_pregnant_array[$i][$j]['pregnant_date'])),
                        'pregnant_status' => $_pregnant_array[$i][$j]['pregnant_status'],
                        'pregnant_id' => $_pregnant_array[$i][$j]['pregnant_id'],
                        'closing_date' => date('d/m/Y', strtotime($_pregnant_array[$i][$j]['closing_date'])),
                        'close_status' => $_pregnant_array[$i][$j]['delivery_status'],
                        'register_date' => date('d/m/Y', strtotime($_pregnant_array[$i][$j]['registration_date']))
                    );
                }
            }
            return $pregnant_data;
        } else {
            return NULL;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    private function childImmuniParsing($_child_immuni_data = NULL) {
        if ($_child_immuni_data != NULL and $_child_immuni_data) {
            $child_immuni_data = NULL;
            for ($i = 0; $i < count($_child_immuni_data); $i++) {
                for ($j = 0; $j < count($_child_immuni_data[$i]); $j++) {
                    $child_immuni_data[$i][$j] = array(
                        'child_id' => $_child_immuni_data[$i][$j]['child_id'],
                        'vaccine_date' => date('d/m/Y', strtotime($_child_immuni_data[$i][$j]['vaccine_date'])),
                        'vaccine_id' => $_child_immuni_data[$i][$j]['vaccine_name'],
                        'region_code' => $_child_immuni_data[$i][$j]['region_code'],
                        'volunter_id' => $_child_immuni_data[$i][$j]['volunter_id']
                    );
                }
            }
            return $child_immuni_data;
        } else {
            return NULL;
        }
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    public function pregnantImmunizationParsing($_pregnant_immunization_data = NULL) {
        if ($_pregnant_immunization_data != NULL and $_pregnant_immunization_data) {
            $pregnant_immuni_data = NULL;
            for ($i = 0; $i < count($_pregnant_immunization_data); $i++) {
                if ($_pregnant_immunization_data[$i]['alert0'] != NULL) {
                    for ($j = 0; $j < count($_pregnant_immunization_data[$i]['alert0']); $j++) {
                        $pregnant_immuni_data[$i]['alert0'][] = array(
                            'week_id' => $_pregnant_immunization_data[$i]['alert0'][$j]['week_id'],
                            'pregnant_id' => $_pregnant_immunization_data[$i]['alert0'][$j]['pregnant_id']
                        );
                    }
                } else {
                    $pregnant_immuni_data[$i]['alert0'] = NULL;
                }

                if ($_pregnant_immunization_data[$i]['alert1'] != NULL) {



                    for ($j = 0; $j < count($_pregnant_immunization_data[$i]['alert1']); $j++) {


                        $pregnant_immuni_data[$i]['alert1'][$j] = array(
                            'week_id' => $_pregnant_immunization_data[$i]['alert1'][$j]['week_id'],
                            'pregnant_id' => $_pregnant_immunization_data[$i]['alert1'][$j]['pregnant_id']
                        );




                        for ($k = 0; $k < count($_pregnant_immunization_data[$i]['alert1'][$j]['qus_id_ans']); $k++) {
                            $pregnant_immuni_data[$i]['alert1'][$j]['qus_id_ans'][$k]['q_id'] = $_pregnant_immunization_data[$i]['alert1'][$j]['qus_id_ans'][$k]['question_id'];



                            if ($_pregnant_immunization_data[$i]['alert1'][$j]['qus_id_ans'][$k]['anm_answer']) {
                                $pregnant_immuni_data[$i]['alert1'][$j]['qus_id_ans'][$k]['ans'] = $_pregnant_immunization_data[$i]['alert1'][$j]['qus_id_ans'][$k]['anm_answer'];
                            } else {
                                $pregnant_immuni_data[$i]['alert1'][$j]['qus_id_ans'][$k]['ans'] = $_pregnant_immunization_data[$i]['alert1'][$j]['qus_id_ans'][$k]['asha_answer'];
                            }
                        }
                    }
                } else {
                    $pregnant_immuni_data[$i]['alert1'] = NULL;
                }
            }
            return $pregnant_immuni_data;
        } else {
            return NULL;
        }
    }

    /**
     * 
     * 
     * 
     * 
     */
    public function ancStatusParsing($anc_status = NULL) {
        if ($anc_status != NULL and $anc_status) {
            $temp_data = NULL;
            for ($i = 0; $i < count($anc_status); $i++) {
                for ($j = 0; $j < count($anc_status[$i]); $j++) {
                    $temp_data[$i][$j] = array('pregnant_id' => $anc_status[$i][$j]['pregnant_id'], 'anc_code' => $anc_status[$i][$j]['anc_code'], 'critical_status' => $anc_status[$i][$j]['critical_status']);
                }
            }
            return $temp_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;
        }
    }
    
    public function regionArea()
    {
                    $this->data['stateInfo']=$this->Mira_service_asha_model->getStatedataforDMC(); 
                    $this->data['districtInfo']=$this->Mira_service_asha_model->getDistrictdataforDMC(); 
                    $this->data['blockInfo']=$this->Mira_service_asha_model->getBlockdataforDMC();  
                    echo json_encode($this->data, JSON_UNESCAPED_SLASHES);
    }
    
    
      public function saveUserData(){

        $datahouse = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        $newUser = NULL;
  
        if (isset($datahouse) and $datahouse) {
            for ($i = 0; $i < count($datahouse['userDetails']); $i++) {
                 if ($new_house_data = $this->Mira_service_asha_model->saveUserInfo($this->getUserDetailTableFormat($datahouse['userDetails'][$i], $datahouse['region_id']))) {
                    $newUser[] = $new_house_data;
                }
            }
        }
        print_r(json_encode(array('newUser' => $newUser)));
        
    }


      private function getUserDetailTableFormat($_user_data = NULL, $_region_id = NULL) {
        if ($_user_data != NULL and $_region_id != NULL) {
            return array(
                'region_id' => $_region_id,
                'session_id' => $_session_id,
                'name' => $_user_data['name'],
                'age' => $_user_data['age'],
                'sex' => $_user_data['sex'],
                'mobile' => $_user_data['mobile'],
                'address' => $_user_data['address'],
                'totalMembers' => $_user_data['totalMembers'],
                'block' => $_user_data['block'],
                'district' => $_user_data['district'],
                'state' => $_user_data['state']
            );
        } else {
            return FALSE;
        }
    }

      public function TotalSummary() {
     
        $data = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        
        $return_data = NULL;
        if (isset($data['uid']) and $data['uid'] != NULL and isset($data['endate']) and $data['endate'] != NULL and isset($data['stdate']) and $data['stdate'] != NULL) {
             $return_data['thouse'] = $this->Mira_service_asha_model->totalHouses($data['uid'],$data['stdate'],$data['endate']);
             $return_data['tchild'] = $this->Mira_service_asha_model->totalChildren($data['uid'],$data['stdate'],$data['endate']);
            // $return_data['twomen'] = $this->Mira_service_asha_model->totalWomen($data['uid'],$data['stdate'],$data['endate']);
            //  $return_data['tpgwomen']=$this->Mira_service_asha_model->totalPgWomen($data['uid'],$data['stdate'],$data['endate']);;
            // $return_data['tnonpgwomen']=$this->Mira_service_asha_model->totalNonPgWomen($data['uid'],$data['stdate'],$data['endate']);;
            // $return_data['thrp']=$this->Mira_service_asha_model->totalHrp($data['uid'],$data['stdate'],$data['endate']);;
             $return_data['tvaccine']=$this->Mira_service_asha_model->totalVaccinations($data['uid'],$data['stdate'],$data['endate']);
            // $return_data['tpgclosed']=$this->Mira_service_asha_model->totalPgWomenClosed($data['uid'],$data['stdate'],$data['endate']);
             
             $return_data['tchclosed']=$this->Mira_service_asha_model->totalChildClosed($data['uid'],$data['stdate'],$data['endate']);
             $return_data['tchzerodose']=$this->Mira_service_asha_model->totalzerodosechild($data['uid'],$data['stdate'],$data['endate']);
             $return_data['tchpartiallyimmunized']=$this->Mira_service_asha_model->totalpartiallyimmunizedchild($data['uid'],$data['stdate'],$data['endate']);
             $return_data['tchfullyimmunized']=$this->Mira_service_asha_model->totalfullyimmunizedchild($data['uid'],$data['stdate'],$data['endate']);
             
             
             $return_data['tmira_theater_activity']=0;//$this->Mira_service_asha_model->totalmira_theater_activity($data['uid'],$data['stdate'],$data['endate']);
             $return_data['tkiosk_activity']=0;//$this->Mira_service_asha_model->totalkiosk_activity($data['uid'],$data['stdate'],$data['endate']);  
             $return_data['tposter_compaign_activity']=0;//$this->Mira_service_asha_model->totalposter_compaign_activity($data['uid'],$data['stdate'],$data['endate']);
             $return_data['tposter_compaign_activity']=0;//$this->Mira_service_asha_model->totalposter_compaign_activity($data['uid'],$data['stdate'],$data['endate']);
             $return_data['tstakeholder_meeting_activity']=0;//$this->Mira_service_asha_model->totalstakeholder_meeting_activity($data['uid'],$data['stdate'],$data['endate']);
             $return_data['ttraining_activity']=0;//$this->Mira_service_asha_model->totaltraining_activity($data['uid'],$data['stdate'],$data['endate']);
             
             
        }
         print_r(json_encode($return_data));
     }
     
      public function userModulePlayTracking() {
       
        $datahouse = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        $newHouse = NULL;
        $existHouse = NULL;
        if (isset($datahouse) and $datahouse) {
            for ($i = 0; $i < count($datahouse['ModuleDetails']); $i++) {
                $existence_house_data = $this->Mira_service_asha_model->checkModuleExistenceModel($datahouse['ModuleDetails'][$i]['session_id'],$datahouse['ModuleDetails'][$i]['module_code']);
                if ($existence_house_data) {
                    $existHouse[] = array('module_id'=>0,'session_id' => $existence_house_data[0]['session_id'], 'module_code' => $existence_house_data[0]['module_code']);
                } else if ($new_house_data = $this->Mira_service_asha_model->modulePlayStatus($this->getModuleDataTableFormat($datahouse['ModuleDetails'][$i]))) {
                    $newHouse[] = $new_house_data;
                }
            }
        }
        print_r(json_encode(array('newModuleData' => $newHouse, 'existModuleData' => $existHouse)));
    }

    /**
     * 
     * 
     * 
     * 
     * 
     */
    private function getModuleDataTableFormat($_house_data = NULL) {
        if ($_house_data != NULL ) {
            return array(
                'session_id' => $_house_data['session_id'],
                'module_code' => $_house_data['module_code']
   
            );
        } else {
            return FALSE;
        }
    }

      
    
    //New Work for Services  
     public function addSelfandGroupRegisteration() {
        $userData = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        $newData = NULL;
        if (isset($userData) and $userData) {
            for ($i = 0; $i < count($userData['selfUserRegisterationDetails']); $i++) {

                if ($new_data = $this->Mira_service_asha_model->selfRegistrationModel($this->getSelfRegistrationDataTableFormat($userData['selfUserRegisterationDetails'][$i]))) {
                    $newData[] = $new_data;
                }
            }
        }
        print_r(json_encode(array('insertedData' => $newData)));
    }
     public function addModuleTrackingData() {
        $userData = json_decode(urldecode($_SERVER['HTTP_JSON']), TRUE);
        $newData = NULL;
        if (isset($userData) and $userData) {
            for ($i = 0; $i < count($userData['moduleDetails']); $i++) {

                if ($new_data = $this->Mira_service_asha_model->addModuleTrackingDataModel($this->getModulesTrackingDataTableFormat($userData['moduleDetails'][$i]))) {
                    $newData[] = $new_data;
                }
            }
        }
        print_r(json_encode(array('insertedData' => $newData)));
    }
     private function getSelfRegistrationDataTableFormat($_tran_data = NULL) {
        if ($_tran_data != NULL) {
            return array(
                'sessionId' => $_tran_data['sessionId'],
                'sessoinType' => $_tran_data['sessoinType'],
                'name' => $_tran_data['name'],
                'adolcent_number' => $_tran_data['adolcent_number'],
                'children_number' => $_tran_data['children_number'],
                'state' => $_tran_data['state'],
                'district' => $_tran_data['district'],
                'block' => $_tran_data['block'],
                'address' => $_tran_data['address'],
                'mobiledateTime' => $_tran_data['mobiledateTime'],
                'region_code'=> $_tran_data['region_code']
            );
        } else {
            return FALSE;
        }
    }
     private function getModulesTrackingDataTableFormat($_tran_data = NULL) {
        if ($_tran_data != NULL) {
            return array(
                'sessionId' => $_tran_data['sessionId'],
                'neonatol' => $_tran_data['neonatol'],
                'familyplaning' => $_tran_data['familyplaning'],
                'adolcentgirl' => $_tran_data['adolcentgirl'],
                'story' => $_tran_data['story'],
                'mobiledateTime' => $_tran_data['mobiledateTime'],
                'region_code' => $_tran_data['region_code'],
                
            );
        } else {
            return FALSE;
        }
    }  
     public function uploadImgageFile(){
        $imgId=$this->input->post('sessionId');
        $tmp_file=$_FILES['file']['tmp_name'];
        $file_name=$_FILES['file']['name'];
        
        if($imgId!=null && $tmp_file!=null){
           
            $uploadPath="resources/upload/MiraSingleAndGroupSessionImages/";
            $fileExt=explode(".",$file_name)[1];
            $newFileName=$imgId.".".$fileExt;
//            print_r($file_name);
            
            if(move_uploaded_file($tmp_file, "./".$uploadPath.$newFileName)){
                // send data to database

                
                $dataTosave=array(
                    "resource_name"=>$newFileName,
                    "resource_path"=>$uploadPath.$newFileName,
                    "sessionId"=>$imgId
                );
                
                
                $status=$this->Mira_service_asha_model->insertImage($dataTosave);
                if($status==0)
                {
                   echo json_encode(array("inserted_status"=>0,"session_id"=>$imgId,"msg"=>0)); 
                }
                else if($status==1){
                    echo json_encode(array("inserted_status"=>1,"session_id"=>$imgId,"msg"=>1));
                }
                else if($status==2)
                {
                 echo json_encode(array("inserted_status"=>0,"session_id"=>$imgId,"msg"=>2));   
                }
                    
                else{
                    echo json_encode(array("inserted_status"=>0,"session_id"=>$imgId,"msg"=>3)); 
                }
                
            }
            else{
                echo json_encode(array("inserted_status"=>0,"session_id"=>$imgId,"msg"=>3)); 
            }
            
        }
        else{
                echo json_encode(array("inserted_status"=>0,"session_id"=>$imgId,"msg"=>4)); //Data not found to upload
            }
        
    }
    
    
     public function childFollowupVisits() {

         $input = json_decode(file_get_contents("php://input"), true);

    // Safety check
    if (!isset($input['followup_visit_data']) || !is_array($input['followup_visit_data'])) {
        echo json_encode([
            'status' => FALSE,
            'message' => 'Invalid or missing followup visit data'
        ]);
        return;
    }
    $response = $this->Mira_service_asha_model->child_followup_data($input['followup_visit_data']);
    echo json_encode($response);
    }
    
    public function saveStorySessionData_old_post(){
        
         $jsonData = file_get_contents('php://input'); // get input data in json format
        $childData = json_decode($jsonData, true);
        //child registeration
        
        $cdata['child_uid'] = $childData['child_uid'];
        
        
        
        // session registeration
        $sdata['session_uid'] =$childData['session_uid'];
        $sdata['child_uid'] = $childData['child_uid'];
        $sdata['video_start_time'] = $childData['video_start_time'];
        $sdata['video_end_time'] = $childData['video_end_time'];
        $sdata['createrid'] = $childData['createrid'];
        $sdata['storyid'] = $childData['storyid'];
        $sdata['status'] = $childData['status'];
         $sdata['region_code'] = $childData['region_code'];
          $sdata['volunter_id'] = $childData['volunter_id'];
        
          // echo(json_encode($childData));
          // die();
        $status = $this->Mira_service_asha_model->saveStorySessions($cdata,$sdata);
       
        echo(json_encode($status));
 
    }

    /////
   public function saveStorySessionData()
    {
        // Allow only POST requests
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode([
                'status'  => FALSE,
                'message' => 'Invalid request method'
            ]);
            return;
        }

        $jsonData = file_get_contents('php://input');
        $request  = json_decode($jsonData, true);

        if (empty($request['sessions']) || !is_array($request['sessions'])) {
            echo json_encode([
                'status'  => FALSE,
                'message' => 'Invalid request format'
            ]);
            return;
        }

        $response = [];

        foreach ($request['sessions'] as $row) {

            $cdata = [
                'child_uid' => $row['child_uid']
            ];

            $sdata = [
                'session_uid'       => $row['session_uid'],
                'child_uid'         => $row['child_uid'],
                'region_code'       => $row['region_code'],
                'volunter_id'       => $row['volunter_id'],
                'storyid'           => $row['storyid'],
                'video_start_time'  => $row['video_start_time'],
                'video_end_time'    => $row['video_end_time'],
                'status'            => $row['status'],
            ];

            $response[] = $this->Mira_service_asha_model
                               ->saveStorySessions($cdata, $sdata);
        }

        header('Content-Type: application/json');
        echo json_encode([
            'status' => TRUE,
            'data'   => $response
        ]);
    }



}
