<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*------------------------------------------------------*/
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
 
	if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: POST, POST, OPTIONS");         
 
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
 
    exit(0);
}
/* -----------------------------------------------------*/

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
 
	if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, GET, OPTIONS");         
 
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); 
 
    exit(0);
} 
/* -----------------------------------------------------*/ 
require APPPATH . 'perutions/REST_Controller.php';
require APPPATH . 'perutions/Format.php';
use Restserver\Libraries\REST_Controller;
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
class Patient extends REST_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->library('phppass/passwordhash');
        
        // Load these helper to create JWT tokens
        $this->load->helper(['jwt', 'authorization']);    
        $this->load->library('email');
        $this->load->model('Patientmodel');
    }
    
    public function addPatient_post() {
	    
	    $doctor=$this->post('doctorid');
	    $name=$this->post('name');
	    $mobile=$this->post('mobile');
	    $alternativenumber=$this->post('alternativenumber');
	    $age=$this->post('age');
	    $gender=$this->post('gender');
	    $category=$this->post('smoke_category');
	    $categoryitems=$this->post('smoke_items');
	    $alchohol=$this->post('alchohol');
	    $duration=$this->post('alchohol_duration');
	    $drugs=$this->post('other_drugs');
	    $medicalhistory=$this->post('medical_history');
	    $categoryitems=json_encode($categoryitems);
	    
	    $sql="insert into ecom_patients(doctor_id,patient_name,patient_mobile,alternative_number,patient_age,gender,smoke_category,smoke_items,alchohol,alchohol_duration,other_drugs,medical_history) values(".$doctor.",'".$name."','".$mobile."','".$alternativenumber."','".$age."','".$gender."','".$category."','".$categoryitems."','".$alchohol."','".$duration."','".$drugs."','".$medicalhistory."')";
	    $query=$this->db->query($sql);
	    
	    $insertId = $this->db->insert_id();
	    $qry="select * from ecom_patients where patient_id='".$insertId."'";
	    $query=$this->db->query($qry);
	    $data=$query->result_array();
	    
	    $status = parent::HTTP_OK;
        $response = ['httpstatus' => $status, 'status' => 'Success', 'msg' => 'Patient registered Successfully', 'data' => $data];
        $this->response($response, $status);
	}
     
    public function UpdatePatientDetails_post()
	{
	    $doctor=$this->post('doctorid');
	    $name=$this->post('name');
	    $mobile=$this->post('mobile');
	    $alternativenumber=$this->post('alternativenumber');
	    $age=$this->post('age');
	    $gender=$this->post('gender');
	    $category=$this->post('smoke_category');
	    $categoryitems=$this->post('smoke_items');
	    $alchohol=$this->post('alchohol');
	    $duration=$this->post('alchohol_duration');
	    $drugs=$this->post('other_drugs');
	    $medicalhistory=$this->post('medical_history');
	    $categoryitems=json_encode($categoryitems);
	    $patientid=$this->post('PatientId');
        
	    $sql="update ecom_patients set patient_name='".$name."',patient_mobile='".$mobile."',alternative_number='".$alternativenumber."',patient_age='".$age."',gender='".$gender."',smoke_category='".$category."',smoke_items='".$categoryitems."',alchohol='".$alchohol."',alchohol_duration='".$duration."',other_drugs='".$drugs."',medical_history='".$medicalhistory."' where patient_id='".$patientid."'";
	    $query=$this->db->query($sql);

	    
	    $status = parent::HTTP_OK;
        $response = ['httpstatus' => $status, 'status' => 'Success', 'msg' => 'Patient Updated Successfully'];
        $this->response($response, $status);
	}
     
    public function getPatientList_post()
	{

	    $doctorid=$this->post('doctorid');
        
	    $sql="select * from ecom_patients where doctor_id=".$doctorid;
	    $query=$this->db->query($sql);
	    $data=$query->result_array();
	    
	    $status = parent::HTTP_OK;
        $response = ['httpstatus' => $status, 'status' => 'Success', 'data' => $data];
        $this->response($response, $status);
	}
     
    /*public function getPatientDetail_post()
	{

	    $patientid=$this->post('patientid');
        
	    $sql="select * from ecom_patients where patient_id='".$patientid."'";
	    $query=$this->db->query($sql);
	    $data=$query->result_array();
	    
	    $status = parent::HTTP_OK;
        $response = ['httpstatus' => $status, 'status' => 'Success', 'data' => $data];
        $this->response($response, $status);
	}*/
	
	
    public function pushCounselAssessmentold_post()
    {
        $json = trim(file_get_contents('php://input'));
        $status = parent::HTTP_OK;
        if (!empty($json)) {
            $inputData['DoctorId'] = $this->input->post('DoctorId', TRUE);
            $inputData['PatientId'] = $this->input->post('PatientId', TRUE);
            $inputData['CountStep'] = $this->input->post('CountStep', TRUE);
            $inputData['DateTime'] = $this->input->post('DateTime', TRUE);
            $inputData['Data1'] = $this->input->post('Data1', TRUE);
            $inputData['Data2'] = $this->input->post('Data2', TRUE);
            $inputData['Data3'] = $this->input->post('Data3', TRUE);
            $inputData['Data4'] = $this->input->post('Data4', TRUE);

            $input_data = json_decode($json, TRUE);
            if (!$inputData['DoctorId'] && isset($input_data['DoctorId'])) {
                $inputData['DoctorId'] = $input_data['DoctorId'];
            }
            if (!$inputData['PatientId'] && isset($input_data['PatientId'])) {
                $inputData['PatientId'] = $input_data['PatientId'];
            }
            if (!$inputData['CountStep'] && isset($input_data['CountStep'])) {
                $inputData['CountStep'] = $input_data['CountStep'];
            }
            if (!$inputData['DateTime'] && isset($input_data['DateTime'])) {
                $inputData['DateTime'] = $input_data['DateTime'];
            }
            if (!$inputData['Data1'] && isset($input_data['Data1'])) {
                $inputData['Data1'] = $input_data['Data1'];
            }
            if (!$inputData['Data2'] && isset($input_data['Data2'])) {
                $inputData['Data2'] = $input_data['Data2'];
            }
            if (!$inputData['Data3'] && isset($input_data['Data3'])) {
                $inputData['Data3'] = $input_data['Data3'];
            }
            if (!$inputData['Data4'] && isset($input_data['Data4'])) {
                $inputData['Data4'] = $input_data['Data4'];
            }
            //echo "<pre>";print_r($inputData); die;
            if (!empty($inputData['DoctorId']) && !empty($inputData['PatientId'])) {
                if ($pushCounselAssessment = $this->Patientmodel->pushCounselAssessment($inputData)) {
                    $result['status'] = "Success";
                    $result['Success'] = "TRUE";
                    $result['Value'] = "100";
                    $result['Message'] = 'Patient Counsel Assessment added successfully';
                    die(json_encode($result));
                } else {
                    $result['status'] = "Failed";
                    $result['Success'] = "FALSE";
                    $result['Message'] = 'Please check your Entry.';
                    die(json_encode($result));
                }
            } else {
                echo json_encode(array('status' => 'Failed', 'Success' => "FALSE", 'Value' => "100", 'Message' => 'wrong key', 'Result' => array()));
                exit;
            }
        } else {
            echo json_encode(array('status' => 'Failed', 'Success' => "FALSE", 'Value' => "100", 'Message' => 'Incorrect parameters', 'Result' => array()));
            exit;
        }
    }
    
    public function popCounselAssessment_post()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['DoctorId'] = $this->input->post('DoctorId', TRUE);
            $inputData['PatientId'] = $this->input->post('PatientId', TRUE);
            $inputData['CounStep'] = $this->input->post('CounStep', TRUE);

            $input_data = json_decode($json, TRUE);
            if (!$inputData['DoctorId'] && isset($input_data['DoctorId'])) {
                $inputData['DoctorId'] = $input_data['DoctorId'];
            }
            if (!$inputData['PatientId'] && isset($input_data['PatientId'])) {
                $inputData['PatientId'] = $input_data['PatientId'];
            }
            if (!$inputData['CounStep'] && isset($input_data['CounStep'])) {
                $inputData['CounStep'] = $input_data['CounStep'];
            }
            //echo "<pre>";print_r($inputData); die;
            if (!empty($inputData['DoctorId']) && !empty($inputData['PatientId']) && !empty($inputData['CounStep'])) {
                if ($popCounselAssessment = $this->Patientmodel->popCounselAssessment($inputData)) {
                    $result['status'] = "Success";
                    $result['Success'] = "TRUE";
                    $result['Message'] = 'Patient Counsel Assessment fetched successfully';
                    $result['Result'] = [];
                    die(json_encode($result));
                } else {
                    $result['status'] = "Failed";
                    $result['Success'] = "FALSE";
                    $result['Message'] = 'Please check your Entry.';
                    $result['Result'] = [];
                    die(json_encode($result));
                }
            } else {
                echo json_encode(array('status' => 'Success', 'Success' => "FALSE", 'Message' => 'wrong key', 'Result' => array()));
                exit;
            }
        } else {
            echo json_encode(array('status' => 'Success', 'Success' => "FALSE", 'Message' => 'Incorrect parameters', 'Result' => array()));
            exit;
        }
    }

    public function updatePushCounselAssessmentold_post()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['PatientId'] = $this->input->post('PatientId', TRUE);
            $inputData['DoctorId'] = $this->input->post('DoctorId', TRUE);
            $inputData['CountStep'] = $this->input->post('CountStep', TRUE);
            $inputData['Data1'] = $this->input->post('Data1', TRUE);
            $inputData['Data2'] = $this->input->post('Data2', TRUE);
            $inputData['Data3'] = $this->input->post('Data3', TRUE);
            $inputData['Data4'] = $this->input->post('Data4', TRUE);

            $input_data = json_decode($json, TRUE);
            if (!$inputData['PatientId'] && isset($input_data['PatientId'])) {
                $inputData['PatientId'] = $input_data['PatientId'];
            }
            if (!$inputData['DoctorId'] && isset($input_data['DoctorId'])) {
                $inputData['DoctorId'] = $input_data['DoctorId'];
            }
            if (!$inputData['CountStep'] && isset($input_data['CountStep'])) {
                $inputData['CountStep'] = $input_data['CountStep'];
            }
            if (!$inputData['Data1'] && isset($input_data['Data1'])) {
                $inputData['Data1'] = ($input_data['Data1']);
            }
            if (!$inputData['Data2'] && isset($input_data['Data2'])) {
                $inputData['Data2'] = ($input_data['Data2']);
            }
            if (!$inputData['Data3'] && isset($input_data['Data3'])) {
                $inputData['Data3'] = ($input_data['Data3']);
            }
            if (!$inputData['Data4'] && isset($input_data['Data4'])) {
                $inputData['Data4'] = ($input_data['Data4']);
            }
            // echo "<pre>";print_r($inputData); die;
            if (!empty($inputData['PatientId']) && !empty($inputData['DoctorId'])) {
                $arr = array(
                    'assessment_data' => json_encode($inputData['Data1']),
                    'assessment_data2' => json_encode($inputData['Data2']),
                    'assessment_data3' => json_encode($inputData['Data3']),
                    'assessment_data4' => json_encode($inputData['Data4']),
                    'coun_step' => $inputData['CountStep'],
                );
                if (!$inputData['Data1']) {
                    unset($arr['assessment_data']);
                }
                if (!$inputData['Data2']) {
                    unset($arr['assessment_data2']);
                }
                if (!$inputData['Data3']) {
                    unset($arr['assessment_data3']);
                }
                if (!$inputData['Data4']) {
                    unset($arr['assessment_data4']);
                }
                if (!$inputData['CountStep']) {
                    unset($arr['coun_step']);
                }
                if ($checkCounselAssessment = $this->Patientmodel->checkCounselAssessment($inputData['PatientId'], $inputData['DoctorId'])) {
                    if ($updatePushCounselAssessment = $this->Patientmodel->updatePushCounselAssessment($arr, $inputData['PatientId'], $inputData['DoctorId'])) {
                        $result['status'] = "Success";
                        $result['Success'] = "TRUE";
                        $result['Value'] = "100";
                        $result['Message'] = 'Patient Counsel Assessment updated successfully';
                        die(json_encode($result));
                    } else {
                        $result['status'] = "Success";
                        $result['Success'] = "TRUE";
                        $result['Value'] = "100";
                        $result['Message'] = "Nothing for update!";
                        die(json_encode($result));
                    }
                } else {
                    $result['status'] = "Failed";
                    $result['Success'] = "False";
                    $result['Value'] = "100";
                    $result['Message'] = "Record not found in CounselAssessment table!";
                    die(json_encode($result));
                }
            } else {
                echo json_encode(array('status' => 'Failed', 'Success' => "FALSE", 'Message' => 'wrong key', 'Result' => array()));
                exit;
            }
        } else {
            echo json_encode(array('status' => 'Failed', 'Success' => "FALSE", 'Message' => 'Incorrect parameters', 'Result' => array()));
            exit;
        }
    }

    public function UpdatePatientSession_post()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['DoctorId'] = $this->input->post('DoctorId', TRUE);
            $inputData['PatientId'] = $this->input->post('PatientId', TRUE);
            $inputData['LastSession'] = $this->input->post('LastSession', TRUE);
            $inputData['LastSessionDate'] = $this->input->post('LastSessionDate', TRUE);
            $inputData['NextSessionDate'] = $this->input->post('NextSessionDate', TRUE);
            $inputData['Session1_Data'] = $this->input->post('Session1_Data', TRUE);
            $inputData['Session2_Data'] = $this->input->post('Session2_Data', TRUE);
            $inputData['Session3_Data'] = $this->input->post('Session3_Data', TRUE);

            $input_data = json_decode($json, TRUE);
            if (!$inputData['DoctorId'] && isset($input_data['DoctorId'])) {
                $inputData['DoctorId'] = $input_data['DoctorId'];
            }
            if (!$inputData['PatientId'] && isset($input_data['PatientId'])) {
                $inputData['PatientId'] = $input_data['PatientId'];
            }
            if (!$inputData['LastSession'] && isset($input_data['LastSession'])) {
                $inputData['LastSession'] = $input_data['LastSession'];
            }
            if (!$inputData['LastSessionDate'] && isset($input_data['LastSessionDate'])) {
                $inputData['LastSessionDate'] = $input_data['LastSessionDate'];
            }
            if (!$inputData['NextSessionDate'] && isset($input_data['NextSessionDate'])) {
                $inputData['NextSessionDate'] = $input_data['NextSessionDate'];
            }
            if (!$inputData['Session1_Data'] && isset($input_data['Session1_Data'])) {
                $inputData['Session1_Data'] = $input_data['Session1_Data'];
            }
            if (!$inputData['Session2_Data'] && isset($input_data['Session2_Data'])) {
                $inputData['Session2_Data'] = $input_data['Session2_Data'];
            }
            if (!$inputData['Session3_Data'] && isset($input_data['Session3_Data'])) {
                $inputData['Session3_Data'] = $input_data['Session3_Data'];
            }
            //echo "<pre>";print_r($inputData); die;
            if (!empty($inputData['DoctorId']) && !empty($inputData['PatientId'])) {
                $data = [
                    'count_session' => $inputData['LastSession'],
                    'last_schedule_date' => $inputData['LastSessionDate'],
                    'next_schedule_date' => $inputData['NextSessionDate'],
                    'session1_data' => json_encode($inputData['Session1_Data']),
                    'session2_data' => json_encode($inputData['Session2_Data']),
                    'session3_data' => json_encode($inputData['Session3_Data']),
                ];
                if (empty(($inputData['Session1_Data']))) {
                    unset($data['session1_data']);
                }
                if (empty(($inputData['Session2_Data']))) {
                    unset($data['session2_data']);
                }
                if (empty(($inputData['Session3_Data']))) {
                    unset($data['session3_data']);
                }
               
                if ($pushCounselAssessment = $this->Patientmodel->UpdatePatientSession($data, $inputData)) {
                    $result['status'] = "Success";
                    $result['Success'] = "TRUE";
                    $result['Message'] = 'Patient details updated successfully';
                    die(json_encode($result));
                } else {
                    $result['status'] = "Failed";
                    $result['Success'] = "FALSE";
                    $result['Message'] = 'Please check your Entry.';
                    die(json_encode($result));
                }
            } else {
                echo json_encode(array('status' => "Failed",'Success' => "FALSE", 'Message' => 'wrong key', 'Result' => array()));
                exit;
            }
        } else {
            echo json_encode(array('status' => "Failed",'Success' => "FALSE", 'Message' => 'Incorrect parameters', 'Result' => array()));
            exit;
        }
    }

    public function UpdateNextSessionDate_post()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['DoctorId'] = $this->input->post('DoctorId', TRUE);
            $inputData['PatientId'] = $this->input->post('PatientId', TRUE);
            $inputData['NextSessionDate'] = $this->input->post('NextSessionDate', TRUE);

            $input_data = json_decode($json, TRUE);
            if (!$inputData['DoctorId'] && isset($input_data['DoctorId'])) {
                $inputData['DoctorId'] = $input_data['DoctorId'];
            }
            if (!$inputData['PatientId'] && isset($input_data['PatientId'])) {
                $inputData['PatientId'] = $input_data['PatientId'];
            }
            if (!$inputData['NextSessionDate'] && isset($input_data['NextSessionDate'])) {
                $inputData['NextSessionDate'] = $input_data['NextSessionDate'];
            }
            //echo "<pre>";print_r($inputData); die;
            if (!empty($inputData['DoctorId']) && !empty($inputData['PatientId'])) {
                $data = [
                    'next_schedule_date' => $inputData['NextSessionDate'],
                ];

                if ($pushCounselAssessment = $this->Patientmodel->UpdatePatientSession($data, $inputData)) {
                    $result['status'] = "Success";
                    $result['Success'] = "TRUE";
                    $result['Message'] = 'Patient next session date updated successfully';
                    die(json_encode($result));
                } else {
                    $result['status'] = "Failed";
                    $result['Success'] = "FALSE";
                    $result['Message'] = 'Please check your Entry.';
                    die(json_encode($result));
                }
            } else {
                echo json_encode(array('status' => "Failed", 'Success' => "FALSE", 'Message' => 'wrong key', 'Result' => array()));
                exit;
            }
        } else {
            echo json_encode(array('status' => "Failed", 'Success' => "FALSE", 'Message' => 'Incorrect parameters', 'Result' => array()));
            exit;
        }
    }



    public function TodayAppointmentList_post()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['UserId'] = $this->input->post('UserId', TRUE);
            $input_data = json_decode($json, TRUE);
            if (!$inputData['UserId'] && isset($input_data['UserId'])) {
                $inputData['UserId'] = $input_data['UserId'];
            }

            // print_r($inputData);die;
            if (!empty($inputData['UserId'])) {
                $res = $this->Patientmodel->getTodayAppointmentList($inputData);
                if ($res) {
                    foreach ($res as $key => $val) {
                        $data[$key]['patient_id'] = $val['patient_id'];
                        $data[$key]['patient_name'] = $val['patient_name'];
                        $data[$key]['patient_mobile'] = $val['patient_mobile'];
                        if (trim($val['count_session'])) {
                            $data[$key]['last_session'] = $val['count_session'];
                        } else {
                            $data[$key]['last_session'] = 0;
                        }
                        $data[$key]['last_session_date'] = $val['last_schedule_date'];
                        $data[$key]['next_session_date'] = $val['next_schedule_date'];
                    }
                    $result['status'] = "Success";
                    $result['Success'] = "TRUE";
                    $result['Message'] = '';
                    $result['data'] = $res;
                    die(json_encode($result));
                } else {
                    $result['status'] = "Success";
                    $result['Success'] = "TRUE";
                    $result['Message'] = 'Record not found!';
                    $result['data'] = array();
                    die(json_encode($result));
                }
            } else {

                $result['status'] = "Failed";
                $result['Success'] = "False";
                $result['Message'] = 'Invalid given request!';
                $result['data'] = array();
                die(json_encode($result));
            }
        } else {

            $result['status'] = "Failed";
            $result['Success'] = "False";
            $result['Message'] = 'Invalid request!';
            die(json_encode($result));
        }
    }
    
    public function getPatientList___post()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['UserId'] = $this->input->post('UserId', TRUE);
            $inputData['StartDate'] = $this->input->post('StartDate', TRUE);
            $inputData['EndDate'] = $this->input->post('EndDate', TRUE);
            $input_data = json_decode($json, TRUE);
            if (!$inputData['UserId'] && isset($input_data['UserId'])) {
                $inputData['UserId'] = $input_data['UserId'];
            }
            if (!$inputData['StartDate'] && isset($input_data['StartDate'])) {
                $inputData['StartDate'] = $input_data['StartDate'];
            }
            if (!$inputData['EndDate'] && isset($input_data['EndDate'])) {
                $inputData['EndDate'] = $input_data['EndDate'];
            }
            // print_r($inputData);die;
            if (!empty($inputData['UserId']) && !empty($inputData['StartDate']) && $inputData['EndDate']) {
                $res = $this->Patientmodel->getPatientList($inputData);
                if ($res) {
                    foreach ($res as $key => $val) {
                        $data[$key]['patient_id'] = $val['patient_id'];
                        $data[$key]['patient_name'] = $val['patient_name'];
                        $data[$key]['patient_mobile'] = $val['patient_mobile'];
                        if (trim($val['count_session'])) {
                            $data[$key]['last_session'] = $val['count_session'];
                        } else {
                            $data[$key]['last_session'] = 0;
                        }
                        $data[$key]['last_session_date'] = $val['last_schedule_date'];
                        $data[$key]['next_session_date'] = $val['next_schedule_date'];
                    }
                    $result['status'] = "Success";
                    $result['Success'] = "TRUE";
                    $result['Message'] = '';
                    $result['Result'] = $res;
                    die(json_encode($result));
                } else {
                    $result['status'] = "Failed";
                    $result['Success'] = "False";
                    $result['Message'] = 'Record not found!';
                    die(json_encode($result));
                }
            } elseif (!empty($inputData['UserId']) && empty($inputData['StartDate']) && empty($inputData['EndDate'])) {
                $res = $this->Patientmodel->getAllPatientList($inputData);
                if ($res) {
                    $result['status'] = "Success";
                    $result['Success'] = "TRUE";
                    $result['Message'] = '';
                    $result['Result'] = $res;
                    die(json_encode($result));
                } else {
                    $result['status'] = "Failed";
                    $result['Success'] = "False";
                    $result['Message'] = 'Record not found!';
                    die(json_encode($result));
                }
            }
        }
    }
    
    public function getPatientDetail_post()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['PatientId'] = $this->input->post('PatientId', TRUE);
            $input_data = json_decode($json, TRUE);
            if (!$inputData['PatientId'] && isset($input_data['PatientId'])) {
                $inputData['PatientId'] = $input_data['PatientId'];
            }
            //print_r($inputData);die;
            if (!empty($inputData['PatientId'])) {
                $res = $this->Patientmodel->getPatientDetail($inputData);

                if ($res) {
                    if ($res->patient_status == 1) {
                        //echo '<pre>'; print_r($res); die;
                        $res->assessment_data = json_decode($res->assessment_data, true);
                        $res->assessment_data2 = json_decode($res->assessment_data2, true);
                        $res->assessment_data3 = json_decode($res->assessment_data3, true);
                        $res->assessment_data4 = json_decode($res->assessment_data4, true);
                        $res->data = json_decode($res->data, true);
                        if (!$res->assessment_data) {
                            $res->assessment_data = [];
                        }
                        if (!$res->assessment_data2) {
                            $res->assessment_data2 = [];
                        }
                        if (!$res->assessment_data3) {
                            $res->assessment_data3 = [];
                        }
                        if (!$res->assessment_data4) {
                            $res->assessment_data4 = [];
                        }
                        if (!$res->data) {
                            $res->data = [];
                        }
                        if (trim($res->count_session)) {
                            $res->last_session = $res->count_session;
                        } else {
                            $res->last_session = 0;
                        }
                        $res->last_session_date = $res->last_schedule_date;
                        $res->next_session_date = $res->next_schedule_date;
                        $res->alternative_number = $res->alternative_number;
                        $res->session1_data = json_decode($res->session1_data, true);
                        $res->session2_data = json_decode($res->session2_data, true);
                        $res->session3_data = json_decode($res->session3_data, true);
                        unset($res->next_schedule_date);
                        unset($res->last_schedule_date);
                        unset($res->last_session);
                        $result['status'] = "Success";
                        $result['Success'] = "TRUE";
                        $result['Message'] = '';
                        $result['Result'] = $res;
                        die(json_encode($result));
                    } else {
                        $result['status'] = "Failed";
                        $result['Success'] = "False";
                        $result['Message'] = 'Otp is not verified, verified first!';
                        die(json_encode($result));
                    }
                } else {
                    $result['status'] = "Failed";
                    $result['Success'] = "False";
                    $result['Message'] = 'Record not found!';
                    die(json_encode($result));
                }
            }
        }
    }
    
    public function UpdatePatientDetails_old_post()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['DoctorId'] = $this->input->post('DoctorId', TRUE);
            $inputData['PatientId'] = $this->input->post('PatientId', TRUE);
            $inputData['Name'] = $this->input->post('Name', TRUE);
            $inputData['Gender'] = $this->input->post('Gender', TRUE);
            $inputData['AlternateMobile'] = $this->input->post('AlternateMobile', TRUE);
            $inputData['Data'] = $this->input->post('Data', TRUE);
            $inputData['Age'] = $this->input->post('Age', TRUE);

            $input_data = json_decode($json, TRUE);
            if (!$inputData['DoctorId'] && isset($input_data['DoctorId'])) {
                $inputData['DoctorId'] = $input_data['DoctorId'];
            }
            if (!$inputData['PatientId'] && isset($input_data['PatientId'])) {
                $inputData['PatientId'] = $input_data['PatientId'];
            }
            if (!$inputData['Name'] && isset($input_data['Name'])) {
                $inputData['Name'] = $input_data['Name'];
            }
            if (!$inputData['Gender'] && isset($input_data['Gender'])) {
                $inputData['Gender'] = $input_data['Gender'];
            }
            if (!$inputData['AlternateMobile'] && isset($input_data['AlternateMobile'])) {
                $inputData['AlternateMobile'] = $input_data['AlternateMobile'];
            }
            if (!$inputData['Data'] && isset($input_data['Data'])) {
                $inputData['Data'] = $input_data['Data'];
            }
            if (!$inputData['Age'] && isset($input_data['Age'])) {
                $inputData['Age'] = $input_data['Age'];
            }
            //echo "<pre>";print_r($inputData); die;
            if (!empty($inputData['DoctorId']) && !empty($inputData['PatientId'])) {
                $data = [
                    'patient_name' => $inputData['Name'],
                    'gender' => $inputData['Gender'],
                    'patient_age' => $inputData['Age'],
                    'alternative_number' => $inputData['AlternateMobile'],
                    'data' => json_encode($inputData['Data']),
                ];

                if ($pushCounselAssessment = $this->Patientmodel->UpdatePatientSession($data, $inputData)) {
                    $result['status'] = "Success";
                    $result['Success'] = "TRUE";
                    $result['Message'] = 'Patient details updated successfully';
                    die(json_encode($result));
                } else {
                    $result['status'] = "Failed";
                    $result['Success'] = "FALSE";
                    $result['Message'] = 'Please check your Entry.';
                    die(json_encode($result));
                }
            } else {
                echo json_encode(array('status' => "Success",'Success' => "FALSE", 'Message' => 'wrong key', 'Result' => array()));
                exit;
            }
        } else {
            echo json_encode(array('status' => "Failed",'Success' => "FALSE", 'Message' => 'Incorrect parameters', 'Result' => array()));
            exit;
        }
    }
    
    
     
    public function fndtProductItems_post()
	{

	    $patientid=$this->post('PatientId');
        
	    $sql="select smoke_category,smoke_items from ecom_patients where patient_id=".$patientid;
	    $query=$this->db->query($sql);
	    $data=$query->result_array();
	    $newdata=array();
	    foreach($data as $item) {
	        $newdata['smoke_category']=$item['smoke_category'];
	        $values=$item['smoke_items'];
	        $people= json_decode($values, true);
            $count= count($people);
	        $people=str_replace("[","",$people);
	        $people=str_replace("]","",$people);
	        $array = explode(',', $people);
            $trimmed_array = array_map('trim', $array);
	        $newdata['smoke_items']=$trimmed_array;
	    }
	    
	    $status = parent::HTTP_OK;
        $response = ['status' => 'Success', 'data' => $newdata];
        $this->response($response, $status);
	}
	
	public function pushCounselAssessment_post()
	{

	    //print_r($_POST);
	    $data=$this->post('data');
        //$Data1 = $this->post('Data1');

	    $json = json_decode($data, true);

        $patientid=$json['PatientId'];
        $doctorid=$json['DoctorId'];
        $step=$json['CountStep'];
        $Data1=$json['Data1'];
        //$valuelist=json_decode($json['values']);
        $valuelist=$json['values'];


        //$smokecategory=$valuelist->smoke_category;
        //$smokeitems=$valuelist->smoke_items;
        //$smokevalues=$valuelist->smoke_values;
        
        $smokecategory=$valuelist['smoke_category'];
        $smokeitems=$valuelist['smoke_items'];
        $smokevalues=$valuelist['smoke_values'];

        
        $data=$json['data'];
    
        $sql="select t1.*,t2.symbol from ecom_doctors t1,currency t2 where t1.doctor_countryid=t2.id and doctor_id=".$doctorid;
	    $query=$this->db->query($sql);
	    $doctor=$query->result_array();
	    
	    foreach($doctor as $item) {
	        $currency=$item['symbol'];
	    }
	    
        $sql="select * from ecom_doc_counselings where coun_step=".$step." and patient_id=".$patientid;
	    $query=$this->db->query($sql);
	    $coun=$query->result_array();
	    
	    if($coun) {
	        
	        $counid=$coun[0]['coun_id'];
            
            if(isset($Data1)) {
	            $sql="update ecom_doc_counselings set coun_date=curdate(),coun_step='".$step."',value=0 where coun_id=".$counid;
    	        $query=$this->db->query($sql);
    	        
    	        $sql="insert into ecom_doc_counselings_data(coun_id,data) values(".$counid.",".$this->db->escape(json_encode($Data1)).")";
    	        $this->db->query($sql);
	        } else {
	            $sql="update ecom_doc_counselings set coun_date=curdate(),coun_step='".$step."',value=0 where coun_id=".$counid;
    	        $query=$this->db->query($sql);
	        }
    	    
    	    if(isset($smokeitems)) {
    	        //$sql="delete from ecom_doc_counselings_items where coun_id=".$counid;
    	        //$query=$this->db->query($sql);
    	    }
    	    
    	    if(isset($data)) {
    	        //$sql="delete from ecom_doc_counselings_questions where coun_id=".$counid;
    	        //$query=$this->db->query($sql);
    	    }
    	    
    	    $sql="select IFNULL(max(count),0)+1 as nextcount from ecom_doc_counselings_items where coun_id=".$counid;
    	    $count=$this->db->query($sql);
    	    $count=$count->result_array();
    	    
    	    foreach($count as $item) {
    	        $nextcount=$item['nextcount'];
    	    }
            
            $total=0;
            for ($i = 0; $i < count($smokeitems); $i++)  {
                $sum=0;
    	        $sum=$smokevalues[$i]['consumption']*($smokevalues[$i]['year']+($smokevalues[$i]['month']/12))*365*$smokevalues[$i]['cost'];
                $sql="insert into ecom_doc_counselings_items(coun_id,count,item,year,month,consumption,cost,total) values(".$counid.",".$nextcount.",'".$smokeitems[$i]."','".$smokevalues[$i]['year']."','".$smokevalues[$i]['month']."','".$smokevalues[$i]['consumption']."','".$smokevalues[$i]['cost']."',".$sum.")";
    	        $query=$this->db->query($sql);
    	        $total=$total+($smokevalues[$i]['consumption']*($smokevalues[$i]['year']+($smokevalues[$i]['month']/12))*365*$smokevalues[$i]['cost']);
            }
            
            $totalamount=$total;
            
            if($totalamount>0) {
                $sql="update ecom_doc_counselings set value='".$total."' where coun_id=".$counid;
    	        $query=$this->db->query($sql);
            }
            
            $sql="select IFNULL(max(count),0)+1 as nextcount from ecom_doc_counselings_questions where coun_id=".$counid;
    	    $count=$this->db->query($sql);
    	    $count=$count->result_array();
    	    foreach($count as $item) {
    	        $nextqcount=$item['nextcount'];
    	    }
    	    
    	    for ($i = 0; $i < count($data); $i++)  {
    	        $question=$data[$i]['Question'];
    	        $answer=$data[$i]['Answer'];
    	        $score=$data[$i]['score'];
    	        //$question=mysql_real_escape_string($question);
    	        //$answer=mysql_real_escape_string($answer);
                $sql="insert into ecom_doc_counselings_questions(coun_id,count,number,question,answer,score) values(".$counid.",".$nextqcount.",'".$data[$i]['QuestionId']."',".$this->db->escape($question).",".$this->db->escape($answer).",".$this->db->escape($score).")";
    	        $query=$this->db->query($sql);
            }
            
            $sql="select coun_id,doctor_id,patient_id,coun_date,coun_step,value,assessment_data from ecom_doc_counselings where coun_id=".$counid;
    	    $query=$this->db->query($sql);
    	    $coun=$query->result_array();
    	    
    	    $sql2="select distinct coun_id,count,date(entry_date) as cdate from ecom_doc_counselings_items where coun_id=".$counid;
    	    $query=$this->db->query($sql2);
    	    $itemdonelist=$query->result_array();
    	    //$counseling['assessment_data2']=$itemlist;
    	    
    	    $sql2="select *,'".$currency."' as currency from ecom_doc_counselings_items where coun_id=".$counid;
    	    $query=$this->db->query($sql2);
    	    $itemlist=$query->result_array();
    	    $counseling['assessment_data2']=$itemlist;
    	    
    	    $sql2="select distinct coun_id,count,date(entry_date) as cdate,getTotalScore(coun_id) as totalscore from ecom_doc_counselings_questions where coun_id=".$counid;
    	    $query=$this->db->query($sql2);
    	    $questiondonelist=$query->result_array();
    	    
    	    $sql3="select * from ecom_doc_counselings_questions where coun_id=".$counid;
    	    $query=$this->db->query($sql3);
    	    $questions=$query->result_array();
    	    
    	    $sql4="select * from ecom_doc_counselings_data where coun_id=".$counid;
    	    $query=$this->db->query($sql4);
    	    $datalist=$query->result_array();
            
            $status = parent::HTTP_OK;
            $response = ['status' => 'Success', 'value' => $totalamount, 'counseling' => $coun,'itemlist' =>$itemdonelist, 'items' => $itemlist,'questionlist' => $questiondonelist, 'questions' => $questions, 'datalist' => $datalist, 'CountStep' => $step, 'currency' => $currency];
            $this->response($response, $status);
            
	    } else {

	        $sql="insert into ecom_doc_counselings(doctor_id,patient_id,coun_date,coun_step,value) values(".$doctorid.",".$patientid.",curdate(),'".$step."',0)";
    	    $query=$this->db->query($sql);
    	    $insertId = $this->db->insert_id();
    	    if(isset($Data1)) {
        	    $sql="insert into ecom_doc_counselings_data(coun_id,data) values(".$insertId.",".$this->db->escape(json_encode($Data1)).")";
        	    $this->db->query($sql);
    	    }
    	    
    	    $sql="select IFNULL(max(count),0)+1 as nextcount from ecom_doc_counselings_items where coun_id=".$insertId;
    	    $count=$this->db->query($sql);
    	    $count=$count->result_array();
    	    
    	    foreach($count as $item) {
    	        $nextcount=$item['nextcount'];
    	    }
            
            $total=0;
     
            /*for ($i = 0; $i < count($smokeitems); $i++)  {
                $sum=0;

    	        $sum=$smokevalues[$i]->consumption*($smokevalues[$i]->year+($smokevalues[$i]->month/12))*365*$smokevalues[$i]->cost;
                $sql="insert into ecom_doc_counselings_items(coun_id,count,item,year,month,consumption,cost,total) values(".$insertId.",".$nextcount.",'".$smokeitems[$i]."','".$smokevalues[$i]->year."','".$smokevalues[$i]->month."','".$smokevalues[$i]->consumption."','".$smokevalues[$i]->cost."',".$sum.")";
    	        $query=$this->db->query($sql);
    	        $total=$total+($smokevalues[$i]->consumption*($smokevalues[$i]->year+($smokevalues[$i]->month/12))*365*$smokevalues[$i]->cost);
            }*/
            for ($i = 0; $i < count($smokeitems); $i++)  {
                $sum=0;
    	        $sum=$smokevalues[$i]['consumption']*($smokevalues[$i]['year']+($smokevalues[$i]['month']/12))*365*$smokevalues[$i]['cost'];
                $sql="insert into ecom_doc_counselings_items(coun_id,count,item,year,month,consumption,cost,total) values(".$counid.",".$nextcount.",'".$smokeitems[$i]."','".$smokevalues[$i]['year']."','".$smokevalues[$i]['month']."','".$smokevalues[$i]['consumption']."','".$smokevalues[$i]['cost']."',".$sum.")";
    	        $query=$this->db->query($sql);
    	        $total=$total+($smokevalues[$i]['consumption']*($smokevalues[$i]['year']+($smokevalues[$i]['month']/12))*365*$smokevalues[$i]['cost']);
            }
            
            $totalamount=$total;
            
            if($totalamount>0) {
                $sql="update ecom_doc_counselings set value='".$total."' where coun_id=".$insertId;
    	        $query=$this->db->query($sql);
            }
            
            $sql="select IFNULL(max(count),0)+1 as nextcount from ecom_doc_counselings_questions where coun_id=".$insertId;
    	    $count=$this->db->query($sql);
    	    $count=$count->result_array();
    	    
    	    foreach($count as $item) {
    	        $nextqcount=$item['nextcount'];
    	    }
    	    
    	    for ($i = 0; $i < count($data); $i++)  {
    	        $question=$data[$i]['Question'];
    	        $answer=$data[$i]['Answer'];
    	        $score=$data[$i]['score'];
    	        //$question=mysql_real_escape_string($question);
    	        //$answer=mysql_real_escape_string($answer);
                $sql="insert into ecom_doc_counselings_questions(coun_id,count,number,question,answer,score) values(".$insertId.",".$nextqcount.",'".$data[$i]['QuestionId']."',".$this->db->escape($question).",".$this->db->escape($answer).",".$this->db->escape($score).")";
    	        $query=$this->db->query($sql);
            }
            
            $sql="select coun_id,doctor_id,patient_id,coun_date,coun_step,value,assessment_data from ecom_doc_counselings where coun_id=".$insertId;
    	    $query=$this->db->query($sql);
    	    $coun=$query->result_array();
    	    
    	    $sql2="select distinct coun_id,count,date(entry_date) as cdate from ecom_doc_counselings_items where coun_id=".$insertId;
    	    $query=$this->db->query($sql2);
    	    $itemdonelist=$query->result_array();
    	    
    	    $sql2="select *,'".$currency."' as currency from ecom_doc_counselings_items where coun_id=".$insertId;
    	    $query=$this->db->query($sql2);
    	    $itemlist=$query->result_array();
    	    $coun[0]['assessment_data2']=$itemlist;
    	    
    	    $sql2="select distinct coun_id,count,date(entry_date) as cdate,getTotalScore(coun_id) as totalscore from ecom_doc_counselings_questions where coun_id=".$insertId;
    	    $query=$this->db->query($sql2);
    	    $questiondonelist=$query->result_array();
    	    
    	    $sql3="select * from ecom_doc_counselings_questions where coun_id=".$insertId;
    	    $query=$this->db->query($sql3);
    	    $questions=$query->result_array();
    	    
    	    $sql4="select * from ecom_doc_counselings_data where coun_id=".$insertId;
    	    $query=$this->db->query($sql4);
    	    $datalist=$query->result_array();
            
            $status = parent::HTTP_OK;
            $response = ['status' => 'Success', 'value' => $totalamount, 'counseling' => $coun,'itemlist' =>$itemdonelist, 'items' => $itemlist,'questionlist' => $questiondonelist, 'questions' => $questions, 'datalist' => $datalist, 'CountStep' => $step, 'currency' => $currency];
            $this->response($response, $status);
	    }
        

	}
	
	public function updatePushCounselAssessment_post()
	{

	    
	    $data=$this->post('data');
        $Data1 = $this->post('Data1');
	    $json = json_decode($data, true);
        
        $counid=$json['CounId'];
        $patientid=$json['PatientId'];
        $doctorid=$json['DoctorId'];
        $step=$json['CountStep'];
        $Data1=$json['Data1'];
        $valuelist=json_decode($json['values']);
        $smokecategory=$valuelist->smoke_category;
        $smokeitems=$valuelist->smoke_items;
        $smokevalues=$valuelist->smoke_values;
        
        
        $data=$json['data'];
        
        $sql="select * from ecom_doc_counselings where coun_step=".$step." and patient_id=".$patientid;
	    $query=$this->db->query($sql);
	    $coun=$query->result_array();
	    
	    if(!$coun) {
            
            $status = parent::HTTP_OK;
            $response = ['status' => 'Failed', 'message' => 'No such Counseling data for this patient with Step:'.$step];
            $this->response($response, $status);
            
	    } else {
	        
	        if(isset($Data1)) {
	            $sql="update ecom_doc_counselings set coun_date=curdate(),coun_step='".$step."',value=0,assessment_data=".$this->db->escape(json_encode($Data1))." where coun_id=".$counid;
    	        $query=$this->db->query($sql);
	        } else {
	            $sql="update ecom_doc_counselings set coun_date=curdate(),coun_step='".$step."',value=0 where coun_id=".$counid;
    	        $query=$this->db->query($sql);
	        }
    	    
    	    if(isset($smokeitems)) {
    	        $sql="delete from ecom_doc_counselings_items where coun_id=".$counid;
    	        $query=$this->db->query($sql);
    	    }
    	    
    	    if(isset($data)) {
    	        $sql="delete from ecom_doc_counselings_questions where coun_id=".$counid;
    	        $query=$this->db->query($sql);
    	    }
            
            $total=0;
            for ($i = 0; $i < count($smokeitems); $i++)  {
                $sum=0;
    	        $sum=$smokevalues[$i]->consumption*$smokevalues[$i]->age*365*$smokevalues[$i]->cost;
                $sql="insert into ecom_doc_counselings_items(coun_id,item,age,consumption,cost,total) values(".$counid.",'".$smokeitems[$i]."','".$smokevalues[$i]->age."','".$smokevalues[$i]->consumption."','".$smokevalues[$i]->cost."',".$sum.")";
    	        $query=$this->db->query($sql);
    	        $total=$total+($smokevalues[$i]->consumption*$smokevalues[$i]->age*365*$smokevalues[$i]->cost);
            }
            
            $totalamount=$total;
            
            if($totalamount>0) {
                $sql="update ecom_doc_counselings set value='".$total."' where coun_id=".$counid;
    	        $query=$this->db->query($sql);
            }
    	    
    	    for ($i = 0; $i < count($data); $i++)  {
    	        $question=$data[$i]['Question'];
    	        $answer=$data[$i]['Answer'];
    	        //$question=mysql_real_escape_string($question);
    	        //$answer=mysql_real_escape_string($answer);
                $sql="insert into ecom_doc_counselings_questions(coun_id,number,question,answer) values(".$counid.",'".$data[$i]['QuestionId']."',".$this->db->escape($question).",".$this->db->escape($answer).")";
    	        $query=$this->db->query($sql);
            }
            
            $sql="select coun_id,doctor_id,patient_id,coun_date,coun_step,value,assessment_data from ecom_doc_counselings where coun_id=".$counid;
    	    $query=$this->db->query($sql);
    	    $coun=$query->result_array();
    	    
    	    $sql2="select * from ecom_doc_counselings_items where coun_id=".$counid;
    	    $query=$this->db->query($sql2);
    	    $itemlist=$query->result_array();
    	    $counseling['assessment_data2']=$itemlist;
    	    
    	    $sql3="select * from ecom_doc_counselings_questions where coun_id=".$counid;
    	    $query=$this->db->query($sql3);
    	    $questions=$query->result_array();
            
            $status = parent::HTTP_OK;
            $response = ['status' => 'Success', 'value' => $totalamount, 'counseling' => $coun, 'items' => $itemlist, 'questions' => $questions];
            $this->response($response, $status);
	    }
        
        

	}
	
	public function getCounselAssessmentData_post()
	{

	    
	    $patientid=$this->post('PatientId');
	    $step=$this->post('CountStep');
	    
	    
        
        $sql="select * from ecom_doc_counselings where coun_step=".$step." and patient_id=".$patientid;
	    $query=$this->db->query($sql);
	    $coun=$query->result_array();
	    
	    if(!$coun) {
            
            $status = parent::HTTP_OK;
            $response = ['status' => 'Failed', 'message' => 'No such Counseling data for this patient with Step:'.$step];
            $this->response($response, $status);
            
	    } else {
	        
	        foreach($coun as $item) {
	            $counid=$item['coun_id'];
	            $totalamount=$item['value'];
	        }
	        
	        $sql="select t1.*,t2.symbol from ecom_doctors t1,currency t2 where t1.doctor_countryid=t2.id and doctor_id=".$item['doctor_id'];
    	    $query=$this->db->query($sql);
    	    $doctor=$query->result_array();
    	    
    	    foreach($doctor as $item) {
    	        $currency=$item['symbol'];
    	    }
            
            $sql="select coun_id,doctor_id,patient_id,coun_date,coun_step,value from ecom_doc_counselings where coun_id=".$counid;
    	    $query=$this->db->query($sql);
    	    $coun=$query->result_array();
    	    
    	    $sql2="select distinct coun_id,count,date(entry_date) as cdate from ecom_doc_counselings_items where coun_id=".$counid;
    	    $query=$this->db->query($sql2);
    	    $itemdonelist=$query->result_array();
    	    
    	    $sql2="select *,'".$currency."' as currency from ecom_doc_counselings_items where coun_id=".$counid;
    	    $query=$this->db->query($sql2);
    	    $itemlist=$query->result_array();
    	    $coun[0]['assessment_data2']=$itemlist;
    	    
    	    $sql2="select distinct coun_id,count,date(entry_date) as cdate from ecom_doc_counselings_questions where coun_id=".$counid;
    	    $query=$this->db->query($sql2);
    	    $questiondonelist=$query->result_array();
    	    
    	    $sql3="select * from ecom_doc_counselings_questions where coun_id=".$counid;
    	    $query=$this->db->query($sql3);
    	    $questions=$query->result_array();
    	    
    	    $sql4="select * from ecom_doc_counselings_data where coun_id=".$counid;
    	    $query=$this->db->query($sql4);
    	    $datalist=$query->result_array();
            
            $status = parent::HTTP_OK;
            $response = ['status' => 'Success', 'value' => $totalamount, 'counseling' => $coun, 'itemlist' =>$itemdonelist, 'items' => $itemlist,'questionlist' => $questiondonelist, 'questions' => $questions, 'datalist' => $datalist, 'currency' => $currency];
            $this->response($response, $status);
	    }
        
        

	}
	
	
    
}