<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//define('KEY','AAAAlwr9C0g:APA91bGDvCkePC2E__03Jm6U3Jz8046DyZN4I-NlwisBhxT0GgpesJ1ZXLvdz5EqeR58Q8f0_Af-tpclYU7X1Eo4FHm34nzXUnrifgLoeFDMtjH77FoxvkHICFWQFt04Az5riiDtIalW');
require_once(APPPATH . '../spreadsheets/autoload.php'); // For CodeIgniter
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Register extends CI_Controller {
	
	function __construct()
	{
		parent::__construct();
		date_default_timezone_set("Asia/Kolkata");
		$this->load->library(array('form_validation'));
		$this->load->library('session');
		//echo 'hii';exit;
		$this->load->helper('url','form','HTML');
		
		$this->is_logged_in();
		$this->load->model('admin/registermodel');
		$this->db->query('SET SESSION sql_mode =
                  REPLACE(REPLACE(REPLACE(
                  @@sql_mode,
                  "ONLY_FULL_GROUP_BY,", ""),
                  ",ONLY_FULL_GROUP_BY", ""),
                  "ONLY_FULL_GROUP_BY", "")');
        $this->bharosa_base_path = '/home/medconnectorg/public_html/bharosa/assets/admin/';
	}

public function is_logged_in(){
	$is_logged = $this->session->userdata('user_info');
	if(!empty($is_logged)){
        $is_logged_in = $is_logged['is_logged_in'];
    	if(!isset($is_logged_in) || $is_logged_in != TRUE){
    		redirect('admin/login', 'refresh');
    	}
	}else{
	    redirect('admin/login', 'refresh');
	}
}

/*required_functions*/
public function session_data() {
    $session = $this->session->userdata('user_info');
    
    //print_r($session);exit;
    
    if (!$session) {
        return null; // Or handle as needed if session is not set
    }

    if ($this->session->userdata('login_type') == 'sub_admin') {
        // For sub_admin, fetch main_data_id from sub_admins table
        $this->db->select('main_data_id');
        $this->db->from('sub_admins');
        $this->db->where('id', $session['user_id']);
        $query = $this->db->get();
        $row = $query->row_array();

        return isset($row['main_data_id']) ? $row['main_data_id'] : null;
    }

    // For admin, return their own user_id
    return $session['user_id'];
}
/*required_functions*/

/*normal_notification*/
public function sendNotification($playerId, $title, $message) {
    $appId = 'cebaa375-de95-4fb8-9403-71089f304ffe'; // Replace with your OneSignal App ID
    $apiKey = 'os_v2_app_z25kg5o6svh3rfadoeej6mcp7y6ua2qygeoewimkum6gid4guz7bejfb7bpi3sfhqunafvh5tipyfwkrs77thwvap5q5bbkknd4jfdy'; // Replace with your OneSignal REST API Key
    
    $curl = curl_init();

    // Common notification data
    $notificationData = [
        "app_id" => $appId,
        "headings" => ["en" => $title], // Notification title
        "contents" => ["en" => $message], // Notification content
        "small_icon" => "kaam_hai_na_logo", // Android Small Icon (Place inside res/drawable)
    ];

    // 1️⃣ **Sending to ALL Users**
    if ($playerId === 'all') {
        //$notificationData["included_segments"] = ["All"]; // Send to all users
        $notificationData["filters"] = [
            ["field" => "tag", "key" => "user_type", "relation" => "=", "value" => $userType]
        ];
    
    // 2️⃣ **Sending to a Filtered User Type (e.g., Only Employees or Only Users)**
    } /*elseif ($userType !== null) {
        
    
    // 3️⃣ **Sending to Multiple Specific Users**
    }*/ elseif (is_array($playerId)) {
        $notificationData["include_player_ids"] = $playerId; // Send to multiple users
    
    // 4️⃣ **Sending to a Single User**
    } else {
        $notificationData["include_player_ids"] = [$playerId]; // Send to a single user
    }

    curl_setopt_array($curl, [
        CURLOPT_URL => "https://onesignal.com/api/v1/notifications",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($notificationData),
        CURLOPT_HTTPHEADER => [
            "Authorization: Key $apiKey", // API Key in Authorization header
            "Content-Type: application/json"
        ],
        CURLOPT_SSL_VERIFYPEER => false, // Disable SSL verification for debugging
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        return "cURL Error: " . $err;
    } else {
        return $response;
    }
}

public function send_web_notification($player_id, $title, $message, $url = 'https://medrayder.in/hospitals/admin/register/') {
    $content = array(
        "en" => $message
    );
    $heading = array(
        "en" => $title
    );

    $fields = array(
        'app_id' => "cebaa375-de95-4fb8-9403-71089f304ffe", // your OneSignal App ID
        'include_player_ids' => array($player_id),          // pass array of player_ids
        'headings' => $heading,
        'contents' => $content,
        "small_icon" => "app_notification_icon",
        'url' => $url,                                      // optional: open URL when clicked
        'priority' => 10                                     // optional: high priority
    );

    $fields = json_encode($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic os_v2_app_z25kg5o6svh3rfadoeej6mcp7y6ua2qygeoewimkum6gid4guz7bejfb7bpi3sfhqunafvh5tipyfwkrs77thwvap5q5bbkknd4jfdy' // Replace with your OneSignal REST API Key
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}
/*normal_notification*/

/*index*/
public function tele_caller_index(){
    $this->load->view('admin/includes/header');
	$this->load->view('admin/includes/footer');
}
public function index(){
    check_permission(1);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch_rows('users',['delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch_rows('main_data',['delete_status' => 1]);
    $data['pharmacies'] = $this->registermodel->common_fetch_rows('pharmacies',['delete_status' => 1]);
    $data['diagnostics'] = $this->registermodel->common_fetch_rows('diagnostics',['delete_status' => 1]);
    $data['lab_tests'] = $this->registermodel->common_fetch_rows('lab_tests',['delete_status' => 1]);
    $data['online_doctors'] = $this->registermodel->common_fetch_rows('online_doctors',['delete_status' => 1]);
    //echo $this->db->last_query();exit;
	$this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/home',$data);
	$this->load->view('admin/includes/footer');
}
public function save_admin_player_id(){
    $input = json_decode(file_get_contents('php://input'), true);
    $sess_data = $this->session_data();
    $playerId = $input['player_id'] ?? '';
    $adminId  = $sess_data;

    if (!$playerId || !$adminId) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['status' => false, 'msg' => 'Missing data']));
    }

    $exists = $this->db->get_where('main_data', ['id' => $adminId])->row();

    if ($exists) {
        $this->db->update('main_data', ['web_player_id' => $playerId], ['id' => $adminId]);
    } 

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(['status' => true, 'msg' => 'Player ID saved']));
}
/*index*/

/*users*/
public function users(){
    check_permission(9);
    $search = '';
    $data['total_records'] = $this->registermodel->get_users_count($search);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/users',$data);
	$this->load->view('admin/includes/footer');
}
public function get_users(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_users($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_users_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_user_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('users',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function subscribed_users(){
    check_permission(9);
    $search = '';
    $data['total_records']  = $this->registermodel->get_subscribed_users_count($search);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/users',$data);
	$this->load->view('admin/includes/footer');
}
public function get_subscribed_users(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_subscribed_users($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_subscribed_users_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function unsubscribed_users(){
    check_permission(9);
    $search = '';
    $data['total_records']  = $this->registermodel->get_unsubscribed_users_count($search);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/users',$data);
	$this->load->view('admin/includes/footer');
}
public function get_unsubscribed_users(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_unsubscribed_users($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_unsubscribed_users_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*users*/

/*sales_hierarchy*/

/*state_heads*/
public function state_heads(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/state_heads');
	$this->load->view('admin/includes/footer');
}
public function get_state_heads(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_state_heads($limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_state_heads_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_state_head_status(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('state_heads',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_state_head(){
    check_permission(2);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_state_head',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_state_head(){ 
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $state_id = $this->input->post('state_id');
    $mobile = $this->input->post('mobile');
    $email = $this->input->post('email');
    $check_state = $this->registermodel->common_fetch('state_heads',['state_id' => $state_id,'delete_status' => 1]);
    $check_mobile = $this->registermodel->common_fetch('state_heads',['mobile' => $mobile,'delete_status' => 1]);
    $check_email = $this->registermodel->common_fetch('state_heads',['email' => $email,'delete_status' => 1]);
    if(!empty($check_state)||!empty($check_mobile)||!empty($check_email)){
        echo json_encode(['success' => false, 'message' => 'state,mobile or email inserted already']);
        return;
    }else{
        $config['upload_path']			= $this->bharosa_base_path . 'state_heads/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/state_heads/'.$uploadData['file_name'];
    
        $data = [
            'name'              => $this->input->post('name'),
            'mobile'            => $this->input->post('mobile'),
            'email'             => $this->input->post('email'),
            'image'             => $photo,
            'state_id'          => $this->input->post('state_id'),
            'gender'            => $this->input->post('gender'),
            'dob'               => $this->input->post('dob'),
            'occupation'        => $this->input->post('occupation'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert = $this->registermodel->common_insert('state_heads',$data);
        
        $unq = sprintf('%04d',$insert);
        
        $update = $this->registermodel->common_update('state_heads',['unique_id' => "SH_$unq"],['id' => $insert]);

        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_state_head($id){
    check_permission(3);
   $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
   $data['state_head'] = $this->registermodel->common_fetch('state_heads',['id' => base64_decode($id)]);
   $this->load->view('admin/includes/header');
   $this->load->view('admin/super_admin/edit_state_head',$data);
   $this->load->view('admin/includes/footer');
}
public function edit_state_head_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'state_heads/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/state_heads/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$data = [
	    'name'              => $this->input->post('name'),
        'mobile'            => $this->input->post('mobile'),
        'email'             => $this->input->post('email'),
        'image'             => $image,
        'state_id'          => $this->input->post('state_id'),
        'gender'            => $this->input->post('gender'),
        'dob'               => $this->input->post('dob'),
        'occupation'        => $this->input->post('occupation'),
	    'modified_on'    => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $mobile = $this->input->post('mobile');
    $check_with_same_mobile = $this->registermodel->common_fetch('state_heads', ['mobile' => $mobile,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_mobile) {
        echo json_encode(['success' => false, 'message' => 'mobile is added already']);
        return;
    }
    
    $email = $this->input->post('email');
    $check_with_same_email = $this->registermodel->common_fetch('state_heads', ['email' => $email,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_email) {
        echo json_encode(['success' => false, 'message' => 'email is added already']);
        return;
    }
    
    $update 	= $this->registermodel->common_update('state_heads',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_state_head(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('state_heads',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('state_heads', ['delete_status' => 0], ['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*state_heads*/

/*zonal_heads*/
public function zonal_heads(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/zonal_heads');
	$this->load->view('admin/includes/footer');
}
public function get_zonal_heads(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_zonal_heads($limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_zonal_heads_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_zonal_head_status(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('zonal_heads',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_zonal_head(){
    check_permission(2);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_zonal_head',$data);
	$this->load->view('admin/includes/footer');
}
public function get_state_heads_by_state(){
    $state_id = $this->input->post('state_id');
    $districts = $this->registermodel->common_fetch_asc('state_heads', [
        'state_id' => $state_id,
        'status' => 1,
        'delete_status' => 1
    ]);
    echo json_encode($districts);
}
public function insert_zonal_head(){ 
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $mobile = $this->input->post('mobile');
    $email = $this->input->post('email');
    $check_mobile = $this->registermodel->common_fetch('zonal_heads',['mobile' => $mobile,'delete_status' => 1]);
    $check_email = $this->registermodel->common_fetch('state_heads',['email' => $email,'delete_status' => 1]);
    if(!empty($check_mobile)||!empty($check_email)){
        echo json_encode(['success' => false, 'message' => 'mobile or email inserted already']);
        return;
    }else{
        $config['upload_path']			= $this->bharosa_base_path . 'zonal_heads/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/zonal_heads/'.$uploadData['file_name'];
    
        $data = [
            'name'              => $this->input->post('name'),
            'mobile'            => $this->input->post('mobile'),
            'email'             => $this->input->post('email'),
            'image'             => $photo,
            'state_id'          => $this->input->post('state_id'),
            'state_head_id'     => $this->input->post('state_head_id'),
            'gender'            => $this->input->post('gender'),
            'dob'               => $this->input->post('dob'),
            'occupation'        => $this->input->post('occupation'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert = $this->registermodel->common_insert('zonal_heads',$data);
        
        $unq = sprintf('%04d',$insert);
        
        $update = $this->registermodel->common_update('zonal_heads',['unique_id' => "ZH_$unq"],['id' => $insert]);

        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_zonal_head($id){
    check_permission(3);
   $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
   $data['zonal_head'] = $this->registermodel->common_fetch('zonal_heads',['id' => base64_decode($id)]);
   $this->load->view('admin/includes/header');
   $this->load->view('admin/super_admin/edit_zonal_head',$data);
   $this->load->view('admin/includes/footer');
}
public function edit_zonal_head_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'zonal_heads/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/zonal_heads/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$data = [
	    'name'              => $this->input->post('name'),
        'mobile'            => $this->input->post('mobile'),
        'email'             => $this->input->post('email'),
        'image'             => $image,
        'state_id'          => $this->input->post('state_id'),
        'state_head_id'     => $this->input->post('state_head_id'),
        'gender'            => $this->input->post('gender'),
        'dob'               => $this->input->post('dob'),
        'occupation'        => $this->input->post('occupation'),
	    'modified_on'    => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $mobile = $this->input->post('mobile');
    $check_with_same_mobile = $this->registermodel->common_fetch('zonal_heads', ['mobile' => $mobile,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_mobile) {
        echo json_encode(['success' => false, 'message' => 'mobile is added already']);
        return;
    }
    
    $email = $this->input->post('email');
    $check_with_same_email = $this->registermodel->common_fetch('zonal_heads', ['email' => $email,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_email) {
        echo json_encode(['success' => false, 'message' => 'email is added already']);
        return;
    }
    
    $update 	= $this->registermodel->common_update('zonal_heads',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_zonal_head(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('zonal_heads',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('zonal_heads', ['delete_status' => 0], ['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*zonal_heads*/

/*territory_heads*/
public function territory_heads(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/territory_heads');
	$this->load->view('admin/includes/footer');
}
public function get_territory_heads(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_territory_heads($limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_territory_heads_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_territory_head_status(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('territory_heads',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_territory_head(){
    check_permission(2);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_territory_head',$data);
	$this->load->view('admin/includes/footer');
}
public function get_zonal_heads_by_state(){
    $state_id = $this->input->post('state_id');
    $state_head_id = $this->input->post('state_head_id');
    $cities = $this->registermodel->common_fetch_asc('zonal_heads', [
        'state_id' => $state_id,
        'state_head_id' => $state_head_id,
        'status' => 1,
        'delete_status' => 1
    ]);
    echo json_encode($cities);
}
public function insert_territory_head(){ 
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $mobile = $this->input->post('mobile');
    $email = $this->input->post('email');
    $check_mobile = $this->registermodel->common_fetch('territory_heads',['mobile' => $mobile,'delete_status' => 1]);
    $check_email = $this->registermodel->common_fetch('territory_heads',['email' => $email,'delete_status' => 1]);
    if(!empty($check_mobile)||!empty($check_email)){
        echo json_encode(['success' => false, 'message' => 'mobile or email inserted already']);
        return;
    }else{
        $config['upload_path']			= $this->bharosa_base_path . 'territory_heads/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/territory_heads/'.$uploadData['file_name'];
        $dis = implode(',',$this->input->post('district_id'));
        $data = [
            'name'              => $this->input->post('name'),
            'mobile'            => $this->input->post('mobile'),
            'email'             => $this->input->post('email'),
            'image'             => $photo,
            'state_id'          => $this->input->post('state_id'),
            'state_head_id'     => $this->input->post('state_head_id'),
            'zonal_head_id'     => $this->input->post('zonal_head_id'),
            'district_id'       => $dis,
            'gender'            => $this->input->post('gender'),
            'dob'               => $this->input->post('dob'),
            'occupation'        => $this->input->post('occupation'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert = $this->registermodel->common_insert('territory_heads',$data);
        
        $unq = sprintf('%04d',$insert);
        
        $update = $this->registermodel->common_update('territory_heads',['unique_id' => "TH_$unq"],['id' => $insert]);

        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_territory_head($id){
    check_permission(3);
   $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
   $data['territory_head'] = $this->registermodel->common_fetch('territory_heads',['id' => base64_decode($id)]);
   $this->load->view('admin/includes/header');
   $this->load->view('admin/super_admin/edit_territory_head',$data);
   $this->load->view('admin/includes/footer');
}
public function edit_territory_head_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'territory_heads/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/territory_heads/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$dis = implode(',',$this->input->post('district_id'));
	$data = [
	    'name'              => $this->input->post('name'),
        'mobile'            => $this->input->post('mobile'),
        'email'             => $this->input->post('email'),
        'image'             => $image,
        'state_id'          => $this->input->post('state_id'),
        'state_head_id'     => $this->input->post('state_head_id'),
        'zonal_head_id'     => $this->input->post('zonal_head_id'),
        'district_id'       => $dis,
        'gender'            => $this->input->post('gender'),
        'dob'               => $this->input->post('dob'),
        'occupation'        => $this->input->post('occupation'),
	    'modified_on'    => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $mobile = $this->input->post('mobile');
    $check_with_same_mobile = $this->registermodel->common_fetch('territory_heads', ['mobile' => $mobile,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_mobile) {
        echo json_encode(['success' => false, 'message' => 'mobile is added already']);
        return;
    }
    
    $email = $this->input->post('email');
    $check_with_same_email = $this->registermodel->common_fetch('territory_heads', ['email' => $email,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_email) {
        echo json_encode(['success' => false, 'message' => 'email is added already']);
        return;
    }
    
    $update 	= $this->registermodel->common_update('territory_heads',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_territory_head(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('territory_heads',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('territory_heads', ['delete_status' => 0], ['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*territory_heads*/

/*regional_managers*/
public function regional_managers(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/regional_managers');
	$this->load->view('admin/includes/footer');
}
public function get_regional_managers(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_regional_managers($limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_regional_managers_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_regional_manager_status(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('regional_managers',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_regional_manager(){
    check_permission(2);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_regional_manager',$data);
	$this->load->view('admin/includes/footer');
}
public function get_territory_heads_by_zonal(){
    $state_id = $this->input->post('state_id');
    $state_head_id = $this->input->post('state_head_id');
    $state_head_id = $this->input->post('state_head_id');
    $zonal_head_id = $this->input->post('zonal_head_id');
    
    $cities = $this->registermodel->common_fetch_asc('territory_heads', [
        'state_id' => $state_id,
        'state_head_id' => $state_head_id,
        'zonal_head_id' => $zonal_head_id,
        'status' => 1,
        'delete_status' => 1
    ]);
    echo json_encode($cities);
}
public function get_districts_by_territory(){
    $state_id          = $this->input->post('state_id');
    $state_head_id     = $this->input->post('state_head_id');
    $zonal_head_id     = $this->input->post('zonal_head_id');
    $territory_head_id = $this->input->post('territory_head_id');

    // Fetch the matching territory head
    $territory = $this->registermodel->common_fetch('territory_heads', [
        'state_id'          => $state_id,
        'state_head_id'     => $state_head_id,
        'zonal_head_id'     => $zonal_head_id,
        'id'                => $territory_head_id,
        'status'            => 1,
        'delete_status'     => 1
    ]);

    if (!empty($territory)) {
        $district_ids = explode(',', $territory[0]['district_id']);
        $this->db->where_in('id', $district_ids);
        $this->db->order_by('name', 'ASC');
        $districts = $this->db->get('districts')->result_array();
    } else {
        $districts = [];
    }

    echo json_encode($districts);
}
public function get_mandals_by_districts(){
    $district_id = $this->input->post('district_id');
    
    $cities = $this->registermodel->common_fetch_asc('mandals', [
        'district_id' => $district_id,
        'status' => 1,
        'delete_status' => 1
    ]);
    echo json_encode($cities);
}
public function insert_regional_manager(){ 
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $mobile = $this->input->post('mobile');
    $email = $this->input->post('email');
    $check_mobile = $this->registermodel->common_fetch('regional_managers',['mobile' => $mobile,'delete_status' => 1]);
    $check_email = $this->registermodel->common_fetch('regional_managers',['email' => $email,'delete_status' => 1]);
    if(!empty($check_mobile)||!empty($check_email)){
        echo json_encode(['success' => false, 'message' => 'mobile or email inserted already']);
        return;
    }else{
        $config['upload_path']			= $this->bharosa_base_path . 'regional_managers/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/regional_managers/'.$uploadData['file_name'];
        $man = implode(',',$this->input->post('mandal_id'));
        $data = [
            'name'              => $this->input->post('name'),
            'mobile'            => $this->input->post('mobile'),
            'email'             => $this->input->post('email'),
            'image'             => $photo,
            'state_id'          => $this->input->post('state_id'),
            'state_head_id'     => $this->input->post('state_head_id'),
            'zonal_head_id'     => $this->input->post('zonal_head_id'),
            'territory_head_id' => $this->input->post('territory_head_id'),
            'district_id'       => $this->input->post('district_id'),
            'mandal_id'         => $man,
            'gender'            => $this->input->post('gender'),
            'dob'               => $this->input->post('dob'),
            'occupation'        => $this->input->post('occupation'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert = $this->registermodel->common_insert('regional_managers',$data);
        
        $unq = sprintf('%04d',$insert);
        
        $update = $this->registermodel->common_update('regional_managers',['unique_id' => "RM_$unq"],['id' => $insert]);

        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_regional_manager($id){
    check_permission(3);
   $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
   $data['regional_manager'] = $this->registermodel->common_fetch('regional_managers',['id' => base64_decode($id)]);
   $this->load->view('admin/includes/header');
   $this->load->view('admin/super_admin/edit_regional_manager',$data);
   $this->load->view('admin/includes/footer');
}
public function edit_regional_manager_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'regional_managers/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/regional_managers/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$man = implode(',',$this->input->post('mandal_id'));
	$data = [
	    'name'              => $this->input->post('name'),
        'mobile'            => $this->input->post('mobile'),
        'email'             => $this->input->post('email'),
        'image'             => $image,
        'state_id'          => $this->input->post('state_id'),
        'state_head_id'     => $this->input->post('state_head_id'),
        'zonal_head_id'     => $this->input->post('zonal_head_id'),
        'territory_head_id' => $this->input->post('territory_head_id'),
        'district_id'       => $this->input->post('district_id'),
        'mandal_id'         => $man,
        'gender'            => $this->input->post('gender'),
        'dob'               => $this->input->post('dob'),
        'occupation'        => $this->input->post('occupation'),
	    'modified_on'    => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $mobile = $this->input->post('mobile');
    $check_with_same_mobile = $this->registermodel->common_fetch('regional_managers', ['mobile' => $mobile,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_mobile) {
        echo json_encode(['success' => false, 'message' => 'mobile is added already']);
        return;
    }
    
    $email = $this->input->post('email');
    $check_with_same_email = $this->registermodel->common_fetch('regional_managers', ['email' => $email,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_email) {
        echo json_encode(['success' => false, 'message' => 'email is added already']);
        return;
    }
    
    $update 	= $this->registermodel->common_update('regional_managers',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_regional_manager(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('regional_managers',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('regional_managers', ['delete_status' => 0], ['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*regional_managers*/

/*medical_advisors*/
public function medical_advisors(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/medical_advisors');
	$this->load->view('admin/includes/footer');
}
public function get_medical_advisors(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_medical_advisors($limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_medical_advisors_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_medical_advisor_status(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('executives',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_medical_advisor(){
    check_permission(2);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_medical_advisor',$data);
	$this->load->view('admin/includes/footer');
}
public function get_regional_managers_by_territory(){
    $state_id = $this->input->post('state_id');
    $state_head_id = $this->input->post('state_head_id');
    $state_head_id = $this->input->post('state_head_id');
    $zonal_head_id = $this->input->post('zonal_head_id');
    $territory_head_id = $this->input->post('territory_head_id');
    
    $cities = $this->registermodel->common_fetch_asc('regional_managers', [
        'state_id' => $state_id,
        'state_head_id' => $state_head_id,
        'zonal_head_id' => $zonal_head_id,
        'territory_head_id' => $territory_head_id,
        'status' => 1,
        'delete_status' => 1
    ]);
    echo json_encode($cities);
}
public function get_districts_by_regional_manager(){
    $state_id          = $this->input->post('state_id');
    $state_head_id     = $this->input->post('state_head_id');
    $zonal_head_id     = $this->input->post('zonal_head_id');
    $territory_head_id = $this->input->post('territory_head_id');
    $regional_manager_id = $this->input->post('regional_manager_id');

    // Fetch the matching territory head
    $territory = $this->registermodel->common_fetch('regional_managers', [
        'state_id'          => $state_id,
        'state_head_id'     => $state_head_id,
        'zonal_head_id'     => $zonal_head_id,
        'territory_head_id' => $territory_head_id,
        'id'                => $regional_manager_id,
        'status'            => 1,
        'delete_status'     => 1
    ]);

    if (!empty($territory)) {
        $district_ids = explode(',', $territory[0]['district_id']);
        $this->db->where_in('id', $district_ids);
        $this->db->order_by('name', 'ASC');
        $districts = $this->db->get('districts')->result_array();
    } else {
        $districts = [];
    }

    echo json_encode($districts);
}
public function get_villages_by_mandal(){
    $mandal_id = $this->input->post('mandal_id');
    
    $cities = $this->registermodel->common_fetch_asc('villages', [
        'mandal_id' => $mandal_id,
        'status' => 1,
        'delete_status' => 1
    ]);
    echo json_encode($cities);
}
public function insert_medical_advisor(){ 
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $mobile = $this->input->post('mobile');
    $email = $this->input->post('email');
    $check_mobile = $this->registermodel->common_fetch('executives',['mobile' => $mobile,'delete_status' => 1]);
    $check_email = $this->registermodel->common_fetch('executives',['email' => $email,'delete_status' => 1]);
    if(!empty($check_mobile)||!empty($check_email)){
        echo json_encode(['success' => false, 'message' => 'mobile or email inserted already']);
        return;
    }else{
        $config['upload_path']			= $this->bharosa_base_path . 'executives/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/executives/'.$uploadData['file_name'];
        //$vil = implode(',',$this->input->post('village_id'));
        $data = [
            'name'              => $this->input->post('name'),
            'mobile'            => $this->input->post('mobile'),
            'email'             => $this->input->post('email'),
            'image'             => $photo,
            'state_id'          => $this->input->post('state_id'),
            'state_head_id'     => $this->input->post('state_head_id'),
            'zonal_head_id'     => $this->input->post('zonal_head_id'),
            'territory_head_id' => $this->input->post('territory_head_id'),
            'regional_manager_id'=> $this->input->post('regional_manager_id'),
            'district_id'       => $this->input->post('district_id'),
            'mandal_id'         => $this->input->post('mandal_id'),
            'village_id'        => $this->input->post('village_id'),
            'gender'            => $this->input->post('gender'),
            'dob'               => $this->input->post('dob'),
            'occupation'        => $this->input->post('occupation'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert = $this->registermodel->common_insert('executives',$data);
        
        $unq = sprintf('%04d',$insert);
        
        $update = $this->registermodel->common_update('executives',['unique_id' => "MA_$unq"],['id' => $insert]);

        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_medical_advisor($id){
    check_permission(3);
   $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
   $data['medical_advisor'] = $this->registermodel->common_fetch('executives',['id' => base64_decode($id)]);
   $this->load->view('admin/includes/header');
   $this->load->view('admin/super_admin/edit_medical_advisor',$data);
   $this->load->view('admin/includes/footer');
}
public function edit_medical_advisor_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'executives/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/executives/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	//$man = implode(',',$this->input->post('mandal_id'));
	$data = [
	    'name'              => $this->input->post('name'),
        'mobile'            => $this->input->post('mobile'),
        'email'             => $this->input->post('email'),
        'image'             => $image,
        'state_id'          => $this->input->post('state_id'),
        'state_head_id'     => $this->input->post('state_head_id'),
        'zonal_head_id'     => $this->input->post('zonal_head_id'),
        'territory_head_id' => $this->input->post('territory_head_id'),
        'regional_manager_id'=> $this->input->post('regional_manager_id'),
        'district_id'       => $this->input->post('district_id'),
        'mandal_id'         => $this->input->post('mandal_id'),
        'village_id'        => $this->input->post('village_id'),
        'gender'            => $this->input->post('gender'),
        'dob'               => $this->input->post('dob'),
        'occupation'        => $this->input->post('occupation'),
	    'modified_on'    => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $mobile = $this->input->post('mobile');
    $check_with_same_mobile = $this->registermodel->common_fetch('executives', ['mobile' => $mobile,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_mobile) {
        echo json_encode(['success' => false, 'message' => 'mobile is added already']);
        return;
    }
    
    $email = $this->input->post('email');
    $check_with_same_email = $this->registermodel->common_fetch('executives', ['email' => $email,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_email) {
        echo json_encode(['success' => false, 'message' => 'email is added already']);
        return;
    }
    
    $update 	= $this->registermodel->common_update('executives',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_medical_advisor(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('executives',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('executives', ['delete_status' => 0], ['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*medical_advisors*/

/*sales_target*/
public function sales_target(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/sales_target');
	$this->load->view('admin/includes/footer');
}
public function get_sales_target(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_sales_target($limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_sales_target_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function add_sales_target(){
    check_permission(2);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $data['months'] = $this->registermodel->common_fetch_asc('months',[]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_sales_target',$data);
	$this->load->view('admin/includes/footer');
}
// Fetch districts by state
public function get_districts_by_state(){
    $state_id = $this->input->post('state_id');
    $districts = $this->registermodel->common_fetch_asc('districts', [
        'state_id' => $state_id,
        'status' => 1,
        'delete_status' => 1
    ]);
    echo json_encode($districts);
}

// Fetch cities by state + district
public function get_mandals_by_state_district(){
    $state_id = $this->input->post('state_id');
    $district_id = $this->input->post('district_id');
    $cities = $this->registermodel->common_fetch_asc('mandals', [
        'state_id' => $state_id,
        'district_id' => $district_id,
        'status' => 1,
        'delete_status' => 1
    ]);
    echo json_encode($cities);
}

// Fetch regional managers by state + district + mandal
public function get_regional_managers_by_state_district_mandal(){
    $state_id     = $this->input->post('state_id');
    $district_id  = $this->input->post('district_id');
    $mandal_ids   = $this->input->post('mandal_id'); // Should be an array

    $this->db->where('state_id', $state_id);
    $this->db->where('district_id', $district_id);
    $this->db->where('status', 1);
    $this->db->where('delete_status', 1);

    if (!empty($mandal_ids) && is_array($mandal_ids)) {
        $this->db->where_in('mandal_id', $mandal_ids);
    }

    $cities = $this->db->get('regional_managers')->result_array();

    echo json_encode($cities);
}
public function check_existing_target(){
    $state_id = $this->input->post('state_id');
    $district_id = $this->input->post('district_id');
    $mandal_id = $this->input->post('mandal_id');
    $regional_manager_id = $this->input->post('regional_manager_id');
    $month = $this->input->post('month');
    $year = $this->input->post('year');

    $exists = $this->db->get_where('regional_managers_sales_target', [
        /*'state_id' => $state_id,
        'district_id' => $district_id,
        'mandal_id' => $mandal_id,*/
        'regional_manager_id' => $regional_manager_id,
        'month' => $month,
        'year' => $year,
        //'delete_status' => 1
    ])->num_rows() > 0;

    echo json_encode(['exists' => $exists]);
}

// public function insert_sales_target(){
//     if (!has_access(2)) {
//         echo json_encode([
//             'success' => false,
//             'message' => 'Unauthorized access'
//         ]);
//         return;
//     }
//     $sess_data = $this->session_data();
//     $regional_manager_id = $this->input->post('regional_manager_id');
//     $month = $this->input->post('month');
//     $year = $this->input->post('year');
//     $check = $this->registermodel->common_fetch('regional_managers_sales_target',['regional_manager_id' => $regional_manager_id,'month' => $month,'year' => $year]);
//     if(!empty($check)){
//         echo json_encode(['success' => false, 'message' => 'data inserted already']);
//         return;
//     }else{
    
//         $data = [
//             'regional_manager_id'       => $this->input->post('regional_manager_id'),
//             'month'                     => $this->input->post('month'),
//             'year'                      => $this->input->post('year'),
//             'target'                    => $this->input->post('target'),
//             'created_on'                => date('Y-m-d H:i:s')
//         ];
    
//         $insert = $this->registermodel->common_insert('regional_managers_sales_target',$data);
        

//         echo json_encode(['success' => true, 'message' => 'data added successfully']);
//         return;
//     }
// }

public function insert_sales_target(){
    $state_id = $this->input->post('state_id');
    $month    = $this->input->post('month');
    $year     = $this->input->post('year');
    $target   = $this->input->post('target');

    if ($state_id === 'all') {
        $regional_managers = $this->registermodel->common_fetch('regional_managers', ['status' => 1, 'delete_status' => 1]);

        if (empty($regional_managers)) {
            echo json_encode(['success' => false, 'message' => 'No Regional Managers found.']);
            return;
        }

        // Fetch existing entries to avoid duplicates
        $rm_ids = array_column($regional_managers, 'id');
        $existing = $this->db
            ->select('regional_manager_id')
            ->from('regional_managers_sales_target')
            ->where_in('regional_manager_id', $rm_ids)
            ->where('month', $month)
            ->where('year', $year)
            ->get()
            ->result_array();

        $existing_ids = array_column($existing, 'regional_manager_id');

        $insert_data = [];
        foreach ($regional_managers as $rm) {
            /*if (in_array($rm['id'], $existing_ids)) {
                continue; // Skip if already inserted
            }*/

            $insert_data[] = [
                'regional_manager_id' => $rm['id'],
                'month'               => $month,
                'year'                => $year,
                'target'              => $target,
                'target_given_by'     => 'admin',
                'created_on'          => date('Y-m-d H:i:s')
            ];
        }

        if (!empty($insert_data)) {
            $this->db->insert_batch('regional_managers_sales_target', $insert_data);
            echo json_encode(['success' => true, 'message' => 'Targets inserted for ' . count($insert_data) . ' regional managers.']);
        } else {
            echo json_encode(['success' => false, 'message' => 'All regional managers already have targets for this month and year.']);
        }
    } else {
        // Insert for single RM
        $regional_manager_id = $this->input->post('regional_manager_id');

        $check = $this->registermodel->common_fetch('regional_managers_sales_target', [
            'regional_manager_id' => $regional_manager_id,
            'month' => $month,
            'year' => $year
        ]);

        /*if (!empty($check)) {
            echo json_encode(['success' => false, 'message' => 'Target already inserted for this regional manager.']);
            return;
        }*/

        $data = [
            'regional_manager_id' => $regional_manager_id,
            'month'               => $month,
            'year'                => $year,
            'target'              => $target,
            'target_given_by'     => 'admin',
            'created_on'          => date('Y-m-d H:i:s')
        ];

        $this->db->insert('regional_managers_sales_target', $data);
        echo json_encode(['success' => true, 'message' => 'Target inserted successfully.']);
    }
}
/*sales_target*/

/*medical_advisor_sales_target*/
public function medical_advisor_sales_target(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/medical_advisor_sales_target');
	$this->load->view('admin/includes/footer');
}
public function get_medical_advisor_sales_target(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_medical_advisor_sales_target($limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_medical_advisor_sales_target_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function add_medical_advisor_sales_target(){
    check_permission(2);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $data['months'] = $this->registermodel->common_fetch_asc('months',[]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_medical_advisor_sales_target',$data);
	$this->load->view('admin/includes/footer');
}
public function get_villages_by_state_district_mandal(){
    $state_id = $this->input->post('state_id');
    $district_id = $this->input->post('district_id');
    $mandal_id = $this->input->post('mandal_id');
    $cities = $this->registermodel->common_fetch_asc('villages', [
        'state_id' => $state_id,
        'district_id' => $district_id,
        'mandal_id' => $mandal_id,
        'status' => 1,
        'delete_status' => 1
    ]);
    echo json_encode($cities);
}
public function get_medical_advisors_by_state_district_mandal_village(){
    $state_id     = $this->input->post('state_id');
    $district_id  = $this->input->post('district_id');
    $mandal_ids   = $this->input->post('mandal_id'); // Should be an array
    $village_id   = $this->input->post('village_id');
    
    $this->db->where('state_id', $state_id);
    $this->db->where('district_id', $district_id);
    $this->db->where('mandal_id', $mandal_ids);
    $this->db->where('village_id', $village_id);
    $this->db->where('status', 1);
    $this->db->where('delete_status', 1);

    /*if (!empty($mandal_ids) && is_array($mandal_ids)) {
        $this->db->where_in('mandal_id', $mandal_ids);
    }*/

    $cities = $this->db->get('executives')->result_array();

    echo json_encode($cities);
}
public function check_medical_advisor_existing_target() {
    $state_id = $this->input->post('state_id');
    $district_id = $this->input->post('district_id');
    $mandal_id = $this->input->post('mandal_id');
    $village_id = $this->input->post('village_id');
    $regional_manager_id = $this->input->post('regional_manager_id');
    $month = $this->input->post('month');
    $year = $this->input->post('year');

    $exists = $this->db->get_where('executive_sales_target', [
        /*'state_id' => $state_id,
        'district_id' => $district_id,
        'mandal_id' => $mandal_id,*/
        'executive_id' => $regional_manager_id,
        'month' => $month,
        'year' => $year,
        //'delete_status' => 1
    ])->num_rows() > 0;

    echo json_encode(['exists' => $exists]);
}
public function insert_medical_advisor_sales_target(){
    $state_id = $this->input->post('state_id');
    $month    = $this->input->post('month');
    $year     = $this->input->post('year');
    $target   = $this->input->post('target');

    if ($state_id === 'all') {
        $regional_managers = $this->registermodel->common_fetch('executives', ['status' => 1, 'delete_status' => 1]);

        if (empty($regional_managers)) {
            echo json_encode(['success' => false, 'message' => 'No Medical Advisors found.']);
            return;
        }

        // Fetch existing entries to avoid duplicates
        $rm_ids = array_column($regional_managers, 'id');
        $existing = $this->db
            ->select('executive_id')
            ->from('executive_sales_target')
            ->where_in('executive_id', $rm_ids)
            ->where('month', $month)
            ->where('year', $year)
            ->get()
            ->result_array();

        $existing_ids = array_column($existing, 'executive_id');

        $insert_data = [];
        foreach ($regional_managers as $rm) {
            /*if (in_array($rm['id'], $existing_ids)) {
                continue; // Skip if already inserted
            }*/

            $insert_data[] = [
                //'regional_manager_id'   => $rm['regional_manager_id'],
                'executive_id'          => $rm['id'],
                'month'                 => $month,
                'year'                  => $year,
                'target'                => $target,
                'target_given_by'       => 'admin',
                'created_on'            => date('Y-m-d H:i:s')
            ];
        }
        
        //print_r($insert_data);exit;

        if (!empty($insert_data)) {
            $this->db->insert_batch('executive_sales_target', $insert_data);
            echo json_encode(['success' => true, 'message' => 'Targets inserted for ' . count($insert_data) . ' medical advisors.']);
        } else {
            echo json_encode(['success' => false, 'message' => 'All medical advisors already have targets for this month and year.']);
        }
    } else {
        // Insert for single RM
        $regional_manager_id = $this->input->post('regional_manager_id');

        $check = $this->registermodel->common_fetch('executive_sales_target', [
            'executive_id' => $regional_manager_id,
            'month' => $month,
            'year' => $year
        ]);
        
        $check = $this->registermodel->common_fetch('executives', [
            'id' => $regional_manager_id
        ]);

        /*if (!empty($check)) {
            echo json_encode(['success' => false, 'message' => 'Target already inserted for this medical advisor.']);
            return;
        }*/

        $data = [
            //'regional_manager_id' => $check[0]['regional_manager_id'],
            'executive_id'        => $regional_manager_id,
            'month'               => $month,
            'year'                => $year,
            'target'              => $target,
            'target_given_by'     => 'admin',
            'created_on'          => date('Y-m-d H:i:s')
        ];

        $this->db->insert('executive_sales_target', $data);
        echo json_encode(['success' => true, 'message' => 'Target inserted successfully.']);
    }
}
/*medical_advisor_sales_target*/

/*regional_manager_sales_target*/
public function regional_manager_sales_target(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/regional_manager_sales_target');
	$this->load->view('admin/includes/footer');
}
public function get_regional_manager_sales_target(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query
    
    $month_year = $this->input->post('month_year');

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_regional_manager_sales_target($month_year,$limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_regional_manager_sales_target_count($month_year,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*regional_manager_sales_target*/

/*executive_sales_requests*/
public function executive_sales_requests(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/executive_sales_requests');
	$this->load->view('admin/includes/footer');
}
public function get_executive_sales_requests(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query
    
    $month_year = $this->input->post('month_year');

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_executive_sales_requests($month_year,$limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_executive_sales_requests_count($month_year,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function executive_amount_credit_status(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $order_id = $this->input->post('order_idd');
    $status = $this->input->post('status');
    
    $booking_details = $this->registermodel->common_fetch('executive_sales_commission_requests',['id' => $order_id]);
    $update = $this->registermodel->common_update('executive_sales_commission_requests',['status' => $status,'credit_date' => date('Y-m-d')],['id' => $order_id]);
    
    $user_details = $this->registermodel->common_fetch('executives',['id' => $booking_details[0]['executive_id']]);
    
    
    /*user_notification*/
    $data = array(
       'member_id'          => $booking_details[0]['executive_id'],
       'title'              => 'Med Rayder',
       'message'            => "Your Amount Request(₹ {$booking_details[0]['amount']}) has been successfully credited",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data['title']; 
    $message['body'] = $data['message'];
    $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('executive_notifications',$data);
    /*user_notification*/
    
    
    echo json_encode(['success' => true, 'message' => "Amount has been $status successfully."]);
}
public function executive_sales_history($id){
    $data['id'] = $id;
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/executive_sales_history',$data);
	$this->load->view('admin/includes/footer');
}
public function get_executive_sales_history($id){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }

    $sess_data   = $this->session_data();
    $limit       = $this->input->post("length");
    $start       = $this->input->post("start");
    $search      = $this->input->post("search")["value"] ?? "";
    $month_year  = $this->input->post('month_year');

    // If month_year is empty, return default empty DataTables response
    /*if (empty($month_year)) {
        echo json_encode([
            "draw" => intval($this->input->post("draw")),
            "recordsTotal" => 0,
            "recordsFiltered" => 0,
            "data" => []
        ]);
        return;
    }*/

    // Fetch data if month_year is available
    $data = $this->registermodel->get_executive_sales_history($month_year, $id, $limit, $start, $search);
    $totalRecords = $this->registermodel->get_executive_sales_history_count($month_year, $id, $search);

    echo json_encode([
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ]);
}
/*executive_sales_requests*/

/*executive_sales_credit*/
public function executive_sales_credit(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/executive_sales_credit');
	$this->load->view('admin/includes/footer');
}
public function get_executive_sales_credit(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query
    
    $month_year = $this->input->post('month_year');

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_executive_sales_credit($month_year,$limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_executive_sales_credit_count($month_year,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*executive_sales_credit*/

/*sales_hierarchy*/

/*sub_admins*/
public function sub_admins(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/sub_admins');
	$this->load->view('admin/includes/footer');
}
public function get_sub_admins(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_sub_admins($sess_data,$limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_sub_admins_count($sess_data,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_sub_admin_status(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('sub_admins',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_sub_admin(){
    check_permission(2);
    $data['roles'] = $this->registermodel->common_fetch_asc('roles',['id!='=> 1,'status' => 1, 'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/add_sub_admin',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_sub_admin(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $mobile = $this->input->post('mobile');
    $check = $this->registermodel->common_fetch('sub_admins',['mobile' => $mobile,'delete_status' => 1]);
    if(!empty($check)){
        echo json_encode(['success' => false, 'message' => 'data inserted already']);
        return;
    }else{
        $config['upload_path']			= $this->bharosa_base_path . 'sub_admins/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/sub_admins/'.$uploadData['file_name'];
    
        $data = [
            'main_data_id'      => $sess_data,
            'name'              => $this->input->post('name'),
            'mobile'            => $this->input->post('mobile'),
            'image'             => $photo,
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert = $this->registermodel->common_insert('sub_admins',$data);
        
        $selected_roles = $this->input->post('roles');

        // Ensure role_id 1 is always included
        if (!empty($selected_roles)) {
            if (!in_array(1, $selected_roles)) {
                $selected_roles[] = 1;
            }
        } else {
            $selected_roles = [1]; // If no roles selected, still assign role_id 1
        }
        
        foreach ($selected_roles as $role_id) {
            $this->db->insert('permissions', [
                'sub_admin_id' => $insert,
                'role_id'      => $role_id,
                'created_on'   => date('Y-m-d H:i:s')
            ]);
        }

        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_sub_admin($id){
    check_permission(2);
   $decoded_id = base64_decode($id);

   $data['sub_admin'] = $this->registermodel->common_fetch('sub_admins', ['id' => $decoded_id]);
   $data['roles'] = $this->registermodel->common_fetch_asc('roles', ['id!='=> 1,'status' => 1, 'delete_status' => 1]);

   $permissions = $this->registermodel->common_fetch_asc('permissions', ['sub_admin_id' => $decoded_id]);
   $data['assigned_roles'] = array_column($permissions, 'role_id');

   $this->load->view('admin/includes/header');
   $this->load->view('admin/edit_sub_admin', $data);
   $this->load->view('admin/includes/footer');
}
public function edit_sub_admin_data($id){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    //echo $id;exit;
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'sub_admins/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/sub_admins/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$data = [
	   'name'           => $this->input->post('name'),
	   'image'          => $image,
	   'modified_on'    => date('Y-m-d H:i:s')
	];
    $update 	= $this->registermodel->common_update('sub_admins',$data,['id' => $id]);
    $delete = $this->registermodel->common_delete('permissions',['sub_admin_id' => $id]);
    $selected_roles = $this->input->post('roles');

    // Ensure role_id 1 is always included
    if (!empty($selected_roles)) {
        if (!in_array(1, $selected_roles)) {
            $selected_roles[] = 1;
        }
    } else {
        $selected_roles = [1]; // Only role_id 1 if no selection
    }
    
    foreach ($selected_roles as $role_id) {
        $this->db->insert('permissions', [
            'sub_admin_id' => $id,
            'role_id'      => $role_id,
            'created_on'   => date('Y-m-d H:i:s')
        ]);
    }

    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_sub_admin(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('sub_admins',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('sub_admins', ['delete_status' => 0], ['id' => $id]);
    $this->registermodel->common_delete('permissions', ['sub_admin_id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*sub_admins*/

/*tele_callers*/
public function tele_callers(){
    check_permission(2);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/tele_callers');
	$this->load->view('admin/includes/footer');
}
public function get_tele_callers(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_tele_callers($limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_tele_callers_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_tele_caller_status(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('tele_callers',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_tele_caller(){
    check_permission(2);
    //$data['roles'] = $this->registermodel->common_fetch_asc('roles',['id!='=> 1,'status' => 1, 'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_tele_caller');
	$this->load->view('admin/includes/footer');
}
public function insert_tele_caller(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $mobile = $this->input->post('mobile');
    $check = $this->registermodel->common_fetch('tele_callers',['mobile' => $mobile,'delete_status' => 1]);
    if(!empty($check)){
        echo json_encode(['success' => false, 'message' => 'data inserted already']);
        return;
    }else{
        $config['upload_path']			= $this->bharosa_base_path . 'tele_callers/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/tele_callers/'.$uploadData['file_name'];
    
        $data = [
            'name'              => $this->input->post('name'),
            'mobile'            => $this->input->post('mobile'),
            'image'             => $photo,
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert = $this->registermodel->common_insert('tele_callers',$data);
        
        /*$selected_roles = $this->input->post('roles');

        // Ensure role_id 1 is always included
        if (!empty($selected_roles)) {
            if (!in_array(1, $selected_roles)) {
                $selected_roles[] = 1;
            }
        } else {
            $selected_roles = [1]; // If no roles selected, still assign role_id 1
        }
        
        foreach ($selected_roles as $role_id) {
            $this->db->insert('permissions', [
                'sub_admin_id' => $insert,
                'role_id'      => $role_id,
                'created_on'   => date('Y-m-d H:i:s')
            ]);
        }*/

        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_tele_caller($id){
    check_permission(2);
   $decoded_id = base64_decode($id);

   $data['tele_caller'] = $this->registermodel->common_fetch('tele_callers', ['id' => $decoded_id]);

   $this->load->view('admin/includes/header');
   $this->load->view('admin/super_admin/edit_tele_caller', $data);
   $this->load->view('admin/includes/footer');
}
public function edit_tele_caller_data($id){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    //echo $id;exit;
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'tele_callers/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/tele_callers/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$data = [
	   'name'           => $this->input->post('name'),
	   'image'          => $image,
	   'modified_on'    => date('Y-m-d H:i:s')
	];
    $update 	= $this->registermodel->common_update('tele_callers',$data,['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_tele_caller(){
    if (!has_access(2)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('tele_callers',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('tele_callers', ['delete_status' => 0], ['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*tele_callers*/

/*banners*/
public function banners(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/banners');
	$this->load->view('admin/includes/footer');
}
public function get_banners(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_banners($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_banners_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_banner_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('banners',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_banner(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_banner');
	$this->load->view('admin/includes/footer');
}
public function insert_banner() {
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }

    $config['upload_path']   = $this->bharosa_base_path . 'banners/';
    $config['allowed_types'] = 'jpeg|jpg|png';
    $this->load->library('upload');
    
    $files = $_FILES['image'];
    $file_count = count($files['name']);
    $uploaded_files = [];

    for ($i = 0; $i < $file_count; $i++) {
        $_FILES['single_image']['name']     = $files['name'][$i];
        $_FILES['single_image']['type']     = $files['type'][$i];
        $_FILES['single_image']['tmp_name'] = $files['tmp_name'][$i];
        $_FILES['single_image']['error']    = $files['error'][$i];
        $_FILES['single_image']['size']     = $files['size'][$i];

        $config['file_name'] = time() . '_' . $i; // unique name per file
        $this->upload->initialize($config);

        if (!$this->upload->do_upload('single_image')) {
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'Upload error: ' . $error]);
            return;
        } else {
            $uploadData = $this->upload->data();
            $photo_path = 'assets/admin/banners/' . $uploadData['file_name'];

            $data = [
                'image'      => $photo_path,
                'created_on' => date('Y-m-d H:i:s')
            ];

            $this->registermodel->common_insert('banners', $data);
            $uploaded_files[] = $photo_path;
        }
    }

    echo json_encode(['success' => true, 'message' => 'All images uploaded successfully.', 'files' => $uploaded_files]);
}
public function edit_banner($id){
    check_permission(3);
   $data['banner'] = $this->registermodel->common_fetch('banners',['id' => base64_decode($id)]);
   $this->load->view('admin/includes/header');
   $this->load->view('admin/super_admin/edit_banner',$data);
   $this->load->view('admin/includes/footer');
}
public function edit_banner_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'banners/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/banners/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$data = [
	   'image'          => $image,
	   'modified_on'    => date('Y-m-d H:i:s')
	];
    $update 	= $this->registermodel->common_update('banners',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_banner(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('banners',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('banners', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*banners*/

/*lab_test_banners*/
public function lab_test_banners(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_test_banners');
	$this->load->view('admin/includes/footer');
}
public function get_lab_test_banners(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_lab_test_banners($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_lab_test_banners_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_lab_test_banner_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('lab_test_banners',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_lab_test_banner(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_lab_test_banner');
	$this->load->view('admin/includes/footer');
}
public function insert_lab_test_banner(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $check = $this->registermodel->common_fetch('lab_test_banners',['name' => $name,'delete_status' => 1]);
    if(!empty($check)){
        echo json_encode(['success' => false, 'message' => 'Lab test banner name is inserted already']);
        return;
    }else{
    
        $config['upload_path']			= $this->bharosa_base_path . 'lab_test_banners/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/lab_test_banners/'.$uploadData['file_name'];
        
        $data = [
            'name'              => $this->input->post('name'),
            'image'             => $photo,
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('lab_test_banners',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_lab_test_banner($id){
    check_permission(3);
   $data['banner'] = $this->registermodel->common_fetch('lab_test_banners',['id' => base64_decode($id)]);
   $this->load->view('admin/includes/header');
   $this->load->view('admin/super_admin/edit_lab_test_banner',$data);
   $this->load->view('admin/includes/footer');
}
public function edit_lab_test_banner_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'lab_test_banners/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/lab_test_banners/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$data = [
	   'name'           => $this->input->post('name'),
	   'image'          => $image,
	   'modified_on'    => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('lab_test_banners', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'lab test banner name is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('lab_test_banners',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_lab_test_banner(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('lab_test_banners',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('lab_test_banners', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*lab_test_banners*/

/*blood_groups*/
public function blood_groups(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/blood_groups');
	$this->load->view('admin/includes/footer');
}
public function get_blood_groups(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_blood_groups($limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_blood_groups_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_blood_group_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('blood_groups',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_blood_group(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_blood_group');
	$this->load->view('admin/includes/footer');
}
public function insert_blood_group(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $name = $this->input->post('name');
    $check = $this->registermodel->common_fetch('blood_groups',['name' => $name,'delete_status' => 1]);
    if(!empty($check)){
        echo json_encode(['success' => false, 'message' => 'blood group inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert = $this->registermodel->common_insert('blood_groups',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_blood_group($id){
    check_permission(3);
   $data['blood_group'] = $this->registermodel->common_fetch('blood_groups',['id' => base64_decode($id)]);
   $this->load->view('admin/includes/header');
   $this->load->view('admin/super_admin/edit_blood_group',$data);
   $this->load->view('admin/includes/footer');
}
public function edit_blood_group_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	   'name'           => $this->input->post('name'),
	   'modified_on'    => date('Y-m-d H:i:s')
	];
	// Check if the category is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('blood_groups', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'blood group is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('blood_groups',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_blood_group(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');

    $this->registermodel->common_update('blood_groups', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*blood_groups*/

/*categories*/
public function categories(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/categories');
	$this->load->view('admin/includes/footer');
}
public function get_categories(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_categories($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_categories_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_category_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('categories',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_category(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_category');
	$this->load->view('admin/includes/footer');
}
public function insert_category(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $check = $this->registermodel->common_fetch('categories',['name' => $name,'delete_status' => 1]);
    if(!empty($check)){
        echo json_encode(['success' => false, 'message' => 'category is inserted already']);
        return;
    }else{
    
        $config['upload_path']			= $this->bharosa_base_path . 'categories/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/categories/'.$uploadData['file_name'];
        
        $data = [
            'name'              => $this->input->post('name'),
            'image'             => $photo,
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('categories',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_category($id){
    check_permission(3);
    $data['category'] = $this->registermodel->common_fetch('categories',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_category',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_category_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'categories/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/categories/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$data = [
	   'name'              => $this->input->post('name'),
       'image'             => $image,
	   'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('categories', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'category is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('categories',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_category(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('categories',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('categories', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*categories*/

/*coverage_categories*/
public function coverage_categories(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/coverage_categories');
	$this->load->view('admin/includes/footer');
}
public function get_coverage_categories(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_coverage_categories($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_coverage_categories_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_coverage_category_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('coverage_categories',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_coverage_category(){
    check_permission(3);
    $sess_data = $this->session_data();
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_coverage_category',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_coverage_category(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $cat_id = $this->input->post('cat_id');
    $check_name = $this->registermodel->common_fetch('coverage_categories',['name' => $name,'delete_status' => 1]);
    if(!empty($check_name)){
        echo json_encode(['success' => false, 'message' => 'coverage category is inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('coverage_categories',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_coverage_category($id){
    check_permission(3);
    $data['coverage_category'] = $this->registermodel->common_fetch('coverage_categories',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_coverage_category',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_coverage_category_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('coverage_categories', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'coverage category is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('coverage_categories',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_coverage_category(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');

    $this->registermodel->common_update('coverage_categories', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*coverage_categories*/

/*distance*/
public function distance(){
    check_permission(3);
    $data['distance'] = $this->registermodel->common_fetch('distance',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/distance',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_distance_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'distance'           => $this->input->post('distance'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('distance',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*distance*/

/*gst*/
public function gst(){
    check_permission(3);
    $data['gst'] = $this->registermodel->common_fetch('gst',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/gst',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_gst_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'amount'             => $this->input->post('amount'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('gst',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*gst*/

/*states*/
public function states(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/states');
	$this->load->view('admin/includes/footer');
}
public function get_states(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_states($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_states_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_state_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('states',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_state(){
    check_permission(3);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_state');
	$this->load->view('admin/includes/footer');
}
public function insert_state(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $cat_id = $this->input->post('cat_id');
    $check_name = $this->registermodel->common_fetch('states',['name' => $name,'delete_status' => 1]);
    if(!empty($check_name)){
        echo json_encode(['success' => false, 'message' => 'state is inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('states',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_state($id){
    check_permission(3);
    $data['state'] = $this->registermodel->common_fetch('states',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_state',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_state_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('states', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'state is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('states',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_state(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');

    $this->registermodel->common_update('states', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*states*/

/*districts*/
public function districts(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/districts');
	$this->load->view('admin/includes/footer');
}
public function get_districts(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_districts($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_districts_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_district_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('districts',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_district(){
    check_permission(3);
    $sess_data = $this->session_data();
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_district',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_district(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }

    $sess_data = $this->session_data();
    $names = $this->input->post('name'); // This is an array
    $state_id = $this->input->post('state_id');

    if (empty($state_id) || empty($names) || !is_array($names)) {
        echo json_encode(['success' => false, 'message' => 'Invalid input']);
        return;
    }

    $added = [];
    $duplicates = [];

    foreach ($names as $name) {
        $name = trim($name);
        if ($name === '') continue;

        $check_name = $this->registermodel->common_fetch('districts', [
            'state_id' => $state_id,
            'name' => $name,
            'delete_status' => 1
        ]);

        if (!empty($check_name)) {
            $duplicates[] = $name;
        } else {
            $data = [
                'state_id' => $state_id,
                'name' => $name,
                'created_on' => date('Y-m-d H:i:s')
            ];
            $this->registermodel->common_insert('districts', $data);
            $added[] = $name;
        }
    }

    if (!empty($added)) {
        $message = 'District(s) added: ' . implode(', ', $added);
        if (!empty($duplicates)) {
            $message .= '. Skipped (already exist): ' . implode(', ', $duplicates);
        }
        echo json_encode(['success' => true, 'message' => $message]);
    } else {
        $message = 'No new districts added.';
        if (!empty($duplicates)) {
            $message .= ' All entries already exist: ' . implode(', ', $duplicates);
        }
        echo json_encode(['success' => false, 'message' => $message]);
    }
}
public function edit_district($id){
    check_permission(3);
    $data['district'] = $this->registermodel->common_fetch('districts',['id' => base64_decode($id)]);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_district',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_district_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	    'state_id'           => $this->input->post('state_id'),
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
	$state_id = $this->input->post('state_id');
    $name     = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('districts', ['state_id' => $state_id,'name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'district is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('districts',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_district(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');

    $this->registermodel->common_update('districts', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*districts*/

/*cities*/
public function cities(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/cities');
	$this->load->view('admin/includes/footer');
}
public function get_cities(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_cities($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_cities_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_city_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('cities',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_city(){
    check_permission(3);
    $sess_data = $this->session_data();
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_city',$data);
	$this->load->view('admin/includes/footer');
}

public function insert_city() {
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }

    $sess_data   = $this->session_data();
    $names       = $this->input->post('name'); // Should be an array of names
    $state_id    = $this->input->post('state_id');
    $district_id = $this->input->post('district_id');

    if (!is_array($names) || empty($names)) {
        echo json_encode(['success' => false, 'message' => 'Please provide at least one city name']);
        return;
    }

    // Fetch all existing city names for that district and state
    $existing_names = $this->db->select('name')
        ->from('cities')
        ->where([
            'state_id' => $state_id,
            'district_id' => $district_id,
            'delete_status' => 1
        ])
        ->get()->result();

    // Convert to lowercase array for easy comparison
    $existing_names_lower = array_map(function($obj) {
        return mb_strtolower(trim($obj->name), 'UTF-8');
    }, $existing_names);

    $inserted = [];
    $skipped = [];

    foreach ($names as $name) {
        $name_clean = trim($name);
        if ($name_clean == '') continue;

        $name_lower = mb_strtolower($name_clean, 'UTF-8');

        if (in_array($name_lower, $existing_names_lower)) {
            $skipped[] = $name_clean;
        } else {
            $data = [
                'state_id'    => $state_id,
                'district_id' => $district_id,
                'name'        => $name_clean,
                'created_on'  => date('Y-m-d H:i:s')
            ];
            $this->registermodel->common_insert('cities', $data);
            $inserted[] = $name_clean;
        }
    }

    echo json_encode([
        'success' => true,
        'message' => 'city added successfully',
        'inserted' => $inserted,
        'skipped'  => $skipped
    ]);
}
public function edit_city($id){
    check_permission(3);
    $data['city'] = $this->registermodel->common_fetch('cities',['id' => base64_decode($id)]);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_city',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_city_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	    'state_id'           => $this->input->post('state_id'),
	    'district_id'        => $this->input->post('district_id'),
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
	$state_id = $this->input->post('state_id');
	$district_id = $this->input->post('district_id');
    $name     = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('cities', ['state_id' => $state_id,'district_id' => $district_id,'name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'city is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('cities',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_city(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');

    $this->registermodel->common_update('cities', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*cities*/

/*mandals*/
public function mandals(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/mandals');
	$this->load->view('admin/includes/footer');
}
public function get_mandals(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_mandals($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_mandals_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_mandal_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('mandals',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_mandal(){
    check_permission(3);
    $sess_data = $this->session_data();
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_mandal',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_mandal(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }

    $sess_data   = $this->session_data();
    $names       = $this->input->post('name'); // Should be an array of names
    $state_id    = $this->input->post('state_id');
    $district_id = $this->input->post('district_id');

    if (!is_array($names) || empty($names)) {
        echo json_encode(['success' => false, 'message' => 'Please provide at least one mandal name']);
        return;
    }

    // Fetch all existing city names for that district and state
    $existing_names = $this->db->select('name')
        ->from('mandals')
        ->where([
            'state_id' => $state_id,
            'district_id' => $district_id,
            'delete_status' => 1
        ])
        ->get()->result();

    // Convert to lowercase array for easy comparison
    $existing_names_lower = array_map(function($obj) {
        return mb_strtolower(trim($obj->name), 'UTF-8');
    }, $existing_names);

    $inserted = [];
    $skipped = [];

    foreach ($names as $name) {
        $name_clean = trim($name);
        if ($name_clean == '') continue;

        $name_lower = mb_strtolower($name_clean, 'UTF-8');

        if (in_array($name_lower, $existing_names_lower)) {
            $skipped[] = $name_clean;
        } else {
            $data = [
                'state_id'    => $state_id,
                'district_id' => $district_id,
                'name'        => $name_clean,
                'created_on'  => date('Y-m-d H:i:s')
            ];
            $this->registermodel->common_insert('mandals', $data);
            $inserted[] = $name_clean;
        }
    }

    echo json_encode([
        'success' => true,
        'message' => 'mandal added successfully',
        'inserted' => $inserted,
        'skipped'  => $skipped
    ]);
}
public function edit_mandal($id){
    check_permission(3);
    $data['mandal'] = $this->registermodel->common_fetch('mandals',['id' => base64_decode($id)]);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_mandal',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_mandal_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	    'state_id'           => $this->input->post('state_id'),
	    'district_id'        => $this->input->post('district_id'),
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
	$state_id = $this->input->post('state_id');
	$district_id = $this->input->post('district_id');
    $name     = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('mandals', ['state_id' => $state_id,'district_id' => $district_id,'name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'mandal is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('mandals',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_mandal(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');

    $this->registermodel->common_update('mandals', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*mandals*/

/*villages*/
public function villages(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/villages');
	$this->load->view('admin/includes/footer');
}
public function get_villages(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_villages($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_villages_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_village_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('villages',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_village(){
    check_permission(3);
    $sess_data = $this->session_data();
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_village',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_village(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }

    $sess_data   = $this->session_data();
    $names       = $this->input->post('name'); // Should be an array of names
    $state_id    = $this->input->post('state_id');
    $district_id = $this->input->post('district_id');
    $mandal_id = $this->input->post('mandal_id');

    if (!is_array($names) || empty($names)) {
        echo json_encode(['success' => false, 'message' => 'Please provide at least one village name']);
        return;
    }

    // Fetch all existing city names for that district and state
    $existing_names = $this->db->select('name')
        ->from('villages')
        ->where([
            'state_id' => $state_id,
            'district_id' => $district_id,
            'mandal_id'  => $mandal_id,
            'delete_status' => 1
        ])
        ->get()->result();

    // Convert to lowercase array for easy comparison
    $existing_names_lower = array_map(function($obj) {
        return mb_strtolower(trim($obj->name), 'UTF-8');
    }, $existing_names);

    $inserted = [];
    $skipped = [];

    foreach ($names as $name) {
        $name_clean = trim($name);
        if ($name_clean == '') continue;

        $name_lower = mb_strtolower($name_clean, 'UTF-8');

        if (in_array($name_lower, $existing_names_lower)) {
            $skipped[] = $name_clean;
        } else {
            $data = [
                'state_id'    => $state_id,
                'district_id' => $district_id,
                'mandal_id' => $mandal_id,
                'name'        => $name_clean,
                'created_on'  => date('Y-m-d H:i:s')
            ];
            $this->registermodel->common_insert('villages', $data);
            $inserted[] = $name_clean;
        }
    }

    echo json_encode([
        'success' => true,
        'message' => 'village added successfully',
        'inserted' => $inserted,
        'skipped'  => $skipped
    ]);
}
public function edit_village($id){
    check_permission(3);
    $data['village'] = $this->registermodel->common_fetch('villages',['id' => base64_decode($id)]);
    $data['states'] = $this->registermodel->common_fetch_asc('states',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_village',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_village_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	    'state_id'           => $this->input->post('state_id'),
	    'district_id'        => $this->input->post('district_id'),
	    'mandal_id'          => $this->input->post('mandal_id'),
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
	$state_id = $this->input->post('state_id');
	$district_id = $this->input->post('district_id');
	$mandal_id = $this->input->post('mandal_id');
    $name     = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('villages', ['state_id' => $state_id,'district_id' => $district_id,'mandal_id' => $mandal_id,'name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'village is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('villages',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_village(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');

    $this->registermodel->common_update('villages', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*villages*/

/*subscriptions*/
public function subscriptions(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/subscriptions');
	$this->load->view('admin/includes/footer');
}
public function get_subscriptions(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_subscriptions($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_subscriptions_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_subscription_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('health_cards',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_subscription(){
    check_permission(3);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_subscription');
	$this->load->view('admin/includes/footer');
}
public function insert_subscription(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $check = $this->registermodel->common_fetch('health_cards',['name' => $name,'delete_status' => 1]);
    if(!empty($check)){
        echo json_encode(['success' => false, 'message' => 'subscription is inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'price'             => $this->input->post('price'),
            'discount_price'    => $this->input->post('discount_price'),
            'duration'          => $this->input->post('duration'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('health_cards',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_subscription($id){
    check_permission(3);
    $data['subscription'] = $this->registermodel->common_fetch('health_cards',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_subscription',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_subscription_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'name'                  => $this->input->post('name'),
        'price'                 => $this->input->post('price'),
        'discount_price'        => $this->input->post('discount_price'),
        'duration'              => $this->input->post('duration'),
	    'modified_on'           => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $name     = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('health_cards', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'subscription is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('health_cards',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_subscription(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');

    $this->registermodel->common_update('health_cards', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*subscriptions*/

/*medical_degrees*/
public function medical_degrees(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/medical_degrees');
	$this->load->view('admin/includes/footer');
}
public function get_medical_degrees(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_medical_degrees($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_medical_degrees_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_medical_degree_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('medical_degrees',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_medical_degree(){
    check_permission(3);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_medical_degree');
	$this->load->view('admin/includes/footer');
}
public function insert_medical_degree(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $check = $this->registermodel->common_fetch('medical_degrees',['name' => $name,'delete_status' => 1]);
    if(!empty($check)){
        echo json_encode(['success' => false, 'message' => 'medical degree is inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('medical_degrees',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_medical_degree($id){
    check_permission(3);
    $data['medical_degree'] = $this->registermodel->common_fetch('medical_degrees',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_medical_degree',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_medical_degree_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('medical_degrees', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'medical degree is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('medical_degrees',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_medical_degree(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');

    $this->registermodel->common_update('medical_degrees', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*medical_degrees*/

/*online_doctor_specialities*/
public function online_doctor_specialities(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctor_specialities');
	$this->load->view('admin/includes/footer');
}
public function get_online_doctor_specialities(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_online_doctor_specialities($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_online_doctor_specialities_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_online_doctor_speciality_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('online_doctor_specialities',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_online_doctor_speciality(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_online_doctor_speciality');
	$this->load->view('admin/includes/footer');
}
public function insert_online_doctor_speciality(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $check = $this->registermodel->common_fetch('online_doctor_specialities',['name' => $name,'delete_status' => 1]);
    if(!empty($check)){
        echo json_encode(['success' => false, 'message' => 'online doctor speciality is inserted already']);
        return;
    }else{
    
        $config['upload_path']			= $this->bharosa_base_path . 'specialities/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/specialities/'.$uploadData['file_name'];
        
        $data = [
            'name'              => $this->input->post('name'),
            'image'             => $photo,
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('online_doctor_specialities',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_online_doctor_speciality($id){
    check_permission(3);
    $data['online_doctor_speciality'] = $this->registermodel->common_fetch('online_doctor_specialities',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_online_doctor_speciality',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_online_doctor_speciality_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'specialities/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/specialities/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$data = [
	   'name'              => $this->input->post('name'),
       'image'             => $image,
	   'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('online_doctor_specialities', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'online doctor speciality is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('online_doctor_specialities',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_online_doctor_speciality(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('online_doctor_specialities',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('online_doctor_specialities', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*online_doctor_specialities*/

/*specialities*/
public function specialities(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/specialities');
	$this->load->view('admin/includes/footer');
}
public function get_specialities(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_specialities($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_specialities_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_speciality_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('specialities',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_speciality(){
    check_permission(3);
    $sess_data = $this->session_data();
    $data['categories'] = $this->registermodel->common_fetch_asc('categories',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_speciality',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_speciality(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $cat_id = $this->input->post('cat_id');
    $check_name = $this->registermodel->common_fetch('specialities',['cat_id' => $cat_id,'name' => $name,'delete_status' => 1]);
    if(!empty($check_name)){
        echo json_encode(['success' => false, 'message' => 'speciality is inserted already']);
        return;
    }else{
        $config['upload_path']			= $this->bharosa_base_path . 'specialities/';
    	$config['allowed_types']        = 'jpeg|jpg|png';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/specialities/'.$uploadData['file_name'];
        
        $data = [
            'cat_id'            => $this->input->post('cat_id'),
            'name'              => $this->input->post('name'),
            'image'             => $photo,
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('specialities',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_speciality($id){
    check_permission(3);
    $data['categories'] = $this->registermodel->common_fetch_asc('categories',['status' => 1,'delete_status' => 1]);
    $data['speciality'] = $this->registermodel->common_fetch('specialities',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_speciality',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_speciality_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $image = $this->input->post('image');
	if($_FILES['image']['name']!==""){
		$config['upload_path']			= $this->bharosa_base_path . 'specialities/';
		$config['allowed_types']        = 'jpeg|jpg|png';
		$config['file_name']            = time();
		$config['max_size']             = 2000;
		/* $config['max_width']         	= 480;
		$config['max_height']           = 160; */
		//print_r($config);exit;
		$this->load->library('upload',$config);
		$this->upload->initialize($config,true);
		if($this->upload->do_upload('image')){
			//echo 'hi';exit;
			$filedata = $this->upload->data();
			$image = 'assets/admin/specialities/'.$filedata['file_name'];
			//echo $image;exit;
		}else{
			$error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
		}
	}
	$data = [
	   'cat_id'             => $this->input->post('cat_id'),
	   'name'               => $this->input->post('name'),
       'image'              => $image,
	   'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
	$cat_id = $this->input->post('cat_id');
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('specialities', ['cat_id' => $cat_id, 'name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'speciality is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('specialities',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_speciality(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('specialities',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('specialities', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*specialities*/

/*contact_number*/
public function contact_number(){
    check_permission(3);
    $data['contact_number'] = $this->registermodel->common_fetch('contact_number',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/contact_number',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_contact_number_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'mobile'             => $this->input->post('mobile'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('contact_number',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*contact_number*/

/*executive_commision*/
public function executive_commision(){
    check_permission(3);
    $data['executive_commission'] = $this->registermodel->common_fetch('executive_commission',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/executive_commision',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_executive_commission_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'commission'         => $this->input->post('commission'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('executive_commission',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*executive_commision*/

/*questions*/
public function questions(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/questions');
	$this->load->view('admin/includes/footer');
}
public function get_questions(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_questions($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_questions_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_question_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('questions',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_question(){
   check_permission(3);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_question');
	$this->load->view('admin/includes/footer'); 
}
public function insert_question(){
    if (!has_access(9)) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        return;
    }

    $question = $this->input->post('question');
    $answer = $this->input->post('answer');
    $options = $this->input->post('options');

    if (!$question || !$answer || count($options) < 4) {
        echo json_encode(['success' => false, 'message' => 'All fields are required.']);
        return;
    }

    // Insert question
    $question_data = [
        'question'      => $question,
        'answer'        => $answer,
        'status'        => 1,
        'delete_status' => 1,
        'created_on'    => date('Y-m-d H:i:s')
    ];
    $check = $this->registermodel->common_fetch('questions',['question' => $question,'delete_status' => 1]);
    $check_name = $this->registermodel->common_fetch('questions',['question' => $question,'delete_status' => 1]);
    if(!empty($check_name)){
        echo json_encode(['success' => false, 'message' => 'Question and options inserted already']);
        return;
    }else{
        $question_id = $this->registermodel->common_insert('questions', $question_data);
    
        // Insert options
        foreach ($options as $opt) {
            $this->registermodel->common_insert('question_options', [
                'question_id'   => $question_id,
                'options'       => $opt,
                'status'        => 1,
                'delete_status' => 1,
                'created_on'    => date('Y-m-d H:i:s')
            ]);
        }
    
        echo json_encode(['success' => true, 'message' => 'Question and options inserted successfully']);
    }
}
public function edit_question($id){
    check_permission(3);
    $data['question'] = $this->registermodel->common_fetch('questions',['id' => base64_decode($id)]);
    $data['question_options'] = $this->registermodel->common_fetch_asc('question_options',['question_id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_question',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_question_data($id){
    if (!has_access(9)) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        return;
    }

    $question = $this->input->post('question');
    $answer = $this->input->post('answer');
    $options = $this->input->post('options');

    if (!$question || !$answer || count($options) < 4) {
        echo json_encode(['success' => false, 'message' => 'All fields are required.']);
        return;
    }

    // Insert question
    $question_data = [
        'question'      => $question,
        'answer'        => $answer,
        'modified_on'   => date('Y-m-d H:i:s')
    ];
    
    $question_id = $this->registermodel->common_update('questions', $question_data,['id' => $id]);
    
    $delete = $this->registermodel->common_delete('question_options',['question_id' => $id]);
    
    // Insert options
    foreach ($options as $opt) {
        $this->registermodel->common_insert('question_options', [
            'question_id'   => $id,
            'options'       => $opt,
            'status'        => 1,
            'delete_status' => 1,
            'created_on'    => date('Y-m-d H:i:s')
        ]);
    }

    echo json_encode(['success' => true, 'message' => 'Question and options updated successfully.']);
}
public function delete_question(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
  
    $this->registermodel->common_update('questions', ['delete_status' => 0], ['id' => $id]);
    
    $this->registermodel->common_update('question_options', ['delete_status' => 0], ['question_id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*questions*/

/*qualify_marks*/
public function qualify_marks(){
    check_permission(3);
    $data['qualify_marks'] = $this->registermodel->common_fetch('marks',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/qualify_marks',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_qualify_marks_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'marks'              => $this->input->post('marks'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	$check = $this->registermodel->common_fetch_rows('questions',['status' => 1,'delete_status' => 1]);
	$marks = $this->input->post('marks');
	if($marks>$check){
	    echo json_encode(['success' => false, 'message' => 'qualify marks cannot be greater than questions count']);
        return;
	}else{
        $update 	= $this->registermodel->common_update('marks',$data,['id' => 1]);
        echo json_encode(['success' => true, 'message' => 'data updated successfully']);
        return;
	}
}
/*qualify_marks*/

/*ios_versions*/
public function user_app_ios_version(){
    check_permission(3);
    $data['user_app_ios_version'] = $this->registermodel->common_fetch('user_app_ios_version',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/user_app_ios_version',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_user_app_ios_version_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'version'             => $this->input->post('version'),
	    'modified_on'         => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('user_app_ios_version',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function hospital_app_ios_version(){
    check_permission(3);
    $data['hospital_app_ios_version'] = $this->registermodel->common_fetch('hospital_app_ios_version',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_app_ios_version',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_hospital_app_ios_version_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'version'             => $this->input->post('version'),
	    'modified_on'         => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('hospital_app_ios_version',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function online_doctor_app_ios_version(){
    check_permission(3);
    $data['online_doctor_app_ios_version'] = $this->registermodel->common_fetch('online_doctor_app_ios_version',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctor_app_ios_version',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_online_doctor_app_ios_version_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'version'             => $this->input->post('version'),
	    'modified_on'         => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('online_doctor_app_ios_version',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*ios_versions*/

/*coupons*/

/*hospital_doctor_coupons*/
public function hospital_doctor_coupons(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_doctor_coupons');
	$this->load->view('admin/includes/footer');
}
public function get_hospital_doctor_coupons(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_hospital_doctor_coupons($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_hospital_doctor_coupons_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_hospital_doctor_coupon_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('doctor_coupons',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_hospital_doctor_coupon(){
    check_permission(3);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_hospital_doctor_coupon');
	$this->load->view('admin/includes/footer');
}
public function insert_hospital_doctor_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $check_name = $this->registermodel->common_fetch('doctor_coupons',['name' => $name,'delete_status' => 1]);
    if(!empty($check_name)){
        echo json_encode(['success' => false, 'message' => 'hospital doctor coupon is inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'percentage'        => $this->input->post('percentage'),
            'description'       => $this->input->post('description'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('doctor_coupons',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_hospital_doctor_coupon($id){
    check_permission(3);
    $data['doctor_coupon'] = $this->registermodel->common_fetch('doctor_coupons',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_hospital_doctor_coupon',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_hospital_doctor_coupon_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	   'name'              => $this->input->post('name'),
       'percentage'        => $this->input->post('percentage'),
       'description'       => $this->input->post('description'),
	   'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('doctor_coupons', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'hospital doctor coupn is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('doctor_coupons',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_hospital_doctor_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
  
    $this->registermodel->common_update('doctor_coupons', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*hospital_doctor_coupons*/

/*hospital_diagnostic_coupons*/
public function hospital_diagnostic_coupons(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_diagnostic_coupons');
	$this->load->view('admin/includes/footer');
}
public function get_hospital_diagnostic_coupons(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_hospital_diagnostic_coupons($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_hospital_diagnostic_coupons_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_hospital_diagnostic_coupon_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('hospital_diagnostic_coupons',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_hospital_diagnostic_coupon(){
    check_permission(3);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_hospital_diagnostic_coupon');
	$this->load->view('admin/includes/footer');
}
public function insert_hospital_diagnostic_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $percentage = $this->input->post('percentage');
    
    if($percentage==100){
        echo json_encode(['success' => false, 'message' => 'discount percentage cannot be 100% because we are giving 30% discount on booking a diagnostic test']);
        return;
    }
    $name = $this->input->post('name');
    $check_name = $this->registermodel->common_fetch('hospital_diagnostic_coupons',['name' => $name,'delete_status' => 1]);
    if(!empty($check_name)){
        echo json_encode(['success' => false, 'message' => 'hospital diagnostic coupon is inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'percentage'        => $this->input->post('percentage'),
            'description'       => $this->input->post('description'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('hospital_diagnostic_coupons',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_hospital_diagnostic_coupon($id){
    check_permission(3);
    $data['hospital_diagnostic_coupon'] = $this->registermodel->common_fetch('hospital_diagnostic_coupons',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_hospital_diagnostic_coupon',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_hospital_diagnostic_coupon_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	   'name'              => $this->input->post('name'),
       'percentage'        => $this->input->post('percentage'),
       'description'       => $this->input->post('description'),
	   'modified_on'        => date('Y-m-d H:i:s')
	];
	
	$percentage = $this->input->post('percentage');
	if($percentage==100){
        echo json_encode(['success' => false, 'message' => 'discount percentage cannot be 100% because we are giving 30% discount on booking a diagnostic test']);
        return;
    }
    
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('hospital_diagnostic_coupons', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'hospital diagnostic coupon is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('hospital_diagnostic_coupons',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_hospital_diagnostic_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
  
    $this->registermodel->common_update('hospital_diagnostic_coupons', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*hospital_diagnostic_coupons*/

/*online_doctor_coupons*/
public function online_doctor_coupons(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctor_coupons');
	$this->load->view('admin/includes/footer');
}
public function get_online_doctor_coupons(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_online_doctor_coupons($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_online_doctor_coupons_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_online_doctor_coupon_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('online_doctor_coupons',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_online_doctor_coupon(){
    check_permission(3);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_online_doctor_coupon');
	$this->load->view('admin/includes/footer');
}
public function insert_online_doctor_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $name = $this->input->post('name');
    $check_name = $this->registermodel->common_fetch('online_doctor_coupons',['name' => $name,'delete_status' => 1]);
    if(!empty($check_name)){
        echo json_encode(['success' => false, 'message' => 'online doctor coupon is inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'percentage'        => $this->input->post('percentage'),
            'description'       => $this->input->post('description'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('online_doctor_coupons',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_online_doctor_coupon($id){
    check_permission(3);
    $data['online_doctor_coupon'] = $this->registermodel->common_fetch('online_doctor_coupons',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_online_doctor_coupon',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_online_doctor_coupon_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	   'name'              => $this->input->post('name'),
       'percentage'        => $this->input->post('percentage'),
       'description'       => $this->input->post('description'),
	   'modified_on'        => date('Y-m-d H:i:s')
	];
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('online_doctor_coupons', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'online doctor coupon is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('online_doctor_coupons',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_online_doctor_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
  
    $this->registermodel->common_update('online_doctor_coupons', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*online_doctor_coupons*/

/*diagnostic_coupons*/
public function diagnostic_coupons(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/diagnostic_coupons');
	$this->load->view('admin/includes/footer');
}
public function get_diagnostic_coupons(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_diagnostic_coupons($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_diagnostic_coupons_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_diagnostic_coupon_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('diagnostic_coupons',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_diagnostic_coupon(){
    check_permission(3);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_diagnostic_coupon');
	$this->load->view('admin/includes/footer');
}
public function insert_diagnostic_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $percentage = $this->input->post('percentage');
    
    if($percentage==100){
        echo json_encode(['success' => false, 'message' => 'discount percentage cannot be 100% because we are giving 30% discount on booking a diagnostic test']);
        return;
    }
    
    $name = $this->input->post('name');
    $check_name = $this->registermodel->common_fetch('diagnostic_coupons',['name' => $name,'delete_status' => 1]);
    if(!empty($check_name)){
        echo json_encode(['success' => false, 'message' => 'doctor coupon is inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'percentage'        => $this->input->post('percentage'),
            'description'       => $this->input->post('description'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('diagnostic_coupons',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_diagnostic_coupon($id){
    check_permission(3);
    $data['diagnostic_coupon'] = $this->registermodel->common_fetch('diagnostic_coupons',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_diagnostic_coupon',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_diagnostic_coupon_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	   'name'              => $this->input->post('name'),
       'percentage'        => $this->input->post('percentage'),
       'description'       => $this->input->post('description'),
	   'modified_on'        => date('Y-m-d H:i:s')
	];
	
	$percentage = $this->input->post('percentage');
    
    if($percentage==100){
        echo json_encode(['success' => false, 'message' => 'discount percentage cannot be 100% because we are giving 30% discount on booking a diagnostic test']);
        return;
    }
    
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('diagnostic_coupons', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'diagnostic coupon is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('diagnostic_coupons',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_diagnostic_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
  
    $this->registermodel->common_update('diagnostic_coupons', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*diagnostic_coupons*/

/*lab_test_coupons*/
public function lab_test_coupons(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_test_coupons');
	$this->load->view('admin/includes/footer');
}
public function get_lab_test_coupons(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_lab_test_coupons($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_lab_test_coupons_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_lab_test_coupon_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('lab_test_coupons',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function add_lab_test_coupon(){
    check_permission(3);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_lab_test_coupon');
	$this->load->view('admin/includes/footer');
}
public function insert_lab_test_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $percentage = $this->input->post('percentage');
    
    if($percentage==100){
        echo json_encode(['success' => false, 'message' => 'discount percentage cannot be 100% because we are giving 40% discount on booking a lab test']);
        return;
    }
    
    $name = $this->input->post('name');
    $check_name = $this->registermodel->common_fetch('lab_test_coupons',['name' => $name,'delete_status' => 1]);
    if(!empty($check_name)){
        echo json_encode(['success' => false, 'message' => 'doctor coupon is inserted already']);
        return;
    }else{
        $data = [
            'name'              => $this->input->post('name'),
            'percentage'        => $this->input->post('percentage'),
            'description'       => $this->input->post('description'),
            'created_on'        => date('Y-m-d H:i:s')
        ];
    
        $insert     = $this->registermodel->common_insert('lab_test_coupons',$data);
        echo json_encode(['success' => true, 'message' => 'data added successfully']);
        return;
    }
}
public function edit_lab_test_coupon($id){
    check_permission(3);
    $data['lab_test_coupon'] = $this->registermodel->common_fetch('lab_test_coupons',['id' => base64_decode($id)]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/edit_lab_test_coupon',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_lab_test_coupon_data($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
	   'name'              => $this->input->post('name'),
       'percentage'        => $this->input->post('percentage'),
       'description'       => $this->input->post('description'),
	   'modified_on'        => date('Y-m-d H:i:s')
	];
	$percentage = $this->input->post('percentage');
    
    if($percentage==100){
        echo json_encode(['success' => false, 'message' => 'discount percentage cannot be 100% because we are giving 40% discount on booking a lab test']);
        return;
    }
    
	// Check if the same data is inserted already
    $name = $this->input->post('name');
    $check_with_same_name = $this->registermodel->common_fetch('lab_test_coupons', ['name' => $name,'id!=' => $id,'delete_status' => 1]);

    if ($check_with_same_name) {
        echo json_encode(['success' => false, 'message' => 'lab test coupon is added already']);
        return;
    }
    $update 	= $this->registermodel->common_update('lab_test_coupons',$data,['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_lab_test_coupon(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
  
    $this->registermodel->common_update('lab_test_coupons', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*lab_test_coupons*/

/*coupons*/

/*hospitals*/
public function hospitals(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospitals');
	$this->load->view('admin/includes/footer');
}
public function get_hospitals(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_hospitals($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_hospitals_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_hospital_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('main_data',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_hospital() {
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }

    $id = $this->input->post('id');
    $base_path = $this->config->item('bharosa_base_path');

    // Helper function to unlink image by field and table
    $unlink_image = function($table, $where, $image_column) use ($base_path) {
        $rows = $this->registermodel->common_fetch_select($table, $where, [$image_column]);
        foreach ($rows as $row) {
            if (!empty($row[$image_column])) {
                $image_path = $base_path . $row[$image_column];
                if (file_exists($image_path)) {
                    unlink($image_path);
                } else {
                    log_message('error', 'File not found: ' . $image_path);
                }
            }
        }
    };

    // Delete hospital logo
    $unlink_image('main_data', ['id' => $id], 'logo');

    // Unlink images from related tables
    $unlink_image('ambulance_drivers', ['main_data_id' => $id], 'image');
    $unlink_image('pr_agents', ['main_data_id' => $id], 'image');
    $unlink_image('doctors', ['main_data_id' => $id], 'image');
    $unlink_image('hospital_diagnostic_packages', ['main_data_id' => $id], 'image');

    // Soft delete entries
    $this->registermodel->common_update('main_data', ['delete_status' => 0], ['id' => $id]);
    $this->registermodel->common_update('ambulance_drivers', ['delete_status' => 0], ['main_data_id' => $id]);
    $this->registermodel->common_update('pr_agents', ['delete_status' => 0], ['main_data_id' => $id]);
    $this->registermodel->common_update('doctors', ['delete_status' => 0], ['main_data_id' => $id]);
    $this->registermodel->common_update('hospital_diagnostic_packages', ['delete_status' => 0], ['main_data_id' => $id]);

    echo json_encode(['success' => true, 'message' => 'Data deleted successfully']);
}
public function public_relation_agents($id){
    check_permission(3);
    $data['id'] = base64_decode($id);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/public_relation_agents',$data);
	$this->load->view('admin/includes/footer');
}
public function get_public_relation_agents($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $id;
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_public_relation_agents($sess_data,$limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_public_relation_agents_count($sess_data,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_public_relation_agent_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('pr_agents',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_public_relation_agent(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('pr_agents',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('pr_agents', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
public function ambulances($id){
    check_permission(3);
    $data['id'] = base64_decode($id);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/ambulances',$data);
	$this->load->view('admin/includes/footer');
}
public function get_ambulances($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $id;
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_ambulances($sess_data,$limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_ambulances_count($sess_data,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_ambulance_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('ambulance_drivers',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function change_work_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('availaibility_status');
    $this->registermodel->common_update('ambulance_drivers',['availability' => $status],['id' => $id]);
    //echo $this->db->last_query();exit;
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_ambulance(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('ambulance_drivers',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('ambulance_drivers', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
public function doctors($id){
    check_permission(3);
    $data['id'] = base64_decode($id);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/doctors',$data);
	$this->load->view('admin/includes/footer');
}
public function get_doctors($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $id;
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_doctors($sess_data,$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_doctors_count($sess_data,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_doctor_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('doctors',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function change_doctor_work_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('availaibility_status');
    $this->registermodel->common_update('doctors',['availability' => $status],['id' => $id]);
    //echo $this->db->last_query();exit;
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_doctor(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('doctors',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('doctors', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
public function diagnostic($id){
    check_permission(3);
    $data['id'] = base64_decode($id);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_diagnostic_packages',$data);
	$this->load->view('admin/includes/footer');
}
public function get_diagnostic($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $id;
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_diagnostic($sess_data,$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_diagnostic_count($sess_data,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function diagnostic_tests($id){
    check_permission(3);
    $data['diagnostic'] = $this->registermodel->common_fetch('hospital_diagnostic_packages',['id' => base64_decode($id)]);
    //print_r($data['diagnostic']);exit;
    $data['tests'] = $this->registermodel->get_tests_by_diagnostic_id($id);
    $data['main_data_id'] = $data['diagnostic'][0]['main_data_id'];
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/diagnostic_tests',$data);
	$this->load->view('admin/includes/footer');
}
public function change_diagnostic_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('hospital_diagnostic_packages',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_diagnostic_package(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('hospital_diagnostic_packages',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('hospital_diagnostic_packages', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
public function update_diagnostic_commission(){
    $hospital_id = $this->input->post('hospital_id');
    $commission = $this->input->post('commission');

    if (!is_numeric($commission) || $commission < 0 || $commission > 100) {
        echo json_encode(['success' => false, 'message' => 'Invalid commission']);
        return;
    }

    $this->db->where('id', $hospital_id);
    $updated = $this->db->update('main_data', ['diagnostics_commission' => $commission]);

    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function update_doctor_commission(){
    $hospital_id = $this->input->post('hospital_idd');
    $commission = $this->input->post('commissionn');

    if (!is_numeric($commission) || $commission < 0 || $commission > 100) {
        echo json_encode(['success' => false, 'message' => 'Invalid commission']);
        return;
    }

    $this->db->where('id', $hospital_id);
    $updated = $this->db->update('main_data', ['doctor_commission' => $commission]);

    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function state_hospitals($id){
    check_permission(3);
    $data['id'] = base64_decode($id);
    $data['count'] = $this->registermodel->common_fetch_rows('main_data',['state_id' => base64_decode($id),'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/state_hospitals',$data);
	$this->load->view('admin/includes/footer');
}
public function get_state_hospitals($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_state_hospitals($id,$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_state_hospitals_count($id,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*hospitals*/

/*pharmacies*/
public function pharmacies(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/pharmacies');
	$this->load->view('admin/includes/footer');
}
public function get_pharmacies(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_pharmacies($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_pharmacies_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_pharmacy_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('pharmacies',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_pharmacy(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    
    $fetch = $this->registermodel->common_fetch('pharmacies',['id' => $id]);

    if (!empty($fetch[0]['logo'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['logo'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }
    
    $this->registermodel->common_update('pharmacies', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
/*pharmacies*/

/*diagnostics*/
public function main_diagnostics(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_diagnostics');
	$this->load->view('admin/includes/footer');
}
public function get_main_diagnostics(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_diagnostics($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_diagnostics_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_main_diagnostic_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('diagnostics',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_main_diagnostic(){
    
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }

    $id = $this->input->post('id');
    $base_path = $this->config->item('bharosa_base_path');

    // Helper function to unlink image by field and table
    $unlink_image = function($table, $where, $image_column) use ($base_path) {
        $rows = $this->registermodel->common_fetch_select($table, $where, [$image_column]);
        foreach ($rows as $row) {
            if (!empty($row[$image_column])) {
                $image_path = $base_path . $row[$image_column];
                if (file_exists($image_path)) {
                    unlink($image_path);
                } else {
                    log_message('error', 'File not found: ' . $image_path);
                }
            }
        }
    };

    // Delete hospital logo
    $unlink_image('diagnostics', ['id' => $id], 'logo');

    // Unlink images from related tables
    $unlink_image('diagnostic_packages', ['main_data_id' => $id], 'image');

    // Soft delete entries
    $this->registermodel->common_update('diagnostics', ['delete_status' => 0], ['id' => $id]);
    $this->registermodel->common_update('diagnostic_packages', ['delete_status' => 0], ['main_data_id' => $id]);
    
    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    
    return;
}
public function main_diagnostic_packages($id){
    check_permission(3);
    $data['id'] = base64_decode($id);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_diagnostic_packages',$data);
	$this->load->view('admin/includes/footer');
}
public function get_main_diagnostic_packages($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $id;
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_diagnostic_packages($sess_data,$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_diagnostic_packages_count($sess_data,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_diagnostic_tests($id){
    check_permission(3);
    $data['diagnostic'] = $this->registermodel->common_fetch('diagnostic_packages',['id' => base64_decode($id)]);
    $data['tests'] = $this->registermodel->get_tests_by_main_diagnostic_id($id);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_diagnostic_tests',$data);
	$this->load->view('admin/includes/footer');
}
public function change_main_diagnostic_package_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('diagnostic_packages',['status' => $status],['id' => $id]);
    //echo $this->db->last_query();exit;
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_main_diagnostic_package(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('diagnostic_packages',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('diagnostic_packages', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
public function update_main_diagnostic_commission(){
    $hospital_id = $this->input->post('hospital_id');
    $commission = $this->input->post('commission');

    if (!is_numeric($commission) || $commission < 0 || $commission > 100) {
        echo json_encode(['success' => false, 'message' => 'Invalid commission']);
        return;
    }

    $this->db->where('id', $hospital_id);
    $updated = $this->db->update('diagnostics', ['diagnostics_commission' => $commission]);

    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function update_main_diagnostic_flat_discount(){
    $hospital_id = $this->input->post('hospital_idd');
    $commission = $this->input->post('commissionn');

    if (!is_numeric($commission) || $commission < 0 || $commission > 99) {
        echo json_encode(['success' => false, 'message' => 'Invalid flat discount']);
        return;
    }

    $this->db->where('id', $hospital_id);
    $updated = $this->db->update('diagnostics', ['diagnostic_flat_discount' => $commission]);

    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*diagnostics*/

/*lab_tests*/
public function lab_tests(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_tests');
	$this->load->view('admin/includes/footer');
}
public function get_lab_tests(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_lab_tests($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_lab_tests_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_lab_test_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('lab_tests',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_lab_test(){
    
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }

    $id = $this->input->post('id');
    $base_path = $this->config->item('bharosa_base_path');

    // Helper function to unlink image by field and table
    $unlink_image = function($table, $where, $image_column) use ($base_path) {
        $rows = $this->registermodel->common_fetch_select($table, $where, [$image_column]);
        foreach ($rows as $row) {
            if (!empty($row[$image_column])) {
                $image_path = $base_path . $row[$image_column];
                if (file_exists($image_path)) {
                    unlink($image_path);
                } else {
                    log_message('error', 'File not found: ' . $image_path);
                }
            }
        }
    };

    // Delete hospital logo
    $unlink_image('lab_tests', ['id' => $id], 'logo');

    // Unlink images from related tables
    $unlink_image('lab_agents', ['main_data_id' => $id], 'image');
    $unlink_image('lab_packages', ['main_data_id' => $id], 'image');

    // Soft delete entries
    $this->registermodel->common_update('lab_tests', ['delete_status' => 0], ['id' => $id]);
    $this->registermodel->common_update('lab_agents', ['delete_status' => 0], ['main_data_id' => $id]);
    $this->registermodel->common_update('lab_packages', ['delete_status' => 0], ['main_data_id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    
    return;
}
public function lab_agents($id){
    check_permission(3);
    $data['id'] = base64_decode($id);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_agents',$data);
	$this->load->view('admin/includes/footer');
}
public function get_lab_agents($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $id;
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_lab_agents($sess_data,$limit,$start,$search);
    
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_lab_agents_count($sess_data,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_lab_agent_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('lab_agents',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_lab_agent(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('lab_agents',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('lab_agents', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
public function lab_test_packages($id){
    check_permission(3);
    $data['id'] = base64_decode($id);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_test_packages',$data);
	$this->load->view('admin/includes/footer');
}
public function get_lab_test_packages($id){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $id;
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_lab_test_packages($sess_data,$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_lab_test_packages_count($sess_data,$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_lab_tests($id){
    check_permission(3);
    $data['diagnostic'] = $this->registermodel->common_fetch('lab_packages',['id' => base64_decode($id)]);
    $data['tests'] = $this->registermodel->get_tests_by_main_lab_id($id);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_lab_tests',$data);
	$this->load->view('admin/includes/footer');
}
public function change_lab_test_package_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('lab_packages',['status' => $status],['id' => $id]);
    //echo $this->db->last_query();exit;
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_lab_test_package(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $fetch = $this->registermodel->common_fetch('lab_packages',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }

    $this->registermodel->common_update('lab_packages', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
public function update_main_lab_commission(){
    $hospital_id = $this->input->post('hospital_id');
    $commission = $this->input->post('commission');

    if (!is_numeric($commission) || $commission < 0 || $commission > 100) {
        echo json_encode(['success' => false, 'message' => 'Invalid commission']);
        return;
    }

    $this->db->where('id', $hospital_id);
    $updated = $this->db->update('lab_tests', ['lab_commission' => $commission]);

    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function update_main_lab_flat_discount(){
    $hospital_id = $this->input->post('hospital_idd');
    $commission = $this->input->post('commissionn');

    if (!is_numeric($commission) || $commission < 0 || $commission > 99) {
        echo json_encode(['success' => false, 'message' => 'Invalid flat discount']);
        return;
    }

    $this->db->where('id', $hospital_id);
    $updated = $this->db->update('lab_tests', ['lab_test_flat_discount' => $commission]);

    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*lab_tests*/

/*online_doctors*/
public function online_doctors(){
    check_permission(3);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctors');
	$this->load->view('admin/includes/footer');
}
public function get_online_doctors(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_online_doctors($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_online_doctors_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function change_online_doctor_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('status');
    $this->registermodel->common_update('online_doctors',['status' => $status],['id' => $id]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function change_online_doctor_work_status(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    $status = $this->input->post('availaibility_status');
    $this->registermodel->common_update('online_doctors',['availability' => $status],['id' => $id]);
    //echo $this->db->last_query();exit;
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
public function delete_online_doctor(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $id = $this->input->post('id');
    
    $fetch = $this->registermodel->common_fetch('online_doctors',['id' => $id]);

    if (!empty($fetch[0]['image'])) {
        $image_path = $this->config->item('bharosa_base_path') . $fetch[0]['image'];

        if (file_exists($image_path)) {
            unlink($image_path);
        } else {
            log_message('error', 'File not found: ' . $image_path);
        }
    }
    
    $this->registermodel->common_update('online_doctors', ['delete_status' => 0], ['id' => $id]);

    echo json_encode(['success' => true, 'message' => 'data deleted successfully']);
    return;
}
public function update_online_doctor_commission(){
    $hospital_id = $this->input->post('hospital_id');
    $commission = $this->input->post('commission');

    if (!is_numeric($commission) || $commission < 0 || $commission > 100) {
        echo json_encode(['success' => false, 'message' => 'Invalid commission']);
        return;
    }

    $this->db->where('id', $hospital_id);
    $updated = $this->db->update('online_doctors', ['doctor_commission' => $commission]);

    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*online_doctors*/

/*ambulance_bookings*/
public function ongoing_ambulance_bookings(){
    check_permission(4);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/ongoing_ambulance_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_ongoing_ambulance_bookings(){
    if (!has_access(4)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_ongoing_ambulance_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_ongoing_ambulance_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function completed_ambulance_bookings(){
    check_permission(4);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/completed_ambulance_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_completed_ambulance_bookings(){
    if (!has_access(4)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_ambulance_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_ambulance_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*ambulance_bookings*/

/*admit_bookings*/
public function ongoing_admit_bookings(){
    check_permission(5);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/ongoing_admit_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_ongoing_admit_bookings(){
    if (!has_access(5)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_ongoing_admit_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_ongoing_admit_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function completed_admit_bookings(){
    check_permission(5);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/completed_admit_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_completed_admit_bookings(){
    if (!has_access(5)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_admit_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_admit_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function admit_reports($id){
    check_permission(5);
    $sess_data = $this->session_data();
    $data['id']  =  $id;
    $booking_details = $this->registermodel->common_fetch('admit_bookings',['id' => base64_decode($id)]);
    $data['booking_id'] = $booking_details[0]['booking_id'];
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/admit_reports',$data);
	$this->load->view('admin/includes/footer');
}
public function get_admit_reports($id){
    if (!has_access(5)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $booking_details = $this->registermodel->common_fetch('admit_bookings',['id' => base64_decode($id)]);
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_admit_reports($booking_details[0]['booking_id'],$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_admit_reports_count($booking_details[0]['booking_id'],$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*admit_bookings*/

/*op_bookings*/
public function ongoing_op_bookings(){
    check_permission(6);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/ongoing_op_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_ongoing_op_bookings(){
    if (!has_access(6)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_ongoing_op_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_ongoing_op_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function completed_op_bookings(){
    check_permission(6);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/completed_op_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_completed_op_bookings(){
    if (!has_access(6)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_op_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_op_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*op_bookings*/

/*doctor_bookings*/
public function ongoing_doctor_bookings(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/ongoing_doctor_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_ongoing_doctor_bookings(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_ongoing_doctor_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_ongoing_doctor_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function completed_doctor_bookings(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/completed_doctor_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_completed_doctor_bookings(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_doctor_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_doctor_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*doctor_bookings*/

/*pharmacy_prescription_bookings*/
public function ongoing_pharmacy_prescription_bookings(){
    check_permission(8);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/ongoing_pharmacy_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_ongoing_pharmacy_prescription_bookings(){
    if (!has_access(8)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_ongoing_pharmacy_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_ongoing_pharmacy_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function completed_pharmacy_prescription_bookings(){
    check_permission(8);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/completed_pharmacy_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_completed_pharmacy_prescription_bookings(){
    if (!has_access(8)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_pharmacy_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_pharmacy_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*pharmacy_prescription_bookings*/

/*diagnostic_bookings*/
public function ongoing_diagnostic_bookings(){
    check_permission(9);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/ongoing_diagnostic_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_ongoing_diagnostic_bookings(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_ongoing_diagnostic_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_ongoing_diagnostic_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function completed_diagnostic_bookings(){
    check_permission(9);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/completed_diagnostic_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_completed_diagnostic_bookings(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_diagnostic_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_diagnostic_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function diagnostic_bookings_reports($id){
    check_permission(9);
    $sess_data = $this->session_data();
    $data['id']  =  $id;
    $booking_details = $this->registermodel->common_fetch('hospital_diagnostic_bookings',['id' => base64_decode($id)]);
    $data['booking_id'] = $booking_details[0]['booking_id'];
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/diagnostic_bookings_reports',$data);
	$this->load->view('admin/includes/footer');
}
public function get_diagnostic_bookings_reports($id){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $booking_details = $this->registermodel->common_fetch('hospital_diagnostic_bookings',['id' => base64_decode($id)]);
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_diagnostic_bookings_reports($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_diagnostic_bookings_reports_count($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*diagnostic_bookings*/

/*diagnostic_prescription_bookings*/
public function ongoing_diagnostic_prescription_bookings(){
    check_permission(10);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/ongoing_diagnostic_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_ongoing_diagnostic_prescription_bookings(){
    if (!has_access(10)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_ongoing_diagnostic_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_ongoing_diagnostic_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function completed_diagnostic_prescription_bookings(){
    check_permission(10);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/completed_diagnostic_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_completed_diagnostic_prescription_bookings(){
    if (!has_access(10)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_diagnostic_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_diagnostic_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function diagnostic_prescription_bookings_reports($id){
    check_permission(10);
    $sess_data = $this->session_data();
    $data['id']  =  $id;
    $booking_details = $this->registermodel->common_fetch('hospital_diagnostic_prescription_bookings',['id' => base64_decode($id)]);
    $data['booking_id'] = $booking_details[0]['booking_id'];
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/diagnostic_prescription_bookings_reports',$data);
	$this->load->view('admin/includes/footer');
}
public function get_diagnostic_prescription_bookings_reports($id){
    if (!has_access(10)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $booking_details = $this->registermodel->common_fetch('hospital_diagnostic_prescription_bookings',['id' => base64_decode($id)]);
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_completed_diagnostic_prescription_bookings_reports($sess_data,$booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_completed_diagnostic_prescription_bookings_reports_count($sess_data,$booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*diagnostic_prescription_bookings*/

/*main_pharmacy_prescription_bookings*/
public function main_ongoing_pharmacy_prescription_bookings(){
    check_permission(8);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_ongoing_pharmacy_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_ongoing_pharmacy_prescription_bookings(){
    if (!has_access(8)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_ongoing_pharmacy_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_ongoing_pharmacy_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_completed_pharmacy_prescription_bookings(){
    check_permission(8);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_completed_pharmacy_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_completed_pharmacy_prescription_bookings(){
    if (!has_access(8)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_completed_pharmacy_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_completed_pharmacy_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*pharmacy_prescription_bookings*/

/*main_diagnostic_bookings*/
public function main_ongoing_diagnostic_bookings(){
    check_permission(9);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_ongoing_diagnostic_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_ongoing_diagnostic_bookings(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_ongoing_diagnostic_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_ongoing_diagnostic_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_completed_diagnostic_bookings(){
    check_permission(9);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_completed_diagnostic_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_completed_diagnostic_bookings(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_completed_diagnostic_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_completed_diagnostic_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_diagnostic_bookings_reports($id){
    check_permission(9);
    $sess_data = $this->session_data();
    $data['id']  =  $id;
    $booking_details = $this->registermodel->common_fetch('diagnostic_bookings',['id' => base64_decode($id)]);
    $data['booking_id'] = $booking_details[0]['booking_id'];
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_diagnostic_bookings_reports',$data);
	$this->load->view('admin/includes/footer');
}
public function get_main_diagnostic_bookings_reports($id){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $booking_details = $this->registermodel->common_fetch('diagnostic_bookings',['id' => base64_decode($id)]);
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_completed_diagnostic_bookings_reports($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_completed_diagnostic_bookings_reports_count($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*main_diagnostic_bookings*/

/*main_diagnostic_prescription_bookings*/
public function main_ongoing_diagnostic_prescription_bookings(){
    check_permission(10);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_ongoing_diagnostic_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_ongoing_diagnostic_prescription_bookings(){
    if (!has_access(10)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_ongoing_diagnostic_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_ongoing_diagnostic_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_completed_diagnostic_prescription_bookings(){
    check_permission(10);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_completed_diagnostic_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_completed_diagnostic_prescription_bookings(){
    if (!has_access(10)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_completed_diagnostic_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_completed_diagnostic_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_diagnostic_prescription_bookings_reports($id){
    check_permission(10);
    $sess_data = $this->session_data();
    $data['id']  =  $id;
    $booking_details = $this->registermodel->common_fetch('diagnostic_prescription_bookings',['id' => base64_decode($id)]);
    $data['booking_id'] = $booking_details[0]['booking_id'];
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_diagnostic_prescription_bookings_reports',$data);
	$this->load->view('admin/includes/footer');
}
public function get_main_diagnostic_prescription_bookings_reports($id){
    if (!has_access(10)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $booking_details = $this->registermodel->common_fetch('diagnostic_prescription_bookings',['id' => base64_decode($id)]);
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_completed_diagnostic_prescription_bookings_reports($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_completed_diagnostic_prescription_bookings_reports_count($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*main_diagnostic_prescription_bookings*/

/*main_lab_test_bookings*/
public function main_ongoing_lab_test_bookings(){
    check_permission(9);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_ongoing_lab_test_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_ongoing_lab_test_bookings(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_ongoing_lab_test_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_ongoing_lab_test_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_completed_lab_test_bookings(){
    check_permission(9);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_completed_lab_test_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_completed_lab_test_bookings(){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_completed_lab_test_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_completed_lab_test_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_lab_test_bookings_reports($id){
    check_permission(9);
    $sess_data = $this->session_data();
    $data['id']  =  $id;
    $booking_details = $this->registermodel->common_fetch('lab_test_bookings',['id' => base64_decode($id)]);
    $data['booking_id'] = $booking_details[0]['booking_id'];
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_lab_test_bookings_reports',$data);
	$this->load->view('admin/includes/footer');
}
public function get_main_lab_test_bookings_reports($id){
    if (!has_access(9)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $booking_details = $this->registermodel->common_fetch('lab_test_bookings',['id' => base64_decode($id)]);
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_completed_lab_test_bookings_reports($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_completed_lab_test_bookings_reports_count($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*main_lab_test_bookings*/

/*main_lab_test_prescription_bookings*/
public function main_ongoing_lab_test_prescription_bookings(){
    check_permission(10);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_ongoing_lab_test_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_ongoing_lab_test_prescription_bookings(){
    if (!has_access(10)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_ongoing_lab_test_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_ongoing_lab_test_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_completed_lab_test_prescription_bookings(){
    check_permission(10);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_completed_lab_test_prescription_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_main_completed_lab_test_prescription_bookings(){
    if (!has_access(10)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_completed_lab_test_prescription_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_completed_lab_test_prescription_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function main_lab_test_prescription_bookings_reports($id){
    check_permission(10);
    $sess_data = $this->session_data();
    $data['id']  =  $id;
    $booking_details = $this->registermodel->common_fetch('lab_test_prescription_bookings',['id' => base64_decode($id)]);
    $data['booking_id'] = $booking_details[0]['booking_id'];
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/main_lab_test_prescription_bookings_reports',$data);
	$this->load->view('admin/includes/footer');
}
public function get_main_lab_test_prescription_bookings_reports($id){
    if (!has_access(10)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    $booking_details = $this->registermodel->common_fetch('lab_test_prescription_bookings',['id' => base64_decode($id)]);
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_main_completed_lab_test_prescription_bookings_reports($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_main_completed_lab_test_prescription_bookings_reports_count($booking_details[0]['booking_id'],$booking_details[0]['booking_type'],$search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*main_lab_test_prescription_bookings*/

/*online_doctor_ongoing_doctor_bookings*/
public function online_doctor_ongoing_doctor_bookings(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctor_ongoing_doctor_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_online_doctor_ongoing_doctor_bookings(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_online_doctor_ongoing_doctor_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_online_doctor_ongoing_doctor_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function online_doctor_completed_doctor_bookings(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctor_completed_doctor_bookings');
	$this->load->view('admin/includes/footer');
}
public function get_online_doctor_completed_doctor_bookings(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_online_doctor_completed_doctor_bookings($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_online_doctor_completed_doctor_bookings_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*online_doctor_ongoing_doctor_bookings*/

/*contact_us*/

/*user_contact_us*/
public function user_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/user_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_user_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_user_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_user_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*user_contact_us*/

/*hospital_contact_us*/
public function hospital_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_hospital_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_hospital_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_hospital_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*hospital_contact_us*/

/*hospital_doctor_contact_us*/
public function hospital_doctor_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_doctor_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_hospital_doctor_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_hospital_doctor_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_hospital_doctor_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*hospital_doctor_contact_us*/

/*hospital_ambulance_driver_contact_us*/
public function hospital_ambulance_driver_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_ambulance_driver_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_hospital_ambulance_driver_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_hospital_ambulance_driver_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_hospital_ambulance_driver_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*hospital_doctor_contact_us*/

/*pharmacy_contact_us*/
public function pharmacy_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/pharmacy_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_pharmacy_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_pharmacy_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_pharmacy_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*pharmacy_contact_us*/

/*diagnostic_contact_us*/
public function diagnostic_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/diagnostic_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_diagnostic_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_diagnostic_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_diagnostic_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*diagnostic_contact_us*/

/*lab_test_contact_us*/
public function lab_test_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_test_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_lab_test_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_lab_test_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_lab_test_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*lab_test_contact_us*/

/*lab_agent_contact_us*/
public function lab_agent_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_agent_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_lab_agent_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_lab_agent_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_lab_agent_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*lab_agent_contact_us*/

/*online_doctor_contact_us*/
public function online_doctor_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctor_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_online_doctor_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_online_doctor_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_online_doctor_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*online_doctor_contact_us*/

/*executive_contact_us*/
public function executive_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/executive_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_executive_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_executive_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_executive_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*executive_contact_us*/

/*regional_manager_contact_us*/
public function regional_manager_contact_us(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/regional_manager_contact_us');
	$this->load->view('admin/includes/footer');
}
public function get_regional_manager_contact_us(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_regional_manager_contact_us($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_regional_manager_contact_us_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
/*regional_manager_contact_us*/

/*contact_us*/

/*notifications*/

/*user_notifications*/
public function user_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/user_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_user_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_user_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_user_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_user_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_user_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_user_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $user_id    = $this->input->post('user_id'); // this is actually user_id
    $title      = trim($this->input->post('title'));
    $message    = trim($this->input->post('message'));

    if (empty($user_id) || empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($user_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('user_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_users($title, $message);

    } else {
        // Get user user_id and player_id
        $user = $this->db->get_where('users', ['id' => $user_id])->row();

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }

        // Insert specific user notification
        $this->db->insert('user_notifications', [
            'member_id'   => $user->id,
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send push to OneSignal
        $this->registermodel->send_to_single_user($user->id, $title, $message);
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*user_notifications*/

/*hospital_notifications*/
public function hospital_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_hospital_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_hospital_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_hospital_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_hospital_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_hospital_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_hospital_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $user_id    = $this->input->post('user_id'); // this is actually user_id
    $title      = trim($this->input->post('title'));
    $message    = trim($this->input->post('message'));

    if (empty($user_id) || empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($user_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('main_data_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_hospitals($title, $message);

    } else {
        // Get  user_id and player_id
        $user = $this->db->get_where('main_data', ['id' => $user_id])->row();

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }

        // Insert specific user notification
        $this->db->insert('main_data_notifications', [
            'member_id'   => $user->id,
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send push to OneSignal
        $this->registermodel->send_to_single_hospital($user->id, $title, $message);
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*hospital_notifications*/

/*hospital_doctor_notifications*/
public function hospital_doctor_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_doctor_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_hospital_doctor_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_hospital_doctor_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_hospital_doctor_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_hospital_doctor_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_hospital_doctor_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function get_doctors_by_hospital(){
    $hospital_id = $this->input->post('hospital_id');
    $doctors = $this->db->get_where('doctors', ['main_data_id' => $hospital_id])->result_array();

    echo json_encode($doctors);
}
// public function insert_hospital_doctor_notifications(){
//     if (!has_access(11)) {
//         echo json_encode([
//             'success' => false,
//             'message' => 'Unauthorized access'
//         ]);
//         return;
//     }
//     $hospital_id    = $this->input->post('hospital_id'); // this is actually user_id
//     $user_id    = $this->input->post('user_id'); // this is actually user_id
//     $title      = trim($this->input->post('title'));
//     $message    = trim($this->input->post('message'));

//     if (empty($user_id) || empty($title) || empty($message)) {
//         echo json_encode(['success' => false, 'message' => 'All fields are required']);
//         return;
//     }

//     //$this->load->model('Notification_model');

//     // Case: Send to all doctors
//     if ($user_id === 'all') {
//         // Insert one row with 'all' as member_id
//         $this->db->insert('doctor_notifications', [
//             'member_id'   => 'all',
//             'title'       => $title,
//             'message'     => $message,
//             //'type'        => 'hospital_doctor',
//             'read_status' => 0,
//             'created_on'  => date('Y-m-d H:i:s')
//         ]);

//         // Send notification to OneSignal tag (e.g., "hospital_doctor")
//         $this->registermodel->send_to_all_hospital_doctors($hospital_id,$title, $message);

//     } else {
//         // Get  user_id and player_id
//         $user = $this->db->get_where('doctors', ['id' => $user_id])->row();

//         if (!$user) {
//             echo json_encode(['success' => false, 'message' => 'User not found']);
//             return;
//         }

//         // Insert specific user notification
//         $this->db->insert('doctor_notifications', [
//             'member_id'   => $user->id,
//             'title'       => $title,
//             'message'     => $message,
//             //'type'        => 'hospital_doctor',
//             'read_status' => 0,
//             'created_on'  => date('Y-m-d H:i:s')
//         ]);

//         // Send push to OneSignal
//         $this->registermodel->send_to_single_hospital_doctor($user->id, $title, $message);
//     }

//     echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
// }
public function insert_hospital_doctor_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $hospital_id    = $this->input->post('hospital_id'); // this is actually user_id
    $user_id        = $this->input->post('user_id'); // this is actually user_id
    $title          = trim($this->input->post('title'));
    $message        = trim($this->input->post('message'));

    if (/*empty($user_id) || */empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($hospital_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('doctor_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_hospital_doctors($title, $message);

    }elseif($hospital_id !='all'){
        if($user_id=='all'){
            // Get  user_id and player_id
            $user = $this->db->get_where('doctors', ['id' => $user_id])->row();
    
            if (!$user) {
                echo json_encode(['success' => false, 'message' => 'User not found']);
                return;
            }
    
            // Insert specific user notification
            $this->db->insert('doctor_notifications', [
                'member_id'   => $user->id,
                'title'       => $title,
                'message'     => $message,
                //'type'        => 'hospital_doctor',
                'read_status' => 0,
                'created_on'  => date('Y-m-d H:i:s')
            ]);
    
            // Send push to OneSignal
            $this->registermodel->send_to_single_hospital_doctor($user->id, $title, $message);
        }else{
           // Get  user_id and player_id
            $user = $this->db->get_where('doctors', ['id' => $user_id])->row();
    
            if (!$user) {
                echo json_encode(['success' => false, 'message' => 'User not found']);
                return;
            }
    
            // Insert specific user notification
            $this->db->insert('doctor_notifications', [
                'member_id'   => $user->id,
                'title'       => $title,
                'message'     => $message,
                //'type'        => 'hospital_doctor',
                'read_status' => 0,
                'created_on'  => date('Y-m-d H:i:s')
            ]);
    
            // Send push to OneSignal
            $this->registermodel->send_to_single_hospital_doctor($user->id, $title, $message); 
        }
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*hospital_doctor_notifications*/

/*hospital_ambulance_notifications*/
public function hospital_ambulance_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_ambulance_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_hospital_ambulance_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_hospital_ambulance_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_hospital_ambulance_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_hospital_ambulance_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_hospital_ambulance_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function get_drivers_by_hospital(){
    $hospital_id = $this->input->post('hospital_id');
    $doctors = $this->db->get_where('ambulance_drivers', ['main_data_id' => $hospital_id])->result_array();

    echo json_encode($doctors);
}
public function insert_hospital_ambulance_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $hospital_id    = $this->input->post('hospital_id'); // this is actually user_id
    $user_id        = $this->input->post('user_id'); // this is actually user_id
    $title          = trim($this->input->post('title'));
    $message        = trim($this->input->post('message'));

    if (/*empty($user_id) || */empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($hospital_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('driver_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_hospital_drivers($title, $message);

    }elseif($hospital_id !='all'){
        if($user_id=='all'){
            // Get  user_id and player_id
            $user = $this->db->get_where('ambulance_drivers', ['id' => $user_id])->row();
    
            if (!$user) {
                echo json_encode(['success' => false, 'message' => 'User not found']);
                return;
            }
    
            // Insert specific user notification
            $this->db->insert('driver_notifications', [
                'member_id'   => $user->id,
                'title'       => $title,
                'message'     => $message,
                //'type'        => 'hospital_doctor',
                'read_status' => 0,
                'created_on'  => date('Y-m-d H:i:s')
            ]);
    
            // Send push to OneSignal
            $this->registermodel->send_to_single_hospital_driver($user->id, $title, $message);
        }else{
           // Get  user_id and player_id
            $user = $this->db->get_where('ambulance_drivers', ['id' => $user_id])->row();
    
            if (!$user) {
                echo json_encode(['success' => false, 'message' => 'User not found']);
                return;
            }
    
            // Insert specific user notification
            $this->db->insert('driver_notifications', [
                'member_id'   => $user->id,
                'title'       => $title,
                'message'     => $message,
                //'type'        => 'hospital_doctor',
                'read_status' => 0,
                'created_on'  => date('Y-m-d H:i:s')
            ]);
    
            // Send push to OneSignal
            $this->registermodel->send_to_single_hospital_driver($user->id, $title, $message); 
        }
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*hospital_ambulance_notifications*/

/*pharmacy_notifications*/
public function pharmacy_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/pharmacy_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_pharmacy_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_pharmacy_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_pharmacy_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_pharmacy_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('pharmacies',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_pharmacy_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_pharmacy_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $user_id    = $this->input->post('user_id'); // this is actually user_id
    $title      = trim($this->input->post('title'));
    $message    = trim($this->input->post('message'));

    if (empty($user_id) || empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($user_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('pharmacy_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_pharmacies($title, $message);

    } else {
        // Get  user_id and player_id
        $user = $this->db->get_where('pharmacies', ['id' => $user_id])->row();

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }

        // Insert specific user notification
        $this->db->insert('pharmacy_notifications', [
            'member_id'   => $user->id,
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send push to OneSignal
        $this->registermodel->send_to_single_pharmacy($user->id, $title, $message);
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*pharmacy_notifications*/

/*diagnostic_notifications*/
public function diagnostic_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/diagnostic_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_diagnostic_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_diagnostic_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_diagnostic_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_diagnostic_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('diagnostics',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_diagnostic_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_diagnostic_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $user_id    = $this->input->post('user_id'); // this is actually user_id
    $title      = trim($this->input->post('title'));
    $message    = trim($this->input->post('message'));

    if (empty($user_id) || empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($user_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('diagnostic_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_diagnostics($title, $message);

    } else {
        // Get  user_id and player_id
        $user = $this->db->get_where('diagnostics', ['id' => $user_id])->row();

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }

        // Insert specific user notification
        $this->db->insert('diagnostic_notifications', [
            'member_id'   => $user->id,
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send push to OneSignal
        $this->registermodel->send_to_single_diagnostic($user->id, $title, $message);
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*diagnostic_notifications*/

/*lab_test_notifications*/
public function lab_test_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_test_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_lab_test_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_lab_test_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_lab_test_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_lab_test_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('lab_tests',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_lab_test_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_lab_test_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $user_id    = $this->input->post('user_id'); // this is actually user_id
    $title      = trim($this->input->post('title'));
    $message    = trim($this->input->post('message'));

    if (empty($user_id) || empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($user_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('lab_test_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_lab_tests($title, $message);

    } else {
        // Get  user_id and player_id
        $user = $this->db->get_where('lab_tests', ['id' => $user_id])->row();

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }

        // Insert specific user notification
        $this->db->insert('lab_test_notifications', [
            'member_id'   => $user->id,
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send push to OneSignal
        $this->registermodel->send_to_single_lab_test($user->id, $title, $message);
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*lab_test_notifications*/

/*lab_agent_notifications*/
public function lab_agent_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_agent_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_lab_agent_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_lab_agent_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_lab_agent_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_lab_agent_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['hospitals'] = $this->registermodel->common_fetch('lab_tests',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_lab_agent_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function get_agents_by_lab(){
    $hospital_id = $this->input->post('hospital_id');
    $doctors = $this->db->get_where('lab_agents', ['main_data_id' => $hospital_id])->result_array();

    echo json_encode($doctors);
}
public function insert_lab_agent_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $hospital_id    = $this->input->post('hospital_id'); // this is actually user_id
    $user_id        = $this->input->post('user_id'); // this is actually user_id
    $title          = trim($this->input->post('title'));
    $message        = trim($this->input->post('message'));

    if (/*empty($user_id) || */empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($hospital_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('lab_agent_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_lab_agents($title, $message);

    }elseif($hospital_id !='all'){
        if($user_id=='all'){
            // Get  user_id and player_id
            $user = $this->db->get_where('lab_agents', ['id' => $user_id])->row();
    
            if (!$user) {
                echo json_encode(['success' => false, 'message' => 'User not found']);
                return;
            }
    
            // Insert specific user notification
            $this->db->insert('lab_agent_notifications', [
                'member_id'   => $user->id,
                'title'       => $title,
                'message'     => $message,
                //'type'        => 'hospital_doctor',
                'read_status' => 0,
                'created_on'  => date('Y-m-d H:i:s')
            ]);
    
            // Send push to OneSignal
            $this->registermodel->send_to_single_lab_agent($user->id, $title, $message);
        }else{
           // Get  user_id and player_id
            $user = $this->db->get_where('lab_agents', ['id' => $user_id])->row();
    
            if (!$user) {
                echo json_encode(['success' => false, 'message' => 'User not found']);
                return;
            }
    
            // Insert specific user notification
            $this->db->insert('lab_agent_notifications', [
                'member_id'   => $user->id,
                'title'       => $title,
                'message'     => $message,
                //'type'        => 'hospital_doctor',
                'read_status' => 0,
                'created_on'  => date('Y-m-d H:i:s')
            ]);
    
            // Send push to OneSignal
            $this->registermodel->send_to_single_lab_agent($user->id, $title, $message); 
        }
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*lab_agent_notifications*/

/*online_doctor_notifications*/
public function online_doctor_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctor_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_online_doctor_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_online_doctor_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_online_doctor_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_online_doctor_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('online_doctors',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_online_doctor_notifications',$data);
	$this->load->view('admin/includes/footer');
}
// public function insert_online_doctor_notifications(){
//     if (!has_access(11)) {
//         echo json_encode([
//             'success' => false,
//             'message' => 'Unauthorized access'
//         ]);
//         return;
//     }
//     $user_id    = $this->input->post('user_id'); // this is actually user_id
//     $title      = trim($this->input->post('title'));
//     $message    = trim($this->input->post('message'));

//     if (empty($user_id) || empty($title) || empty($message)) {
//         echo json_encode(['success' => false, 'message' => 'All fields are required']);
//         return;
//     }

//     //$this->load->model('Notification_model');

//     // Case: Send to all doctors
//     if ($user_id === 'all') {
//         // Insert one row with 'all' as member_id
//         $this->db->insert('online_doctor_notifications', [
//             'member_id'   => 'all',
//             'title'       => $title,
//             'message'     => $message,
//             //'type'        => 'hospital_doctor',
//             'read_status' => 0,
//             'created_on'  => date('Y-m-d H:i:s')
//         ]);

//         // Send notification to OneSignal tag (e.g., "hospital_doctor")
//         $this->registermodel->send_to_all_online_doctors($title, $message);

//     } else {
//         // Get  user_id and player_id
//         $user = $this->db->get_where('online_doctors', ['id' => $user_id])->row();

//         if (!$user) {
//             echo json_encode(['success' => false, 'message' => 'User not found']);
//             return;
//         }

//         // Insert specific user notification
//         $this->db->insert('online_doctor_notifications', [
//             'member_id'   => $user->id,
//             'title'       => $title,
//             'message'     => $message,
//             //'type'        => 'hospital_doctor',
//             'read_status' => 0,
//             'created_on'  => date('Y-m-d H:i:s')
//         ]);

//         // Send push to OneSignal
//         $this->registermodel->send_to_single_online_doctor($user->id, $title, $message);
//     }

//     echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
// }
public function insert_online_doctor_notifications(){
    if (!has_access(11)) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
        return;
    }

    $user_id = $this->input->post('user_id');
    $title   = trim($this->input->post('title'));
    $message = trim($this->input->post('message'));

    if (empty($user_id) || empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    // Case 1: Send to all doctors
    if ($user_id === 'all') {

        // Insert one notification row (for DB tracking)
        $this->db->insert('online_doctor_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Fetch all doctors
        $doctors = $this->db->get('online_doctors')->where(['status' => 1,'delete_status' => 1])->result();

        $android_doctors = [];
        $ios_doctors = [];

        foreach ($doctors as $doc) {
            if (!empty($doc->ios_version)) {
                $ios_doctors[] = $doc;
            } else {
                $android_doctors[] = $doc;
            }
        }

        // Send separately
        if (!empty($android_doctors)) {
            $this->registermodel->send_to_all_online_doctors($title, $message, 'android');
        }
        if (!empty($ios_doctors)) {
            $this->registermodel->send_to_all_online_doctors($title, $message, 'ios');
        }

    } else {
        // Case 2: Send to a specific doctor
        $user = $this->db->get_where('online_doctors', ['id' => $user_id])->row();

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }

        // Insert notification
        $this->db->insert('online_doctor_notifications', [
            'member_id'   => $user->id,
            'title'       => $title,
            'message'     => $message,
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Determine platform
        $platform = (!empty($user->ios_version)) ? 'ios' : 'android';

        // Send to that doctor
        $this->registermodel->send_to_single_online_doctor($user->id, $title, $message, $platform);
    }//exit;

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}

/*online_doctor_notifications*/

/*executive_notifications*/
public function executive_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/executive_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_executive_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_executive_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_executive_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_executive_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('executives',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_executive_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_executive_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $user_id    = $this->input->post('user_id'); // this is actually user_id
    $title      = trim($this->input->post('title'));
    $message    = trim($this->input->post('message'));

    if (empty($user_id) || empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($user_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('executive_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_executives($title, $message);

    } else {
        // Get  user_id and player_id
        $user = $this->db->get_where('executives', ['id' => $user_id])->row();

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }

        // Insert specific user notification
        $this->db->insert('executive_notifications', [
            'member_id'   => $user->id,
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send push to OneSignal
        $this->registermodel->send_to_single_executive($user->id, $title, $message);
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*executive_notifications*/

/*regional_manager_notifications*/
public function regional_manager_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/regional_manager_notifications');
	$this->load->view('admin/includes/footer');
}
public function get_regional_manager_notifications(){
    if (!has_access(7)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $sess_data = $this->session_data();
    
    $limit  = $this->input->post("length"); // Number of records per page
    $start  = $this->input->post("start"); // Offset
    $search = $this->input->post("search")["value"] ?? ""; // Search Query

    //echo $search;exit;
    
    // Get Users with Pagination
    $data = $this->registermodel->get_regional_manager_notifications($limit,$start,$search);
    //echo $this->db->last_query();exit;
    // Get Total Users Count
    $totalRecords = $this->registermodel->get_regional_manager_notifications_count($search);

    // Return Response
    $response = [
        "draw" => intval($this->input->post("draw")),
        "recordsTotal" => $totalRecords,
        "recordsFiltered" => $totalRecords,
        "data" => $data
    ];

    echo json_encode($response);
}
public function send_regional_manager_notifications(){
    check_permission(7);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('regional_managers',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/add_regional_manager_notifications',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_regional_manager_notifications(){
    if (!has_access(11)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
    $user_id    = $this->input->post('user_id'); // this is actually user_id
    $title      = trim($this->input->post('title'));
    $message    = trim($this->input->post('message'));

    if (empty($user_id) || empty($title) || empty($message)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        return;
    }

    //$this->load->model('Notification_model');

    // Case: Send to all doctors
    if ($user_id === 'all') {
        // Insert one row with 'all' as member_id
        $this->db->insert('regional_manager_notifications', [
            'member_id'   => 'all',
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send notification to OneSignal tag (e.g., "hospital_doctor")
        $this->registermodel->send_to_all_regional_managers($title, $message);

    } else {
        // Get  user_id and player_id
        $user = $this->db->get_where('regional_managers', ['id' => $user_id])->row();

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }

        // Insert specific user notification
        $this->db->insert('regional_manager_notifications', [
            'member_id'   => $user->id,
            'title'       => $title,
            'message'     => $message,
            //'type'        => 'hospital_doctor',
            'read_status' => 0,
            'created_on'  => date('Y-m-d H:i:s')
        ]);

        // Send push to OneSignal
        $this->registermodel->send_to_single_regional_manager($user->id, $title, $message);
    }

    echo json_encode(['success' => true, 'message' => 'Notification sent successfully']);
}
/*regional_manager_notifications*/

/*notifications*/

/*content_pages*/

/*terms*/
public function terms(){
    check_permission(3);
    $data['terms'] = $this->registermodel->common_fetch('terms',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/terms',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_terms_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('terms',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*terms*/

/*privacy*/
public function privacy(){
    check_permission(3);
    $data['privacy'] = $this->registermodel->common_fetch('privacy',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/privacy',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_privacy_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('privacy',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*privacy*/

/*about_us*/
public function about_us(){
    check_permission(3);
    $data['about_us'] = $this->registermodel->common_fetch('about_us',['id' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/about_us',$data);
	$this->load->view('admin/includes/footer');
}
public function edit_about_us_data(){
    if (!has_access(3)) {
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        return;
    }
	$data = [
        'name'               => $this->input->post('name'),
	    'modified_on'        => date('Y-m-d H:i:s')
	];
	
    $update 	= $this->registermodel->common_update('about_us',$data,['id' => 1]);
    echo json_encode(['success' => true, 'message' => 'data updated successfully']);
    return;
}
/*about_us*/

/*content_pages*/

/*statistics*/

/*hospital_statistics*/
public function hospital_statistics(){
    check_permission(12);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_statistics');
	$this->load->view('admin/includes/footer');
}
public function get_ambulance_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    // Initialize result arrays for each month (Jan to Dec)
    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    // Build the query
    $this->db->select("
        MONTH(date) as month,
        CASE
            WHEN booking_status = 'booked' AND (accept_status = 'accepted' OR accept_status = '') THEN 'booked'
            WHEN booking_status = 'completed' THEN 'completed'
            WHEN accept_status = 'declined' THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("ambulance_bookings b");
    $this->db->where("YEAR(date)", $year); // using booking date, not created_on
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(date)", "status"]);

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

    // Fill monthly counts based on status
    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    // Output JSON for chart
    echo json_encode($result);
}
public function get_admit_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    // Initialize 12 months of stats for each status
    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    $this->db->select("
        MONTH(date) as month,
        LOWER(booking_status) as status,
        COUNT(*) as total
    ");
    $this->db->from("admit_bookings b");
    $this->db->where("YEAR(date)", $year); // ✅ Use the scheduled date
    //$this->db->where("main_data_id", $sess_data);
    $this->db->where_in("booking_status", ['booked', 'completed', 'cancelled']);
    $this->db->group_by(["MONTH(date)", "booking_status"]);

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

    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    echo json_encode($result);
}
public function get_doctor_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    $this->db->select("
        MONTH(date) as month,
        LOWER(booking_status) as status,
        COUNT(*) as total
    ");
    $this->db->from("doctor_bookings b");
    $this->db->where("YEAR(date)", $year); // ✅ Use scheduled appointment date
    //$this->db->where("main_data_id", $sess_data);
    $this->db->where_in("booking_status", ['booked', 'completed', 'cancelled']);
    $this->db->group_by(["MONTH(date)", "booking_status"]);

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

    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    echo json_encode($result);
}
public function get_wellness_product_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    $this->db->select("
        MONTH(created_on) as month,
        CASE
            WHEN (booking_status IN ('booked', 'pickedup') AND (accept_status = 'accepted' OR accept_status = '')) THEN 'booked'
            WHEN (booking_status = 'completed') THEN 'completed'
            WHEN (accept_status = 'declined') THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("hospital_pharmacy_product_bookings b");
    $this->db->where("YEAR(created_on)", $year);
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(created_on)", "status"]);

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

    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    echo json_encode($result);
}
public function get_pharmacy_prescription_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    $this->db->select("
        MONTH(created_on) as month,
        CASE
            WHEN (booking_status IN ('booked', 'pickedup') AND (accept_status = 'accepted' OR accept_status = '')) THEN 'booked'
            WHEN (booking_status = 'completed') THEN 'completed'
            WHEN (accept_status = 'declined') THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("hospital_pharmacy_medicine_orders b");
    $this->db->where("YEAR(created_on)", $year);
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(created_on)", "status"]);

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

    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    echo json_encode($result);
}
public function get_diagnostic_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    // Initialize result arrays for each month (Jan to Dec)
    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    // Build the query
    $this->db->select("
        MONTH(date) as month,
        CASE
            WHEN booking_status = 'booked' AND (accept_status = 'accepted' OR accept_status = '') THEN 'booked'
            WHEN booking_status = 'completed' THEN 'completed'
            WHEN accept_status = 'declined' THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("hospital_diagnostic_bookings b");
    $this->db->where("YEAR(date)", $year); // using booking date, not created_on
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(date)", "status"]);

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

    // Fill monthly counts based on status
    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    // Output JSON for chart
    echo json_encode($result);
}
public function get_diagnostic_prescription_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    $this->db->select("
        MONTH(created_on) as month,
        CASE
            WHEN (booking_status IN ('booked', 'pickedup') AND (accept_status = 'accepted' OR accept_status = '')) THEN 'booked'
            WHEN (booking_status = 'completed') THEN 'completed'
            WHEN (accept_status = 'declined') THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("hospital_diagnostic_prescription_bookings b");
    $this->db->where("YEAR(created_on)", $year);
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(created_on)", "status"]);

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

    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    echo json_encode($result);
}
/*hospital_statistics*/

/*pharmacy_statistics*/
public function pharmacy_statistics(){
    check_permission(12);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/pharmacy_statistics');
	$this->load->view('admin/includes/footer');
}
public function get_main_pharmacy_prescription_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    $this->db->select("
        MONTH(created_on) as month,
        CASE
            WHEN (booking_status IN ('booked', 'pickedup') AND (accept_status = 'accepted' OR accept_status = '')) THEN 'booked'
            WHEN (booking_status = 'completed') THEN 'completed'
            WHEN (accept_status = 'declined') THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("pharmacy_medicine_orders b");
    $this->db->where("YEAR(created_on)", $year);
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(created_on)", "status"]);

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

    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    echo json_encode($result);
}
/*pharmacy_statistics*/

/*diagnostic_statistics*/
public function diagnostic_statistics(){
    check_permission(12);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/diagnostic_statistics');
	$this->load->view('admin/includes/footer');
}
public function get_main_diagnostic_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    // Initialize result arrays for each month (Jan to Dec)
    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    // Build the query
    $this->db->select("
        MONTH(date) as month,
        CASE
            WHEN booking_status = 'booked' AND (accept_status = 'accepted' OR accept_status = '') THEN 'booked'
            WHEN booking_status = 'completed' THEN 'completed'
            WHEN accept_status = 'declined' THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("diagnostic_bookings b");
    $this->db->where("YEAR(date)", $year); // using booking date, not created_on
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(date)", "status"]);

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

    // Fill monthly counts based on status
    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    // Output JSON for chart
    echo json_encode($result);
}
public function get_main_diagnostic_prescription_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    $this->db->select("
        MONTH(created_on) as month,
        CASE
            WHEN (booking_status IN ('booked', 'pickedup') AND (accept_status = 'accepted' OR accept_status = '')) THEN 'booked'
            WHEN (booking_status = 'completed') THEN 'completed'
            WHEN (accept_status = 'declined') THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("diagnostic_prescription_bookings b");
    $this->db->where("YEAR(created_on)", $year);
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(created_on)", "status"]);

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

    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    echo json_encode($result);
}
/*diagnostic_statistics*/

/*lab_test_statistics*/
public function lab_test_statistics(){
    check_permission(12);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_test_statistics');
	$this->load->view('admin/includes/footer');
}
public function get_main_lab_test_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    // Initialize result arrays for each month (Jan to Dec)
    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    // Build the query
    $this->db->select("
        MONTH(date) as month,
        CASE
            WHEN booking_status = 'booked' AND (accept_status = 'accepted' OR accept_status = '') THEN 'booked'
            WHEN booking_status = 'completed' THEN 'completed'
            WHEN accept_status = 'declined' THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("lab_test_bookings b");
    $this->db->where("YEAR(date)", $year); // using booking date, not created_on
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(date)", "status"]);

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

    // Fill monthly counts based on status
    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    // Output JSON for chart
    echo json_encode($result);
}
public function get_main_lab_test_prescription_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    $this->db->select("
        MONTH(created_on) as month,
        CASE
            WHEN (booking_status IN ('booked', 'pickedup') AND (accept_status = 'accepted' OR accept_status = '')) THEN 'booked'
            WHEN (booking_status = 'completed') THEN 'completed'
            WHEN (accept_status = 'declined') THEN 'cancelled'
            ELSE 'other'
        END as status,
        COUNT(*) as total
    ");
    $this->db->from("lab_test_prescription_bookings b");
    $this->db->where("YEAR(created_on)", $year);
    //$this->db->where("main_data_id", $sess_data);
    $this->db->group_by(["MONTH(created_on)", "status"]);

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

    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    echo json_encode($result);
}
/*lab_test_statistics*/

/*online_doctor_statistics*/
public function online_doctor_statistics(){
    check_permission(12);
    $sess_data = $this->session_data();
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctor_statistics');
	$this->load->view('admin/includes/footer');
}
public function get_main_online_doctor_booking_stats_by_year(){
    $year = $this->input->post('year');
    $sess_data = $this->session_data();

    $result = [
        'booked' => array_fill(0, 12, 0),
        'completed' => array_fill(0, 12, 0),
        'cancelled' => array_fill(0, 12, 0),
    ];

    $this->db->select("
        MONTH(date) as month,
        LOWER(booking_status) as status,
        COUNT(*) as total
    ");
    $this->db->from("online_doctor_bookings b");
    $this->db->where("YEAR(date)", $year); // ✅ Use scheduled appointment date
    //$this->db->where("main_data_id", $sess_data);
    $this->db->where_in("booking_status", ['booked', 'completed', 'cancelled']);
    $this->db->group_by(["MONTH(date)", "booking_status"]);

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

    foreach ($query->result() as $row) {
        $monthIndex = (int)$row->month - 1;
        $status = $row->status;
        if (isset($result[$status])) {
            $result[$status][$monthIndex] = (int)$row->total;
        }
    }

    echo json_encode($result);
}
/*online_doctor_statistics*/

/*statistics*/

/*payments*/

/*hospital_diagnostic_payments*/
public function hospital_diagnostic_payments(){
    check_permission(12);
    $sess_data = $this->session_data();
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_diagnostic_payments',$data);
	$this->load->view('admin/includes/footer');
}
public function get_hospital_diagnostic_revenue_summary(){
    $hospital_id = $this->input->post('hospital_id');
    $start_date  = $this->input->post('start_date'); // format: YYYY-MM-DD
    $end_date    = $this->input->post('end_date');   // format: YYYY-MM-DD
    
    // 1. Get total earnings
    $this->db->select('SUM(consultation_fee) as total_amount');
    $this->db->from('hospital_diagnostic_bookings');
    $this->db->where('main_data_id', $hospital_id);
    $this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);
    //$this->db->where_in('booking_status', ['booked'/*, 'completed'*/]);
    //$this->db->where('booking_status', 'booked');
    $this->db->where_in('accept_status', ['', 'accepted']);
    $booking = $this->db->get()->row_array();
    
    $total_amount = isset($booking['total_amount']) ? (float) $booking['total_amount'] : 0;
    $total_amount = round($total_amount, 2); // Round to 2 decimals
    
    // 2. Get hospital commission percentage
    $this->db->select('name, diagnostics_commission');
    $this->db->from('main_data');
    $this->db->where('id', $hospital_id);
    $hospital = $this->db->get()->row_array();
    
    if (!isset($hospital['diagnostics_commission']) || (float)$hospital['diagnostics_commission'] == 0) {
        echo json_encode([
            'status' => false,
            'message' => 'Please assign a valid diagnostic commission percentage to view the data.'
        ]);
        return;
    }
    
    $commission_percent = isset($hospital['diagnostics_commission']) ? (float) $hospital['diagnostics_commission'] : 0;
    
    // 3. Calculate commission amount
    $commission_amount = round(($total_amount * $commission_percent) / 100, 2);
    
    // 4. Get transferred amount in date range
    $this->db->select('SUM(amount) as transferred_amount');
    $this->db->from('hospital_diagnostic_payment_settlements');
    $this->db->where('main_data_id', $hospital_id);
    /*$this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);*/
    $settlement = $this->db->get()->row_array();
    
    $transferred_amount = isset($settlement['transferred_amount']) ? (float) $settlement['transferred_amount'] : 0;
    $transferred_amount = round($transferred_amount, 2);
    
    // 5. Pending amount
    if($total_amount==0.00){
        $pending_amount = 0;
    }else{
        $pending_amount = round($commission_amount - $transferred_amount, 2);
    }
    
    // 6. Response
    $response = [
        'status' => true,
        'data' => [
            [
                'hospital_id' => (int) $hospital_id,
                'hospital_name' => $hospital['name'],
                'commission' => $hospital['diagnostics_commission'],
                'total_amount' => number_format($total_amount, 2, '.', ''),
                'transferred_amount' => number_format($transferred_amount, 2, '.', ''),
                'pending' => number_format($pending_amount, 2, '.', ''),
                'commission_percent' => (string) $commission_percent,
                'hospital_revenue' => $commission_amount
            ]
        ]
    ];

    
    echo json_encode($response);

}
public function save_hospital_diagnostic_payment_transfer(){
    $hospital_id        = $this->input->post('hospital_id');
    $transfer_amount    = $this->input->post('transfer_amount');
    $start_date         = $this->input->post('start_date');
    $end_date           = $this->input->post('end_date');
    
    $data = [
        'main_data_id'          => $hospital_id,
        'amount'                => $transfer_amount,
        'start_date'            => $start_date,
        'end_date'              => $end_date,
        'payment_date'          => date('Y-m-d'),
        'created_by'            => 1,
        'created_on'            => date('Y-m-d H:i:s')
    ];

    $insert = $this->registermodel->common_insert('hospital_diagnostic_payment_settlements',$data);
    echo json_encode(['success' => true, 'message' => 'data added successfully']);
    return;
}
/*hospital_diagnostic_payments*/

/*hospital_doctor_payments*/
public function hospital_doctor_payments(){
    check_permission(12);
    $sess_data = $this->session_data();
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/hospital_doctor_payments',$data);
	$this->load->view('admin/includes/footer');
}
public function get_hospital_doctor_revenue_summary(){
    $hospital_id = $this->input->post('hospital_id');
    $start_date  = $this->input->post('start_date'); // format: YYYY-MM-DD
    $end_date    = $this->input->post('end_date');   // format: YYYY-MM-DD
    
    // 1. Get total earnings
    $this->db->select('SUM(consultation_fee) as total_amount');
    $this->db->from('doctor_bookings');
    $this->db->where('main_data_id', $hospital_id);
    $this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);
    $this->db->where_in('booking_status', ['booked', 'completed']);
    //$this->db->where('booking_status', 'booked');
    //$this->db->where_in('accept_status', ['', 'accepted']);
    $booking = $this->db->get()->row_array();
    
    $total_amount = isset($booking['total_amount']) ? (float) $booking['total_amount'] : 0;
    $total_amount = round($total_amount, 2); // Round to 2 decimals
    
    // 2. Get hospital commission percentage
    $this->db->select('name, doctor_commission');
    $this->db->from('main_data');
    $this->db->where('id', $hospital_id);
    $hospital = $this->db->get()->row_array();
    
    if (!isset($hospital['doctor_commission']) || (float)$hospital['doctor_commission'] == 0) {
        echo json_encode([
            'status' => false,
            'message' => 'Please assign a valid doctor commission percentage to view the data.'
        ]);
        return;
    }
    
    $commission_percent = isset($hospital['doctor_commission']) ? (float) $hospital['doctor_commission'] : 0;
    
    // 3. Calculate commission amount
    $commission_amount = round(($total_amount * $commission_percent) / 100, 2);
    
    // 4. Get transferred amount in date range
    $this->db->select('SUM(amount) as transferred_amount');
    $this->db->from('hospital_doctor_payment_settlements');
    $this->db->where('main_data_id', $hospital_id);
    /*$this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);*/
    $settlement = $this->db->get()->row_array();
    
    $transferred_amount = isset($settlement['transferred_amount']) ? (float) $settlement['transferred_amount'] : 0;
    $transferred_amount = round($transferred_amount, 2);
    
    // 5. Pending amount
    if($total_amount==0.00){
        $pending_amount = 0;
    }else{
        $pending_amount = round($commission_amount - $transferred_amount, 2);
    }
    
    
    // 6. Response
    $response = [
        'status' => true,
        'data' => [
            [
                'hospital_id' => (int) $hospital_id,
                'hospital_name' => $hospital['name'],
                'commission' => $hospital['doctor_commission'],
                'total_amount' => number_format($total_amount, 2, '.', ''),
                'transferred_amount' => number_format($transferred_amount, 2, '.', ''),
                'pending' => number_format($pending_amount, 2, '.', ''),
                'commission_percent' => (string) $commission_percent,
                'hospital_revenue' => $commission_amount
            ]
        ]
    ];

    
    echo json_encode($response);

}
public function save_hospital_doctor_payment_transfer(){
    $hospital_id        = $this->input->post('hospital_id');
    $transfer_amount    = $this->input->post('transfer_amount');
    $start_date         = $this->input->post('start_date');
    $end_date           = $this->input->post('end_date');
    
    $data = [
        'main_data_id'          => $hospital_id,
        'amount'                => $transfer_amount,
        'start_date'            => $start_date,
        'end_date'              => $end_date,
        'payment_date'          => date('Y-m-d'),
        'created_by'            => 1,
        'created_on'            => date('Y-m-d H:i:s')
    ];

    $insert = $this->registermodel->common_insert('hospital_doctor_payment_settlements',$data);
    echo json_encode(['success' => true, 'message' => 'data added successfully']);
    return;
}
/*hospital_doctor_payments*/

/*diagnostic_payments*/
public function diagnostic_payments(){
    check_permission(12);
    $sess_data = $this->session_data();
    $data['hospitals'] = $this->registermodel->common_fetch('diagnostics',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/diagnostic_payments',$data);
	$this->load->view('admin/includes/footer');
}
public function get_diagnostic_revenue_summary(){
    $hospital_id = $this->input->post('hospital_id');
    $start_date  = $this->input->post('start_date'); // format: YYYY-MM-DD
    $end_date    = $this->input->post('end_date');   // format: YYYY-MM-DD
    
    // 1. Get total earnings
    $this->db->select('SUM(consultation_fee) as total_amount');
    $this->db->from('diagnostic_bookings');
    $this->db->where('main_data_id', $hospital_id);
    $this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);
    //$this->db->where_in('booking_status', ['booked'/*, 'completed'*/]);
    //$this->db->where('booking_status', 'booked');
    $this->db->where_in('accept_status', ['', 'accepted']);
    $booking = $this->db->get()->row_array();
    
    $total_amount = isset($booking['total_amount']) ? (float) $booking['total_amount'] : 0;
    $total_amount = round($total_amount, 2); // Round to 2 decimals
    
    // 2. Get hospital commission percentage
    $this->db->select('name, diagnostics_commission');
    $this->db->from('diagnostics');
    $this->db->where('id', $hospital_id);
    $hospital = $this->db->get()->row_array();
    
    if (!isset($hospital['diagnostics_commission']) || (float)$hospital['diagnostics_commission'] == 0) {
        echo json_encode([
            'status' => false,
            'message' => 'Please assign a valid diagnostic commission percentage to view the data.'
        ]);
        return;
    }
    
    $commission_percent = isset($hospital['diagnostics_commission']) ? (float) $hospital['diagnostics_commission'] : 0;
    
    // 3. Calculate commission amount
    $commission_amount = round(($total_amount * $commission_percent) / 100, 2);
    
    // 4. Get transferred amount in date range
    $this->db->select('SUM(amount) as transferred_amount');
    $this->db->from('diagnostic_payment_settlements');
    $this->db->where('main_data_id', $hospital_id);
    /*$this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);*/
    $settlement = $this->db->get()->row_array();
    
    $transferred_amount = isset($settlement['transferred_amount']) ? (float) $settlement['transferred_amount'] : 0;
    $transferred_amount = round($transferred_amount, 2);
    
    // 5. Pending amount
    if($total_amount==0.00){
        $pending_amount = 0;
    }else{
        $pending_amount = round($commission_amount - $transferred_amount, 2);
    }
    
    // 6. Response
    $response = [
        'status' => true,
        'data' => [
            [
                'hospital_id' => (int) $hospital_id,
                'hospital_name' => $hospital['name'],
                'commission' => $hospital['diagnostics_commission'],
                'total_amount' => number_format($total_amount, 2, '.', ''),
                'transferred_amount' => number_format($transferred_amount, 2, '.', ''),
                'pending' => number_format($pending_amount, 2, '.', ''),
                'commission_percent' => (string) $commission_percent,
                'hospital_revenue' => $commission_amount
            ]
        ]
    ];

    
    echo json_encode($response);

}
public function save_diagnostic_payment_transfer(){
    $hospital_id        = $this->input->post('hospital_id');
    $transfer_amount    = $this->input->post('transfer_amount');
    $start_date         = $this->input->post('start_date');
    $end_date           = $this->input->post('end_date');
    
    $data = [
        'main_data_id'          => $hospital_id,
        'amount'                => $transfer_amount,
        'start_date'            => $start_date,
        'end_date'              => $end_date,
        'payment_date'          => date('Y-m-d'),
        'created_by'            => 1,
        'created_on'            => date('Y-m-d H:i:s')
    ];

    $insert = $this->registermodel->common_insert('diagnostic_payment_settlements',$data);
    echo json_encode(['success' => true, 'message' => 'data added successfully']);
    return;
}
/*diagnostic_payments*/

/*lab_test_payments*/
public function lab_test_payments(){
    check_permission(12);
    $sess_data = $this->session_data();
    $data['hospitals'] = $this->registermodel->common_fetch('lab_tests',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/lab_test_payments',$data);
	$this->load->view('admin/includes/footer');
}
public function get_lab_revenue_summary(){
    $hospital_id = $this->input->post('hospital_id');
    $start_date  = $this->input->post('start_date'); // format: YYYY-MM-DD
    $end_date    = $this->input->post('end_date');   // format: YYYY-MM-DD
    
    // 1. Get total earnings
    $this->db->select('SUM(consultation_fee) as total_amount');
    $this->db->from('lab_test_bookings');
    $this->db->where('main_data_id', $hospital_id);
    $this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);
    //$this->db->where_in('booking_status', ['booked'/*, 'completed'*/]);
    //$this->db->where('booking_status', 'booked');
    $this->db->where_in('accept_status', ['', 'accepted']);
    $booking = $this->db->get()->row_array();
    
    $total_amount = isset($booking['total_amount']) ? (float) $booking['total_amount'] : 0;
    $total_amount = round($total_amount, 2); // Round to 2 decimals
    
    // 2. Get hospital commission percentage
    $this->db->select('name, lab_commission');
    $this->db->from('lab_tests');
    $this->db->where('id', $hospital_id);
    $hospital = $this->db->get()->row_array();
    
    if (!isset($hospital['lab_commission']) || (float)$hospital['lab_commission'] == 0) {
        echo json_encode([
            'status' => false,
            'message' => 'Please assign a valid lab commission percentage to view the data.'
        ]);
        return;
    }
    
    $commission_percent = isset($hospital['lab_commission']) ? (float) $hospital['lab_commission'] : 0;
    
    // 3. Calculate commission amount
    $commission_amount = round(($total_amount * $commission_percent) / 100, 2);
    
    // 4. Get transferred amount in date range
    $this->db->select('SUM(amount) as transferred_amount');
    $this->db->from('lab_test_payment_settlements');
    $this->db->where('main_data_id', $hospital_id);
    /*$this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);*/
    $settlement = $this->db->get()->row_array();
    
    $transferred_amount = isset($settlement['transferred_amount']) ? (float) $settlement['transferred_amount'] : 0;
    $transferred_amount = round($transferred_amount, 2);
    
    // 5. Pending amount
    if($total_amount==0.00){
        $pending_amount = 0;
    }else{
        $pending_amount = round($commission_amount - $transferred_amount, 2);
    }
    
    // 6. Response
    $response = [
        'status' => true,
        'data' => [
            [
                'hospital_id' => (int) $hospital_id,
                'hospital_name' => $hospital['name'],
                'commission' => $hospital['lab_commission'],
                'total_amount' => number_format($total_amount, 2, '.', ''),
                'transferred_amount' => number_format($transferred_amount, 2, '.', ''),
                'pending' => number_format($pending_amount, 2, '.', ''),
                'commission_percent' => (string) $commission_percent,
                'hospital_revenue' => $commission_amount
            ]
        ]
    ];

    
    echo json_encode($response);

}
public function save_lab_payment_transfer(){
    $hospital_id        = $this->input->post('hospital_id');
    $transfer_amount    = $this->input->post('transfer_amount');
    $start_date         = $this->input->post('start_date');
    $end_date           = $this->input->post('end_date');
    
    $data = [
        'main_data_id'          => $hospital_id,
        'amount'                => $transfer_amount,
        'start_date'            => $start_date,
        'end_date'              => $end_date,
        'payment_date'          => date('Y-m-d'),
        'created_by'            => 1,
        'created_on'            => date('Y-m-d H:i:s')
    ];

    $insert = $this->registermodel->common_insert('lab_test_payment_settlements',$data);
    echo json_encode(['success' => true, 'message' => 'data added successfully']);
    return;
}
/*lab_test_payments*/

/*online_doctor_payments*/
public function online_doctor_payments(){
    check_permission(12);
    $sess_data = $this->session_data();
    $data['hospitals'] = $this->registermodel->common_fetch('online_doctors',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/super_admin/online_doctor_payments',$data);
	$this->load->view('admin/includes/footer');
}
public function get_online_doctor_revenue_summary(){
    $hospital_id = $this->input->post('hospital_id');
    $start_date  = $this->input->post('start_date'); // format: YYYY-MM-DD
    $end_date    = $this->input->post('end_date');   // format: YYYY-MM-DD
    
    // 1. Get total earnings
    $this->db->select('SUM(consultation_fee) as total_amount');
    $this->db->from('online_doctor_bookings');
    $this->db->where('doctor_id', $hospital_id);
    $this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);
    $this->db->where_in('booking_status', ['booked', 'completed']);
    //$this->db->where('booking_status', 'booked');
    //$this->db->where_in('accept_status', ['', 'accepted']);
    $booking = $this->db->get()->row_array();
    
    $total_amount = isset($booking['total_amount']) ? (float) $booking['total_amount'] : 0;
    $total_amount = round($total_amount, 2); // Round to 2 decimals
    
    // 2. Get hospital commission percentage
    $this->db->select('name, doctor_commission');
    $this->db->from('online_doctors');
    $this->db->where('id', $hospital_id);
    $hospital = $this->db->get()->row_array();
    
    if (!isset($hospital['doctor_commission']) || (float)$hospital['doctor_commission'] == 0) {
        echo json_encode([
            'status' => false,
            'message' => 'Please assign a valid doctor commission percentage to view the data.'
        ]);
        return;
    }
    
    $commission_percent = isset($hospital['doctor_commission']) ? (float) $hospital['doctor_commission'] : 0;
    
    // 3. Calculate commission amount
    $commission_amount = round(($total_amount * $commission_percent) / 100, 2);
    
    // 4. Get transferred amount in date range
    $this->db->select('SUM(amount) as transferred_amount');
    $this->db->from('online_doctor_payment_settlements');
    $this->db->where('main_data_id', $hospital_id);
    /*$this->db->where('DATE(created_on) >=', $start_date);
    $this->db->where('DATE(created_on) <=', $end_date);*/
    $settlement = $this->db->get()->row_array();
    
    $transferred_amount = isset($settlement['transferred_amount']) ? (float) $settlement['transferred_amount'] : 0;
    $transferred_amount = round($transferred_amount, 2);
    
    // 5. Pending amount
    if($total_amount==0.00){
        $pending_amount = 0;
    }else{
        $pending_amount = round($commission_amount - $transferred_amount, 2);
    }
    
    
    // 6. Response
    $response = [
        'status' => true,
        'data' => [
            [
                'hospital_id' => (int) $hospital_id,
                'hospital_name' => $hospital['name'],
                'commission' => $hospital['doctor_commission'],
                'total_amount' => number_format($total_amount, 2, '.', ''),
                'transferred_amount' => number_format($transferred_amount, 2, '.', ''),
                'pending' => number_format($pending_amount, 2, '.', ''),
                'commission_percent' => (string) $commission_percent,
                'hospital_revenue' => $commission_amount
            ]
        ]
    ];

    
    echo json_encode($response);

}
public function save_online_doctor_payment_transfer(){
    $hospital_id        = $this->input->post('hospital_id');
    $transfer_amount    = $this->input->post('transfer_amount');
    $start_date         = $this->input->post('start_date');
    $end_date           = $this->input->post('end_date');
    
    $data = [
        'main_data_id'          => $hospital_id,
        'amount'                => $transfer_amount,
        'start_date'            => $start_date,
        'end_date'              => $end_date,
        'payment_date'          => date('Y-m-d'),
        'created_by'            => 1,
        'created_on'            => date('Y-m-d H:i:s')
    ];

    $insert = $this->registermodel->common_insert('online_doctor_payment_settlements',$data);
    echo json_encode(['success' => true, 'message' => 'data added successfully']);
    return;
}
/*online_doctor_payments*/

/*payments*/

/*booking_for_an_user*/
public function check_user_subscription($user_id) {
    $this->db->select('users.auth_token, users.status, health_card_holders.user_id, health_card_holders.to_date,
                       user_addresses.id as address_id, user_addresses.address as full_address,
                       user_addresses.lat as lat, user_addresses.lon as lon');
    $this->db->from('users');
    $this->db->join('health_card_holders', 'users.id = health_card_holders.user_id', 'left');
    $this->db->join('user_addresses', 'user_addresses.user_id = health_card_holders.user_id AND user_addresses.default_address = 1', 'left');
    $this->db->where(['users.id' => $user_id, 'users.delete_status' => 1]);
    $user_data = $this->db->get()->row_array();

    if (!$user_data) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['success' => false, 'message' => 'User not found']));
    }

    if ($user_data['status'] != 1) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['success' => false, 'message' => 'Your account is inactive']));
    }

    if (!is_null($user_data['to_date']) && $user_data['to_date'] < date('Y-m-d')) {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['success' => false, 'message' => 'Your subscription has expired. Please renew.']));
    }

    // 👉 Fetch family members (can be multiple)
    $family_members = $this->db->select('id, name, mobile')
                               ->from('family_members')
                               ->where(['user_id' => $user_id, 'status' => 1, 'delete_status' => 1])
                               ->get()
                               ->result_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'message' => 'Subscription is active',
            'address' => $user_data['full_address'] ?? '',
            'address_id' => $user_data['address_id'] ?? '',
            'lat' => $user_data['lat'] ?? '',
            'lon' => $user_data['lon'] ?? '',
            'family_members' => $family_members
        ]));
}
public function check_user_distance(){
    $user_id            = $this->input->post('user_id');
    $hospital_id        = $this->input->post('hospital_id');
    $lat                = $this->input->post('lat');
    $lon                = $this->input->post('lon');
    
    $hospital_details = $this->registermodel->common_fetch_select('main_data',['id' => $hospital_id],'lat,lon',[]);
    
    $hospital_lat  = $hospital_details[0]['lat'];
    
    $hospital_lon  = $hospital_details[0]['lon'];
    
    $distance = $this->registermodel->check_user_distance($lat, $lon, $hospital_lat, $hospital_lon);
    
    if(empty($lat)||empty($lon)){
        echo json_encode(['success' => fla, 'message' => "Hospital is within 10 KM"]);
    }

    if ($distance <= 10) {
        echo json_encode(['success' => true, 'message' => "Hospital is within 10 KM"]);
    } else {
        echo json_encode(['success' => false, 'message' => "Hospital is not within 10 KM"]);
    }

    
    
}
public function get_districts_data($state_id){
    $districts = $this->db->select('id, name')
                               ->from('districts')
                               ->where(['state_id' => $state_id,'status' => 1, 'delete_status' => 1])
                               ->get()
                               ->result_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'districts' => $districts
        ]));
}
public function get_cities_data($state_id,$district_id){
    $cities = $this->db->select('id, name')
                               ->from('cities')
                               ->where(['state_id' => $state_id,'district_id' => $district_id,'status' => 1, 'delete_status' => 1])
                               ->get()
                               ->result_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'cities' => $cities
        ]));
}
public function get_hospitals_data() {
    $state_id    = $this->input->post('state_id');
    $district_id = $this->input->post('district_id');
    $city_id     = $this->input->post('city_id');

    $this->db->select('id, name, mobile,location as address');
    $this->db->from('main_data');
    $this->db->where(['delete_status' => 1,'status' => 1]);

    if (!empty($state_id)) {
        $this->db->where('state_id', $state_id);
    }
    if (!empty($district_id)) {
        $this->db->where('district_id', $district_id);
    }
    if (!empty($city_id)) {
        $this->db->where('city_id', $city_id);
    }

    $hospitals = $this->db->get()->result_array();
    
    //echo $this->db->last_query();exit;

    if (!empty($hospitals)) {
        return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'hospitals' => $hospitals
        ]));
    } else {
        return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => false,
            'message' => 'No hospitals found',
            'hospitals' => []
        ]));
        
    }
}


/*ambulance_booking*/
public function ambulance_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['states'] = $this->registermodel->common_fetch('states',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/ambulance_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_ambulance_booking(){
    $user_id = $this->input->post('user_id');
    $user_details = $this->registermodel->common_fetch_select('users',['id' => $user_id],'name,mobile',[]);
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    $data = [
       'user_id'                =>  $user_id,
       'main_data_id'           =>  $this->input->post('main_data_id'),
       'address_id'             =>  $this->input->post('address'),
       'name'                   =>  $user_details[0]['name'],
       'mobile'                 =>  $user_details[0]['mobile'],
       'booking_status'         =>  'booked',
       'date'                   =>  date('Y-m-d'),
       'booked_by'              =>  $booked_by,
       'created_on'             =>  date('Y-m-d H:i:s')
    ];
    
    //print_r($data);exit;
    $insert = $this->registermodel->common_insert('ambulance_bookings',$data);
    $bkid = sprintf('%04d',$insert);
    $book_id = 'BKID_'.$bkid;
    $update = $this->registermodel->common_update('ambulance_bookings',['booking_id' => $book_id],['id' => $insert]);
    
    $booking_details = $this->registermodel->common_fetch('ambulance_bookings',['id' => $insert]);
    $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
    //echo $this->db->last_query();exit;
    $main_data_details = $this->registermodel->common_fetch('main_data',['id' => $booking_details[0]['main_data_id']]);
    //print_r($main_data_details);exit;
    /*user_notification*/
    $data = array(
       'member_id'          => $booking_details[0]['user_id'],
       'title'              => 'Med Rayder',
       'message'            => "Your ambulance booking (Booking ID: {$booking_details[0]['booking_id']}) has been successfully placed. You will be notified once it is accepted by the hospital",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data['title']; 
    $message['body'] = $data['message'];
    $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
    /*user_notification*/
    
    /*ambulance_notification*/
    $data1 = array(
      'member_id'          => $booking_details[0]['main_data_id'],
      'title'              => 'Med Rayder',
      'message'            => "You have received a new ambulance booking (Booking ID: {$booking_details[0]['booking_id']}). Please review the details and accept the request to proceed with dispatch",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data1['title'];
    $message['body'] = $data1['message'];
    $this->sendNotification($main_data_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $rr = $this->send_web_notification($main_data_details[0]['web_player_id'],$message['title'],$message['body']);//exit;
    //print_r($rr);exit;
    $insert_notifications = $this->registermodel->common_insert('main_data_notifications',$data1);
    echo json_encode(['success' => true, 'message' => 'ambulance booked successfully']);
    return;
}
/*ambulance_booking*/

/*admit_booking*/
public function get_slots_by_date(){
    $selected_date = $this->input->post('date'); // Y-m-d
    $sess_data = $this->input->post('hospital_id');
    $main_data = $this->registermodel->common_fetch('main_data', ['id' => $sess_data]);

    // Parse open/close time from DB (like 10:00 AM format)
    $open_time = date('H:i', strtotime($main_data[0]['open_time']));
    $close_time = date('H:i', strtotime($main_data[0]['close_time']));

    $today = date('Y-m-d');
    $is_today = ($selected_date === $today);
    $current_time = $is_today ? date('H:i') : null;

    $slots = $this->generate_time_slots($open_time, $close_time, 30, $is_today, $current_time, $selected_date);

    echo json_encode($slots);
}
public function generate_time_slots($open_time, $close_time, $interval = 30, $is_today = false, $current_time = null, $selected_date = null) {
    $slots = [
        'morning' => [],
        'afternoon' => [],
        'evening' => []
    ];

    if (!$selected_date) $selected_date = date('Y-m-d');

    $start_timestamp = strtotime($selected_date . ' ' . $open_time);
    $end_timestamp   = strtotime($selected_date . ' ' . $close_time);

    // Handle overnight time (e.g. 10:00 AM to 01:00 AM next day)
    if ($end_timestamp <= $start_timestamp) {
        $end_timestamp = strtotime($selected_date . ' ' . $close_time . ' +1 day');
    }

    // Shift start time to current time if today
    if ($is_today && $current_time) {
        $now = strtotime(date('Y-m-d') . ' ' . $current_time);
        if ($now > $start_timestamp) {
            $start_timestamp = $now;
        }
    }

    // Round to next interval
    $start_timestamp = $this->round_time_to_interval($start_timestamp, $interval);

    $added_slots = [];

    while ($start_timestamp < $end_timestamp) {
    // ⛔ For today's date only, stop if we cross into the next day
        if ($is_today && date('Y-m-d', $start_timestamp) !== $selected_date) {
            break;
        }
    
        $slot = date('h:i A', $start_timestamp);
    
        if (in_array($slot, $added_slots)) {
            $start_timestamp = strtotime("+{$interval} minutes", $start_timestamp);
            continue;
        }
    
        $hour = (int)date('H', $start_timestamp);
        if ($hour >= 0 && $hour < 12) {
            $slots['morning'][] = ['time' => $slot];
        } elseif ($hour >= 12 && $hour < 17) {
            $slots['afternoon'][] = ['time' => $slot];
        } else {
            $slots['evening'][] = ['time' => $slot];
        }
    
        $added_slots[] = $slot;
        $start_timestamp = strtotime("+{$interval} minutes", $start_timestamp);
    }
//exit;

    return $slots;
}
public function round_time_to_interval($timestamp, $interval) {
    $minute = (int)date('i', $timestamp);
    $second = (int)date('s', $timestamp);
    $total_seconds = $minute * 60 + $second;

    $interval_seconds = $interval * 60;
    $next_interval = ceil($total_seconds / $interval_seconds) * $interval_seconds;

    return strtotime(date('Y-m-d H:00:00', $timestamp)) + $next_interval;
}
public function admit_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['states'] = $this->registermodel->common_fetch('states',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/admit_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_admit_booking(){
    
    $time_slots = $this->input->post('time');

    if (empty($time_slots)) {
        echo json_encode(['success' => false, 'message' => 'Please select time slot']);
        return;
    }
     
    $main_data_id = $this->input->post('main_data_id');
    $family_member_id = $this->input->post('family_member_id');
    $fetch = $this->registermodel->common_fetch_select('main_data',['id' => $main_data_id],'name,logo,cat_id',[]);
    $fetch1 = $this->registermodel->common_fetch_select('family_members',['id' => $family_member_id],'name,mobile',[]);
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    $data = [
      'user_id'             => $this->input->post('user_id'),
      'cat_id'              => $fetch[0]['cat_id'],
      'main_data_id'        => $main_data_id,
      'hospital_name'       => $fetch[0]['name'],
      'logo'                => $fetch[0]['logo'],
      'consult_type'        => 'admit',
      'date'                => $this->input->post('date'),
      //'slot_id'             => $slot_id,
      'time'                => $this->input->post('time'),
      'mobile'              => $fetch1[0]['mobile'],
      'name'                => $fetch1[0]['name'],
      'family_member_id'    => $this->input->post('family_member_id'),
      'booking_status'      => 'booked',
      'booked_by'           =>  $booked_by,
      'created_on'          => date('Y-m-d H:i:s')
    ];
    $insert = $this->registermodel->common_insert('admit_bookings',$data);
    $bkid = sprintf('%04d',$insert);
    $booking_id = 'BKID_'.$bkid;
    $update = $this->registermodel->common_update('admit_bookings',['booking_id' => $booking_id],['id' => $insert]);
    //$update = $this->registermodel->common_update('hospital_slots',['booking_status' => 'booked'],['id' => $slot_id]);
    
    $booking_details = $this->registermodel->common_fetch('admit_bookings',['id' => $insert]);
    $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
    //echo $this->db->last_query();exit;
    $main_data_details = $this->registermodel->common_fetch('main_data',['id' => $booking_details[0]['main_data_id']]);
    /*user_notification*/
    $data = array(
       'member_id'          => $booking_details[0]['user_id'],
       'title'              => 'Med Rayder',
       'message'            => "Your admit booking (Booking ID: {$booking_details[0]['booking_id']}) has been successfully placed. The hospital will review and confirm your admission shortly",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data['title']; 
    $message['body'] = $data['message'];
    $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
    /*user_notification*/
    
    /*ambulance_notification*/
    $data1 = array(
       'member_id'          => $booking_details[0]['main_data_id'],
       'title'              => 'Med Rayder',
       'message'            => "You have received a new admit booking (Booking ID: {$booking_details[0]['booking_id']}). Please review the details and confirm the admission as soon as possible",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data1['title'];
    $message['body'] = $data1['message'];
    $this->sendNotification($main_data_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $rr = $this->send_web_notification($main_data_details[0]['web_player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('main_data_notifications',$data1);
    /*ambulance_notification*/
    
    echo json_encode(['success' => true, 'message' => 'hospital admit booked successfully']);
    return;
}
/*admit_booking*/

/*op_booking*/
public function get_hospital_specialities($hospital_id){
    $specialities = $this->registermodel->get_hospital_specialities($hospital_id);
    return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => true,
                'specialities' => $specialities
            ]));
}
public function get_hospital_doctors($hospital_id,$speciality_id){
    $doctors = $this->db->select('id, name,offline_fee')
                               ->from('doctors')
                               ->where(['main_data_id' => $hospital_id, 'speciality_id' => $speciality_id,'availability' => 1,'status' => 1, 'delete_status' => 1])
                               ->get()
                               ->result_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'doctors' => $doctors
        ]));
}
public function get_hospital_doctor_dates($hospital_id,$doctor_id){
    $dates = $this->registermodel->get_doctor_dates($hospital_id,$doctor_id);
    
    //echo $this->db->last_query();exit;

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'dates' => $dates
        ]));
}
public function get_doctor_slots_by_date(){
    $date = $this->input->post('date'); // Y-m-d
    $main_data_id = $this->input->post('hospital_id');
    $doctor_id = $this->input->post('doctor_id');
    
    $slots = $this->registermodel->get_doctor_slots($main_data_id,$doctor_id,$date);
    
    //echo $this->db->last_query();exit;
    
    echo json_encode($slots);
}
public function get_doctor_coupons(){
    $coupons = $this->db->select('id, name,percentage,description')
                               ->from('doctor_coupons')
                               ->where(['status' => 1, 'delete_status' => 1])
                               ->get()
                               ->result_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'coupons' => $coupons
        ]));
}
public function op_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['states'] = $this->registermodel->common_fetch('states',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/op_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function create_cashfree_order() {
    $fee         = $this->input->post('fee'); 
    $amount      = $this->input->post('consultation_fee'); 
    $customer_id = $this->input->post('user_id');
    $main_data_id = $this->input->post('main_data_id');
    $slot_id      = $this->input->post('time');
    $family_member_id = $this->input->post('family_member_id');

    // Get details for saving booking
    $user_details = $this->registermodel->common_fetch_select('users', ['id' => $customer_id], 'email,mobile', []);
    $hospital_details = $this->registermodel->common_fetch_select('main_data', ['id' => $main_data_id], 'cat_id', []);
    $slot_details = $this->registermodel->common_fetch_select('doctor_slots', ['id' => $slot_id], 'time', []);
    $family_member_details = $this->registermodel->common_fetch_select('family_members', ['id' => $family_member_id], 'name,mobile', []);

    $customer_phone = $user_details[0]['mobile'] ?? '';
    $customer_email = $user_details[0]['email'] ?? '';
    
    if (empty($slot_id)) {
        echo json_encode(['success' => false, 'message' => 'Please select time slot']);
        return;
    }
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    // --- Save booking row as pending ---
    $data = [
        'user_id'          => $customer_id,
        'main_data_id'     => $main_data_id,
        'cat_id'           => $hospital_details[0]['cat_id'] ?? null,
        'speciality_id'    => $this->input->post('speciality_id'),
        'doctor_id'        => $this->input->post('doctor_id'),
        'consult_type'     => 'offline',
        'date'             => $this->input->post('date'),
        'slot_id'          => $slot_id,
        'time'             => $slot_details[0]['time'] ?? '',
        'mobile'           => $user_details[0]['mobile'] ?? '',
        'patient_name'     => $family_member_details[0]['name'] ?? '',
        'family_member_id' => $family_member_id,
        'fee'              => $fee,
        'consultation_fee' => $amount,
        'coupon_id'        => $this->input->post('applied_coupon_id'),
        'coupon_name'      => $this->input->post('applied_coupon_code'),
        'coupon_percentage'=> $this->input->post('applied_coupon_discount'),
        'coupon_discount'  => $this->input->post('applied_coupon_amount'),
        'payment_type'     => 'online',
        'transaction_id'   => '',   // will fill later
        'booking_status'   => 'pending',
        'status'           => 'unpaid',
        'booked_by'        =>  $booked_by,
        'created_on'       => date('Y-m-d H:i:s')
    ];
    $insert = $this->registermodel->common_insert('doctor_bookings', $data);

    $bkid = sprintf('%04d',$insert);
    $booking_id = 'BKID_'.$bkid;
    $this->registermodel->common_update('doctor_bookings',['booking_id' => $booking_id],['id' => $insert]);

    // --- Create Cashfree order ---
    $payload = [
        "order_amount" => $amount,
        "order_currency" => "INR",
        "customer_details" => [
            "customer_id"   => $customer_id,
            "customer_phone"=> $customer_phone,
            "customer_email"=> $customer_email
        ],
        "order_meta" => [
            // ✅ Will receive order_id from Cashfree
            "return_url" => base_url("admin/register/cashfree_callback?order_id={order_id}")
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders");
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
        "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_id'])) {
        // ✅ Save Cashfree generated order_id in booking
        $this->registermodel->common_update(
            'doctor_bookings',
            ['transaction_id' => $res['order_id']],
            ['id' => $insert]
        );
    }

    // Send only required values to frontend
    echo json_encode([
        'order_id' => $res['order_id'] ?? null,
        'payment_session_id' => $res['payment_session_id'] ?? null
    ]);
}
public function cashfree_callback() {
    $order_id = $this->input->get('order_id');

    // Verify payment with Cashfree API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders/" . $order_id);
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders/" . $order_id);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
         "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
         "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01"
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_status']) && $res['order_status'] === 'PAID') {
        // ✅ Update booking row
        $this->db->where('transaction_id', $order_id)
                 ->update('doctor_bookings', [
                     'status' => 'paid',
                     'booking_status' => 'booked'
                 ]);

        // Mark slot as booked
        $booking_details = $this->registermodel->common_fetch_select(
            'doctor_bookings',
            ['transaction_id' => $order_id],
            'slot_id,user_id,booking_id,family_member_id,doctor_id,main_data_id,consult_type,date,time',
            []
        );
        if (!empty($booking_details)) {
            $this->registermodel->common_update(
                'doctor_slots',
                ['booking_status' => 'booked'],
                ['id' => $booking_details[0]['slot_id']]
            );
        }
        
        $user_details                   = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
        $family_member_details          = $this->registermodel->common_fetch('family_members',['id' => $booking_details[0]['family_member_id']]);
        $doctor_details                 = $this->registermodel->common_fetch('doctors',['id' => $booking_details[0]['doctor_id']]);
        
        $main_data_details    = $this->registermodel->common_fetch('main_data',['id' => $booking_details[0]['main_data_id']]);
        
        if($booking_details[0]['consult_type']=='online'){
            $ct = 'Online';
        }else{
           $ct = 'Offline'; 
        }
        
        $user_id        = $user_details[0]['id'];
        $doctor_id      = $doctor_details[0]['id'];
        $date           = $booking_details[0]['date'];
        $time           = $booking_details[0]['time'];
        $booking_id     = $booking_details[0]['booking_id'];
        
        /*user_notification*/
        $data1 = array(
           'member_id'          => $user_id,
           'title'              => 'Med Rayder',
           'message'            => "{$ct} consultation with Dr. {$doctor_details[0]['name']} on {$date} at {$time} (Booking ID: {$booking_id}) has been booked successfully",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data1['title'];
        $message['body'] = $data1['message'];
        $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('user_notifications',$data1);
        /*user_notification*/
        
        /*doctor_notification*/
        $data = array(
           'member_id'          => $doctor_id,
           'title'              => 'Med Rayder',
           'message'            => "{$family_member_details[0]['name']} has booked a {$ct} consultation on {$date} at {$time} (Booking ID: {$booking_id})",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data['title'];
        $message['body'] = $data['message'];
        $this->sendNotification($doctor_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('doctor_notifications',$data);
        
        $this->sendNotification($main_data_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $rr = $this->send_web_notification($main_data_details[0]['web_player_id'],$message['title'],$message['body']);//exit;
        $data['member_id'] = $main_data_details[0]['id'];
        $insert_notifications = $this->registermodel->common_insert('main_data_notifications',$data);
        
        /*doctor_notification*/

        // Redirect with toast message
        $this->session->set_flashdata('success', 'Payment Successful! Booking confirmed.');
        redirect('admin/register/op_booking');

    } else {
        // ❌ Delete booking if payment failed
        $this->db->where('transaction_id', $order_id)
                 ->delete('doctor_bookings');

        // Redirect with error toast
        $this->session->set_flashdata('error', 'Payment Failed! Please try again.');
        redirect('admin/register/op_booking');

    }
}
/*op_booking*/

/*doctor_booking*/
public function get_hospital_online_doctors($hospital_id,$speciality_id){
    $doctors = $this->db->select('id, name,online_fee')
                               ->from('doctors')
                               ->where(['main_data_id' => $hospital_id, 'speciality_id' => $speciality_id,'consult_type' => 'online','availability' => 1,'status' => 1, 'delete_status' => 1])
                               ->get()
                               ->result_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'doctors' => $doctors
        ]));
}
public function get_hospital_online_doctor_dates($hospital_id,$doctor_id){
    $dates = $this->registermodel->get_hospital_online_doctor_dates($hospital_id,$doctor_id);
    
    //echo $this->db->last_query();exit;

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'dates' => $dates
        ]));
}
public function doctor_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/doctor_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function create_hospital_online_doctor_cashfree_order() {
    $fee         = $this->input->post('fee'); 
    $amount      = $this->input->post('consultation_fee'); 
    $customer_id = $this->input->post('user_id');
    $main_data_id = $this->input->post('main_data_id');
    $slot_id      = $this->input->post('time');
    $family_member_id = $this->input->post('family_member_id');

    // Get details for saving booking
    $user_details = $this->registermodel->common_fetch_select('users', ['id' => $customer_id], 'email,mobile', []);
    $hospital_details = $this->registermodel->common_fetch_select('main_data', ['id' => $main_data_id], 'cat_id', []);
    $slot_details = $this->registermodel->common_fetch_select('doctor_slots', ['id' => $slot_id], 'time', []);
    $family_member_details = $this->registermodel->common_fetch_select('family_members', ['id' => $family_member_id], 'name,mobile', []);

    $customer_phone = $user_details[0]['mobile'] ?? '';
    $customer_email = $user_details[0]['email'] ?? '';
    
    if (empty($slot_id)) {
        echo json_encode(['success' => false, 'message' => 'Please select time slot']);
        return;
    }
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    // --- Save booking row as pending ---
    $data = [
        'user_id'          => $customer_id,
        'main_data_id'     => $main_data_id,
        'cat_id'           => $hospital_details[0]['cat_id'] ?? null,
        'speciality_id'    => $this->input->post('speciality_id'),
        'doctor_id'        => $this->input->post('doctor_id'),
        'consult_type'     => 'online',
        'date'             => $this->input->post('date'),
        'slot_id'          => $slot_id,
        'time'             => $slot_details[0]['time'] ?? '',
        'mobile'           => $user_details[0]['mobile'] ?? '',
        'patient_name'     => $family_member_details[0]['name'] ?? '',
        'family_member_id' => $family_member_id,
        'fee'              => $fee,
        'consultation_fee' => $amount,
        'coupon_id'        => $this->input->post('applied_coupon_id'),
        'coupon_name'      => $this->input->post('applied_coupon_code'),
        'coupon_percentage'=> $this->input->post('applied_coupon_discount'),
        'coupon_discount'  => $this->input->post('applied_coupon_amount'),
        'payment_type'     => 'online',
        'transaction_id'   => '',   // will fill later
        'booking_status'   => 'pending',
        'status'           => 'unpaid',
        'booked_by'        =>  $booked_by,
        'created_on'       => date('Y-m-d H:i:s')
    ];
    $insert = $this->registermodel->common_insert('doctor_bookings', $data);

    $bkid = sprintf('%04d',$insert);
    $booking_id = 'BKID_'.$bkid;
    $this->registermodel->common_update('doctor_bookings',['booking_id' => $booking_id],['id' => $insert]);

    // --- Create Cashfree order ---
    $payload = [
        "order_amount" => $amount,
        "order_currency" => "INR",
        "customer_details" => [
            "customer_id"   => $customer_id,
            "customer_phone"=> $customer_phone,
            "customer_email"=> $customer_email
        ],
        "order_meta" => [
            // ✅ Will receive order_id from Cashfree
            "return_url" => base_url("admin/register/cashfree_hospital_online_doctor_callback?order_id={order_id}")
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders");
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
        "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_id'])) {
        // ✅ Save Cashfree generated order_id in booking
        $this->registermodel->common_update(
            'doctor_bookings',
            ['transaction_id' => $res['order_id']],
            ['id' => $insert]
        );
    }

    // Send only required values to frontend
    echo json_encode([
        'order_id' => $res['order_id'] ?? null,
        'payment_session_id' => $res['payment_session_id'] ?? null
    ]);
}
public function cashfree_hospital_online_doctor_callback() {
    $order_id = $this->input->get('order_id');

    // Verify payment with Cashfree API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders/" . $order_id);
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders/" . $order_id);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
         "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
         "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01"
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_status']) && $res['order_status'] === 'PAID') {
        // ✅ Update booking row
        $this->db->where('transaction_id', $order_id)
                 ->update('doctor_bookings', [
                     'status' => 'paid',
                     'booking_status' => 'booked'
                 ]);

        // Mark slot as booked
        $booking_details = $this->registermodel->common_fetch_select(
            'doctor_bookings',
            ['transaction_id' => $order_id],
            'slot_id,user_id,booking_id,family_member_id,doctor_id,main_data_id,consult_type,date,time',
            []
        );
        if (!empty($booking_details)) {
            $this->registermodel->common_update(
                'doctor_slots',
                ['booking_status' => 'booked'],
                ['id' => $booking_details[0]['slot_id']]
            );
        }
        
        $user_details                   = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
        $family_member_details          = $this->registermodel->common_fetch('family_members',['id' => $booking_details[0]['family_member_id']]);
        $doctor_details                 = $this->registermodel->common_fetch('doctors',['id' => $booking_details[0]['doctor_id']]);
        
        $main_data_details    = $this->registermodel->common_fetch('main_data',['id' => $booking_details[0]['main_data_id']]);
        
        if($booking_details[0]['consult_type']=='online'){
            $ct = 'Online';
        }else{
           $ct = 'Offline'; 
        }
        
        $user_id        = $user_details[0]['id'];
        $doctor_id      = $doctor_details[0]['id'];
        $date           = $booking_details[0]['date'];
        $time           = $booking_details[0]['time'];
        $booking_id     = $booking_details[0]['booking_id'];
        
        /*user_notification*/
        $data1 = array(
           'member_id'          => $user_id,
           'title'              => 'Med Rayder',
           'message'            => "{$ct} consultation with Dr. {$doctor_details[0]['name']} on {$date} at {$time} (Booking ID: {$booking_id}) has been booked successfully",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data1['title'];
        $message['body'] = $data1['message'];
        $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('user_notifications',$data1);
        /*user_notification*/
        
        /*doctor_notification*/
        $data = array(
           'member_id'          => $doctor_id,
           'title'              => 'Med Rayder',
           'message'            => "{$family_member_details[0]['name']} has booked a {$ct} consultation on {$date} at {$time} (Booking ID: {$booking_id})",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data['title'];
        $message['body'] = $data['message'];
        $this->sendNotification($doctor_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('doctor_notifications',$data);
        
        $this->sendNotification($main_data_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $rr = $this->send_web_notification($main_data_details[0]['web_player_id'],$message['title'],$message['body']);//exit;
        $data['member_id'] = $main_data_details[0]['id'];
        $insert_notifications = $this->registermodel->common_insert('main_data_notifications',$data);
        
        /*doctor_notification*/

        // Redirect with toast message
        $this->session->set_flashdata('success', 'Payment Successful! Booking confirmed.');
        redirect('admin/register/doctor_booking');

    } else {
        // ❌ Delete booking if payment failed
        $this->db->where('transaction_id', $order_id)
                 ->delete('doctor_bookings');

        // Redirect with error toast
        $this->session->set_flashdata('error', 'Payment Failed! Please try again.');
        redirect('admin/register/doctor_booking');

    }
}
/*doctor_booking*/

/*hospital_pharmacy_medicine_booking*/
public function hospital_pharmacy_medicine_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/hospital_pharmacy_medicine_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function get_hospital_details($hospital_id){
    $this->db->select('main_data.id, main_data.home_delivery');
    $this->db->from('main_data');
    $this->db->where(['main_data.id' => $hospital_id]);
    $main_data = $this->db->get()->row_array();
    
    if ($main_data && $main_data['home_delivery'] == 'yes') {
        $order_type = ['pickup' => 'Pickup', 'home_delivery' => 'Home Delivery'];
    } else {
        $order_type = ['pickup' => 'Pickup'];
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'message' => 'Order type fetched successfully',
            'order_type' => $order_type
        ]));
}
public function get_address($hospital_id,$order_type,$user_id){
    if($order_type=='home_delivery'){
        
        $address = $this->registermodel->common_fetch('user_addresses',['user_id' => $user_id,'default_address' => 1]);
        
        //echo $this->db->last_query();exit;
        
        if(!empty($address)){
            return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => true,
                'message' => 'address fetched successfully',
                'address' => $address[0]['address'] ?? '',
                'address_id' => $address[0]['id'] ?? '',
                'lat' => $address[0]['lat'] ?? '',
                'lon' => $address[0]['lon'] ?? ''
            ]));
        }else{
            return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => false,
                'message' => 'no address found',
                'address' => $address[0]['address'] ?? '',
                'address_id' => $address[0]['id'] ?? '',
                'lat' => $address[0]['lat'] ?? '',
                'lon' => $address[0]['lon'] ?? ''
            ]));
        }
        
    }else{
        $address = $this->registermodel->common_fetch('main_data',['id' => $hospital_id],[]);
        
        if(!empty($address)){
            return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => true,
                'message' => 'address fetched successfully',
                'address' => $address[0]['location'] ?? '',
                'address_id' => '',
                'lat' => $address[0]['lat'] ?? '',
                'lon' => $address[0]['lon'] ?? ''
            ]));
        }else{
            return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => false,
                'message' => 'no address found',
                'address' => $address[0]['location'] ?? '',
                'address_id' => '',
                'lat' => $address[0]['lat'] ?? '',
                'lon' => $address[0]['lon'] ?? ''
            ]));
        }
    }
}
public function insert_hospital_pharmacy_prescription_booking(){
    $config['upload_path']			= $this->bharosa_base_path . 'pharmacy_orders/';
	$config['allowed_types']        = 'jpeg|jpg|png|pdf';
	$config['file_name']            = time();
	//$config['max_size']             = 2048;
	//print_r($config);exit;
	$this->load->library('upload',$config);
	$this->upload->initialize($config,true);
	if (!$this->upload->do_upload('image')) {
        // File upload failed
        $error = $this->upload->display_errors();
        echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
        return;
    }
    
    // File upload success
    $uploadData = $this->upload->data();
    $photo = 'assets/admin/pharmacy_orders/'.$uploadData['file_name'];
    
    $user_id        = $this->input->post('user_id');
    
    $user_details = $this->registermodel->common_fetch_select('users',['id' => $user_id],'name,mobile',[]);
    
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    
    $data = [
        'user_id'        => $this->input->post('user_id'),
        'main_data_id'   => $this->input->post('main_data_id'),
        'address_id'     => $this->input->post('address'),
        'order_type'     => $this->input->post('order_type'),
        'name'           => $user_details[0]['name'],
        'mobile'         => $user_details[0]['mobile'],
        'image'          => $photo,
        'booking_status' => 'booked',
        'booked_by'      =>  $booked_by,
        'created_on'     => date('Y-m-d H:i:s')
    ];
    $insert = $this->registermodel->common_insert('hospital_pharmacy_medicine_orders', $data);
    $bkid = sprintf('%04d', $insert);
    $booking_id = 'BKID_' . $bkid;
    
    $this->registermodel->common_update('hospital_pharmacy_medicine_orders', ['booking_id' => $booking_id], ['id' => $insert]);
    
    $booking_details = $this->registermodel->common_fetch('hospital_pharmacy_medicine_orders',['id' => $insert]);
    $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
    //echo $this->db->last_query();exit;
    $pharmacies_details = $this->registermodel->common_fetch('main_data',['id' => $booking_details[0]['main_data_id']]);
    /*user_notification*/
    $data = array(
       'member_id'          => $booking_details[0]['user_id'],
       'title'              => 'Med Rayder',
       'message'            => "Your Hospital pharmacy prescription booking (Booking ID: {$booking_details[0]['booking_id']}) has been successfully placed. The pharmacy will review and accept your booking shortly",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data['title']; 
    $message['body'] = $data['message'];
    $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
    /*user_notification*/
    
    /*pharmacy_notification*/
    $data1 = array(
       'member_id'          => $booking_details[0]['main_data_id'],
       'title'              => 'Med Rayder',
       'message'            => "You have received a new pharmacy prescription booking (Booking ID: {$booking_details[0]['booking_id']}). Please review and accept the order to begin processing",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array(); 
    $message['title'] = $data1['title'];
    $message['body'] = $data1['message'];
    $this->sendNotification($pharmacies_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $rr = $this->send_web_notification($pharmacies_details[0]['web_player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('main_data_notifications',$data1);
    /*pharmacy_notification*/
    
    echo json_encode(['success' => true, 'message' => 'hospital pharmacy prescription order booked successfully']);
    return;
}
/*hospital_pharmacy_medicine_booking*/

/*hospital_diagnostic_prescription_booking*/
public function hospital_diagnostic_prescription_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/hospital_diagnostic_prescription_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_hospital_diagnostic_prescription_booking(){
    $config['upload_path']			= $this->bharosa_base_path . 'diagnostic_prescription_bookings/';
	$config['allowed_types']        = 'jpeg|jpg|png|pdf';
	$config['file_name']            = time();
	//$config['max_size']             = 2048;
	//print_r($config);exit;
	$this->load->library('upload',$config);
	$this->upload->initialize($config,true);
	if (!$this->upload->do_upload('image')) {
        // File upload failed
        $error = $this->upload->display_errors();
        echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
        return;
    }
    
    // File upload success
    $uploadData = $this->upload->data();
    $photo = 'assets/admin/diagnostic_prescription_bookings/'.$uploadData['file_name'];
    
    $user_id             = $this->input->post('user_id');
    $main_data_id        = $this->input->post('main_data_id');
    
    $user_details = $this->registermodel->common_fetch_select('users',['id' => $user_id],'name,mobile',[]);
    
    $diagnostic_data = $this->registermodel->common_fetch_select('main_data', ['id' => $main_data_id], 'name,logo,location', []);
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
        
    $data = [
        'user_id'          => $user_id,
        'main_data_id'     => $main_data_id,
        'diagnostic_name'  => $diagnostic_data[0]['name'],
        'logo'             => $diagnostic_data[0]['logo'],
        'family_member_id' => $this->input->post('family_member_id'),
        'name'             => $user_details[0]['name'],
        'mobile'           => $user_details[0]['mobile'],
        'booking_type'     => 'prescription_booking',
        'image'            => $photo,
        'booking_status'   => 'booked',
        'booked_by'              =>  $booked_by,
        'created_on'       => date('Y-m-d H:i:s')
    ];
    $insert = $this->registermodel->common_insert('hospital_diagnostic_prescription_bookings', $data);
    $bkid = sprintf('%04d', $insert);
    $booking_id = 'BKID_' . $bkid;
    $this->registermodel->common_update('hospital_diagnostic_prescription_bookings', ['booking_id' => $booking_id], ['id' => $insert]);
    
    $booking_details = $this->registermodel->common_fetch('hospital_diagnostic_prescription_bookings',['id' => $insert]);
    $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
    //echo $this->db->last_query();exit;
    $diagnostic_details = $this->registermodel->common_fetch('main_data',['id' => $booking_details[0]['main_data_id']]);
    /*user_notification*/
    $data = array(
       'member_id'          => $booking_details[0]['user_id'],
       'title'              => 'Med Rayder',
       'message'            => "Your hospital diagnostic prescription booking (Booking ID: {$booking_details[0]['booking_id']}) has been placed successfully. Our team will review your prescription and get back to you shortly",           
	   'created_on
'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data['title']; 
    $message['body'] = $data['message'];
    $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
    /*user_notification*/
    
    /*diagnostic_notification*/
    $data1 = array(
       'member_id'          => $booking_details[0]['main_data_id'],
       'title'              => 'Med Rayder',
       'message'            => "New diagnostic prescription booking received (Booking ID: {$booking_details[0]['booking_id']}). Kindly verify the prescription and proceed with scheduling or confirmation",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data1['title'];
    $message['body'] = $data1['message'];
    $this->sendNotification($diagnostic_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $rr = $this->send_web_notification($diagnostic_details[0]['web_player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('main_data_notifications',$data1);
    /*diagnostic_notification*/
    
    echo json_encode(['success' => true, 'message' => 'hospital disgnostic prescription order booked successfully']);
    return;
}
/*hospital_diagnostic_prescription_booking*/

/*hospital_diagnostic_booking*/
public function get_hospital_diagnostic_tests($hospital_id) {
    $page   = (int)$this->input->post('page') ?: 1;
    $limit  = 10; // items per page
    $offset = ($page - 1) * $limit;
    $search = $this->input->post('search');

    // Select tests with subquery for total_test_count
    $this->db->select("hospital_diagnostic_packages.*,
        (
            (SELECT COUNT(*) 
             FROM hospital_diagnostic_tests hdbt 
             WHERE hdbt.package_id = hospital_diagnostic_packages.id) 
        ) AS total_test_count", false);

    $this->db->from('hospital_diagnostic_packages');
    $this->db->where([
        'main_data_id'   => $hospital_id,
        'status'         => 1,
        'delete_status'  => 1
    ]);

    if (!empty($search)) {
        $this->db->like('name', $search);
    }

    // clone query for total count
    $clone_db = clone $this->db;
    $total = $clone_db->count_all_results();

    // apply limit+offset for current page
    $this->db->limit($limit, $offset);
    $query = $this->db->get();
    $tests = $query->result_array();

    // check if more data available
    $has_more = ($total > ($page * $limit));

    if (!empty($tests)) {
        echo json_encode([
            'success'   => true,
            'packages'  => $tests,
            'total'     => $total,
            'page'      => $page,
            'limit'     => $limit,
            'has_more'  => $has_more
        ]);
    } else {
        echo json_encode([
            'success'   => false,
            'message'   => 'No diagnostic packages found.',
            'packages'  => [],
            'total'     => 0,
            'page'      => $page,
            'limit'     => $limit,
            'has_more'  => false
        ]);
    }
}
public function get_hospital_diagnostic_tests_subtests($test_id) {
    $data = $this->registermodel->get_hospital_diagnostic_tests_subtests($test_id);

    echo json_encode([
        'success' => true,
        'tests'   => $data
    ]);
}
public function get_hospital_diagnostic_dates($hospital_id){
    $dates = $this->registermodel->get_hospital_diagnostic_dates($hospital_id);
    
    //echo $this->db->last_query();exit;

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'dates' => $dates
        ]));
}
public function get_hospital_diagnostic_slots_by_date(){
    $date = $this->input->post('date'); // Y-m-d
    $main_data_id = $this->input->post('hospital_id');
    
    $slots = $this->registermodel->get_hospital_diagnostic_slots($main_data_id,$date);
    
    //echo $this->db->last_query();exit;
    
    echo json_encode($slots);
}
public function get_hospital_diagnostic_couponss(){
    $coupons = $this->db->select('id, name,percentage,description')
                               ->from('hospital_diagnostic_coupons')
                               ->where(['status' => 1, 'delete_status' => 1])
                               ->get()
                               ->result_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'coupons' => $coupons
        ]));
}
public function get_hospital_diagnostic_package_prices($test_id) {
    $row = $this->registermodel->common_fetch(
        'hospital_diagnostic_packages',
        ['id' => $test_id],
        'one_person,one_person_discount,two_person,two_person_discount,three_person,three_person_discount,four_person,four_person_discount,five_person,five_person_discount'
    );

    $prices = [];
    if (!empty($row)) {
        $row = $row[0]; // single record

        $prices = [
            [
                'persons_count'   => 1,
                'original_price'  => $row['one_person'],
                'discounted_price'=> $row['one_person_discount']
            ],
            [
                'persons_count'   => 2,
                'original_price'  => $row['two_person'],
                'discounted_price'=> $row['two_person_discount']
            ],
            [
                'persons_count'   => 3,
                'original_price'  => $row['three_person'],
                'discounted_price'=> $row['three_person_discount']
            ],
            [
                'persons_count'   => 4,
                'original_price'  => $row['four_person'],
                'discounted_price'=> $row['four_person_discount']
            ],
            [
                'persons_count'   => 5,
                'original_price'  => $row['five_person'],
                'discounted_price'=> $row['five_person_discount']
            ],
        ];
    }

    echo json_encode([
        'success'   => true,
        'message'   => 'Prices fetched successfully',
        'prices'    => $prices
    ]);
}
public function hospital_diagnostic_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['states'] = $this->registermodel->common_fetch('states',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('main_data',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/hospital_diagnostic_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function create_hospital_diagnostic_cashfree_order() {
    $fee         = $this->input->post('fee'); 
    $amount      = $this->input->post('consultation_fee'); 
    $customer_id = $this->input->post('user_id');
    $main_data_id = $this->input->post('main_data_id');
    $slot_id      = $this->input->post('time');
    $family_member_id = $this->input->post('family_member_id');
    
    $image = $this->input->post('image');
    
    $imp = implode(',',$family_member_id);
    $count = count($family_member_id);
    
    //$exp = explode('');

    // Get details for saving booking
    $user_details = $this->registermodel->common_fetch_select('users', ['id' => $customer_id], 'email,mobile,name', []);
    $diagnostic_data = $this->registermodel->common_fetch_select('main_data', ['id' => $main_data_id], 'cat_id,name,logo', []);
    $slot_details = $this->registermodel->common_fetch_select('	hospital_diagnostic_slots', ['id' => $slot_id], 'time', []);
    //$family_member_details = $this->registermodel->common_fetch_select('family_members', ['id' => $family_member_id], 'name,mobile', []);

    $customer_phone = $user_details[0]['mobile'] ?? '';
    $customer_email = $user_details[0]['email'] ?? '';
    $customer_name = $user_details[0]['name'] ?? '';
    
    if (empty($slot_id)) {
        echo json_encode(['success' => false, 'message' => 'Please select time slot']);
        return;
    }
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    // --- Save booking row as pending ---
    $data = [
      'user_id'             => $this->input->post('user_id'),
      'main_data_id'        => $main_data_id,
      'diagnostic_name'     => $diagnostic_data[0]['name'],
      'logo'                => $diagnostic_data[0]['logo'],
      //'location'            => $diagnostic_data[0]['location'],
      'test_id'             => $this->input->post('applied_coupon_id'),
      'count'               => $count,
      'date'                => $this->input->post('date'),
      'slot_id'             => $slot_id,
      'time'                => $slot_details[0]['time'],
      'mobile'              => $customer_phone,
      'name'                => $customer_name,
      'family_member_id'    => $imp,
      'fee'                 => $fee,
      'consultation_fee'    => $this->input->post('consultation_fee'),
      //'flat_discount'       => $this->input->post('flat_discount'),
      'payment_type'        => 'online',
      'booking_type'        => 'product_booking',
      'booking_status'      => 'booked',
      //'wallet_amount'     => $wallet_amount,
      'coupon_id'           => $this->input->post('applied_coupon_idd'),
      'coupon_name'         => $this->input->post('applied_coupon_codee'),
      'coupon_percentage'   => $this->input->post('applied_coupon_discountt'),
      'coupon_discount'     => $this->input->post('applied_coupon_amountt'),
      'transaction_id'      => '',
      'booking_status'      => 'pending',
      'status'              => 'unpaid',
      'booked_by'              =>  $booked_by,
      'created_on'          => date('Y-m-d H:i:s')
    ];
    if($_FILES['image']['name']!==""){
        $config['upload_path']			= $this->bharosa_base_path . 'diagnostic_prescription_bookings/';
    	$config['allowed_types']        = 'jpeg|jpg|png|pdf';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/diagnostic_prescription_bookings/'.$uploadData['file_name'];
        $data['image']  = $photo;
    }else{
       $data['image']  = ''; 
    }
    $insert = $this->registermodel->common_insert('hospital_diagnostic_bookings',$data);
    $bkid = sprintf('%04d',$insert);
    $booking_id = 'BKID_'.$bkid;
    $update = $this->registermodel->common_update('hospital_diagnostic_bookings',['booking_id' => $booking_id],['id' => $insert]);

    // --- Create Cashfree order ---
    $payload = [
        "order_amount" => $amount,
        "order_currency" => "INR",
        "customer_details" => [
            "customer_id"   => $customer_id,
            "customer_phone"=> $customer_phone,
            "customer_email"=> $customer_email
        ],
        "order_meta" => [
            // ✅ Will receive order_id from Cashfree
            "return_url" => base_url("admin/register/cashfree_hospital_diagnostic_callback?order_id={order_id}")
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders");
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
        "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_id'])) {
        // ✅ Save Cashfree generated order_id in booking
        $this->registermodel->common_update(
            'hospital_diagnostic_bookings',
            ['transaction_id' => $res['order_id']],
            ['id' => $insert]
        );
    }

    // Send only required values to frontend
    echo json_encode([
        'order_id' => $res['order_id'] ?? null,
        'payment_session_id' => $res['payment_session_id'] ?? null
    ]);
}
public function cashfree_hospital_diagnostic_callback() {
    $order_id = $this->input->get('order_id');

    // Verify payment with Cashfree API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders/" . $order_id);
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders/" . $order_id);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
         "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
         "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01"
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_status']) && $res['order_status'] === 'PAID') {
        // ✅ Update booking row
        $this->db->where('transaction_id', $order_id)
                 ->update('hospital_diagnostic_bookings', [
                     'status' => 'paid',
                     'booking_status' => 'booked'
                 ]);

        // Mark slot as booked
        $booking_details = $this->registermodel->common_fetch_select(
            'hospital_diagnostic_bookings',
            ['transaction_id' => $order_id],
            'slot_id,user_id,booking_id,family_member_id,main_data_id,date,time,test_id',
            []
        );
        $update = $this->registermodel->common_update('hospital_diagnostic_slots',['booking_status' => 'booked'],['id' => $booking_details[0]['slot_id']]);
        $diagnostic_data = $this->registermodel->get_single_hospital_diagnostic_tests($booking_details[0]['test_id']);
        $this->registermodel->save_hospital_diagnostic_booking_snapshot($booking_details[0]['booking_id'], $diagnostic_data);
        
        $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
        //echo $this->db->last_query();exit;
        $diagnostic_details = $this->registermodel->common_fetch('main_data',['id' => $booking_details[0]['main_data_id']]);
        /*user_notification*/
        $data = array(
           'member_id'          => $booking_details[0]['user_id'],
           'title'              => 'Med Rayder',
           'message'            => "Your hospital diagnostic booking (Booking ID: {$booking_details[0]['booking_id']}) has been successfully placed. You will receive confirmation once the lab accepts the booking. Please be ready at your scheduled date and time",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data['title']; 
        $message['body'] = $data['message'];
        $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
        /*user_notification*/
        
        /*diagnostic_notification*/
        $data1 = array(
           'member_id'          => $booking_details[0]['main_data_id'],
           'title'              => 'Med Rayder',
           'message'            => "You have received a new diagnostic booking (Booking ID: {$booking_details[0]['booking_id']}). Please review and accept the booking to proceed with the test appointment",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data1['title'];
        $message['body'] = $data1['message'];
        $this->sendNotification($diagnostic_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $rr = $this->send_web_notification($diagnostic_details[0]['web_player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('main_data_notifications',$data1);
        /*diagnostic_notification*/

        // Redirect with toast message
        $this->session->set_flashdata('success', 'Payment Successful! Booking confirmed.');
        redirect('admin/register/hospital_diagnostic_booking');

    } else {
        // ❌ Delete booking if payment failed
        $this->db->where('transaction_id', $order_id)
                 ->delete('hospital_diagnostic_bookings');

        // Redirect with error toast
        $this->session->set_flashdata('error', 'Payment Failed! Please try again.');
        redirect('admin/register/hospital_diagnostic_booking');

    }
}
/*hospital_diagnostic_booking*/

/*pharmacy_medicine_booking*/
public function pharmacy_medicine_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('pharmacies',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/pharmacy_medicine_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function get_pharmacy_details($hospital_id){
    $this->db->select('pharmacies.id, pharmacies.home_delivery');
    $this->db->from('pharmacies');
    $this->db->where(['pharmacies.id' => $hospital_id]);
    $main_data = $this->db->get()->row_array();
    
    if ($main_data && $main_data['home_delivery'] == 'yes') {
        $order_type = ['pickup' => 'Pickup', 'home_delivery' => 'Home Delivery'];
    } else {
        $order_type = ['pickup' => 'Pickup'];
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'message' => 'Order type fetched successfully',
            'order_type' => $order_type
        ]));
}
public function get_pharmacy_address($hospital_id,$order_type,$user_id){
    if($order_type=='home_delivery'){
        
        $address = $this->registermodel->common_fetch('user_addresses',['user_id' => $user_id,'default_address' => 1]);
        
        //echo $this->db->last_query();exit;
        
        if(!empty($address)){
            return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => true,
                'message' => 'address fetched successfully',
                'address' => $address[0]['address'] ?? '',
                'address_id' => $address[0]['id'] ?? '',
                'lat' => $address[0]['lat'] ?? '',
                'lon' => $address[0]['lon'] ?? ''
            ]));
        }else{
            return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => false,
                'message' => 'no address found',
                'address' => $address[0]['address'] ?? '',
                'address_id' => $address[0]['id'] ?? '',
                'lat' => $address[0]['lat'] ?? '',
                'lon' => $address[0]['lon'] ?? ''
            ]));
        }
        
    }else{
        $address = $this->registermodel->common_fetch('pharmacies',['id' => $hospital_id],[]);
        
        if(!empty($address)){
            return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => true,
                'message' => 'address fetched successfully',
                'address' => $address[0]['location'] ?? '',
                'address_id' => '',
                'lat' => $address[0]['lat'] ?? '',
                'lon' => $address[0]['lon'] ?? ''
            ]));
        }else{
            return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => false,
                'message' => 'no address found',
                'address' => $address[0]['location'] ?? '',
                'address_id' => '',
                'lat' => $address[0]['lat'] ?? '',
                'lon' => $address[0]['lon'] ?? ''
            ]));
        }
    }
}
public function insert_pharmacy_prescription_booking(){
    $config['upload_path']			= $this->bharosa_base_path . 'pharmacy_orders/';
	$config['allowed_types']        = 'jpeg|jpg|png|pdf';
	$config['file_name']            = time();
	//$config['max_size']             = 2048;
	//print_r($config);exit;
	$this->load->library('upload',$config);
	$this->upload->initialize($config,true);
	if (!$this->upload->do_upload('image')) {
        // File upload failed
        $error = $this->upload->display_errors();
        echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
        return;
    }
    
    // File upload success
    $uploadData = $this->upload->data();
    $photo = 'assets/admin/pharmacy_orders/'.$uploadData['file_name'];
    
    $user_id        = $this->input->post('user_id');
    
    $user_details = $this->registermodel->common_fetch_select('users',['id' => $user_id],'name,mobile',[]);
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    
    $data = [
        'user_id'        => $this->input->post('user_id'),
        'main_data_id'   => $this->input->post('main_data_id'),
        'address_id'     => $this->input->post('address'),
        'order_type'     => $this->input->post('order_type'),
        'name'           => $user_details[0]['name'],
        'mobile'         => $user_details[0]['mobile'],
        'image'          => $photo,
        'booking_status' => 'booked',
        'booked_by'              =>  $booked_by,
        'created_on'     => date('Y-m-d H:i:s')
    ];
    $insert = $this->registermodel->common_insert('pharmacy_medicine_orders', $data);
    $bkid = sprintf('%04d', $insert);
    $booking_id = 'BKID_' . $bkid;
    
    $this->registermodel->common_update('pharmacy_medicine_orders', ['booking_id' => $booking_id], ['id' => $insert]);
    
    $booking_details = $this->registermodel->common_fetch('pharmacy_medicine_orders',['id' => $insert]);
    $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
    //echo $this->db->last_query();exit;
    $pharmacies_details = $this->registermodel->common_fetch('pharmacies',['id' => $booking_details[0]['main_data_id']]);
    /*user_notification*/
    $data = array(
       'member_id'          => $booking_details[0]['user_id'],
       'title'              => 'Med Rayder',
       'message'            => "Your pharmacy prescription booking (Booking ID: {$booking_details[0]['booking_id']}) has been successfully placed. The pharmacy will review and accept your booking shortly",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data['title']; 
    $message['body'] = $data['message'];
    $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
    /*user_notification*/
    
    /*pharmacy_notification*/
    $data1 = array(
       'member_id'          => $booking_details[0]['main_data_id'],
       'title'              => 'Med Rayder',
       'message'            => "You have received a new pharmacy prescription booking (Booking ID: {$booking_details[0]['booking_id']}). Please review and accept the order to begin processing",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data1['title'];
    $message['body'] = $data1['message'];
    $this->sendNotification($pharmacies_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('pharmacy_notifications',$data1);
    /*pharmacy_notification*/
    
    echo json_encode(['success' => true, 'message' => 'hospital pharmacy prescription order booked successfully']);
    return;
}
/*pharmacy_medicine_booking*/

/*diagnostic_prescription_booking*/
public function diagnostic_prescription_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('diagnostics',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/diagnostic_prescription_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_diagnostic_prescription_booking(){
    $config['upload_path']			= $this->bharosa_base_path . 'diagnostic_prescription_bookings/';
	$config['allowed_types']        = 'jpeg|jpg|png|pdf';
	$config['file_name']            = time();
	//$config['max_size']             = 2048;
	//print_r($config);exit;
	$this->load->library('upload',$config);
	$this->upload->initialize($config,true);
	if (!$this->upload->do_upload('image')) {
        // File upload failed
        $error = $this->upload->display_errors();
        echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
        return;
    }
    
    // File upload success
    $uploadData = $this->upload->data();
    $photo = 'assets/admin/diagnostic_prescription_bookings/'.$uploadData['file_name'];
    
    $user_id             = $this->input->post('user_id');
    $main_data_id        = $this->input->post('main_data_id');
    
    $user_details = $this->registermodel->common_fetch_select('users',['id' => $user_id],'name,mobile',[]);
    
    $diagnostic_data = $this->registermodel->common_fetch_select('diagnostics', ['id' => $main_data_id], 'name,logo,location', []);
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    $data = [
        'user_id'          => $user_id,
        'main_data_id'     => $main_data_id,
        'diagnostic_name'  => $diagnostic_data[0]['name'],
        'logo'             => $diagnostic_data[0]['logo'],
        'family_member_id' => $this->input->post('family_member_id'),
        'name'             => $user_details[0]['name'],
        'mobile'           => $user_details[0]['mobile'],
        'booking_type'     => 'prescription_booking',
        'image'            => $photo,
        'booking_status'   => 'booked',
        'booked_by'        =>  $booked_by,
        'created_on'       => date('Y-m-d H:i:s')
    ];
    $insert = $this->registermodel->common_insert('diagnostic_prescription_bookings', $data);
    $bkid = sprintf('%04d', $insert);
    $booking_id = 'BKID_' . $bkid;
    $update = $this->registermodel->common_update('diagnostic_prescription_bookings', ['booking_id' => $booking_id], ['id' => $insert]);
    
    $booking_details = $this->registermodel->common_fetch('diagnostic_prescription_bookings',['id' => $insert]);
    $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
    //echo $this->db->last_query();exit;
    $diagnostic_details = $this->registermodel->common_fetch('diagnostics',['id' => $booking_details[0]['main_data_id']]);
    /*user_notification*/
    $data = array(
       'member_id'          => $booking_details[0]['user_id'],
       'title'              => 'Med Rayder',
       'message'            => "Your diagnostic prescription booking (Booking ID: {$booking_details[0]['booking_id']}) has been placed successfully. Our team will review your prescription and get back to you shortly",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data['title']; 
    $message['body'] = $data['message'];
    $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
    /*user_notification*/
    
    /*diagnostic_notification*/
    $data1 = array(
       'member_id'          => $booking_details[0]['main_data_id'],
       'title'              => 'Med Rayder',
       'message'            => "New diagnostic prescription booking received (Booking ID: {$booking_details[0]['booking_id']}). Kindly verify the prescription and proceed with scheduling or confirmation",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data1['title'];
    $message['body'] = $data1['message'];
    $this->sendNotification($diagnostic_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('diagnostic_notifications',$data1);
    /*diagnostic_notification*/
    
    echo json_encode(['success' => true, 'message' => 'disgnostic prescription order booked successfully']);
    return;
}
/*diagnostic_prescription_booking*/

/*diagnostic_booking*/
public function get_diagnostic_tests($hospital_id) {
    $page   = (int)$this->input->post('page') ?: 1;
    $limit  = 10; // items per page
    $offset = ($page - 1) * $limit;
    $search = $this->input->post('search');

    // Select tests with subquery for total_test_count
    $this->db->select("diagnostic_packages.*,
        (
            (SELECT COUNT(*) 
             FROM diagnostic_tests hdbt 
             WHERE hdbt.package_id = diagnostic_packages.id) 
        ) AS total_test_count", false);

    $this->db->from('diagnostic_packages');
    $this->db->where([
        'main_data_id'   => $hospital_id,
        'status'         => 1,
        'delete_status'  => 1
    ]);

    if (!empty($search)) {
        $this->db->like('name', $search);
    }

    // clone query for total count
    $clone_db = clone $this->db;
    $total = $clone_db->count_all_results();

    // apply limit+offset for current page
    $this->db->limit($limit, $offset);
    $query = $this->db->get();
    $tests = $query->result_array();

    // check if more data available
    $has_more = ($total > ($page * $limit));

    if (!empty($tests)) {
        echo json_encode([
            'success'   => true,
            'packages'  => $tests,
            'total'     => $total,
            'page'      => $page,
            'limit'     => $limit,
            'has_more'  => $has_more
        ]);
    } else {
        echo json_encode([
            'success'   => false,
            'message'   => 'No diagnostic packages found.',
            'packages'  => [],
            'total'     => 0,
            'page'      => $page,
            'limit'     => $limit,
            'has_more'  => false
        ]);
    }
}
public function get_diagnostic_tests_subtests($test_id) {
    $data = $this->registermodel->get_diagnostic_tests_subtests($test_id);

    echo json_encode([
        'success' => true,
        'tests'   => $data
    ]);
}
public function get_diagnostic_dates($hospital_id){
    $dates = $this->registermodel->get_diagnostic_dates($hospital_id);
    
    //echo $this->db->last_query();exit;

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'dates' => $dates
        ]));
}
public function get_diagnostic_slots_by_date(){
    $date = $this->input->post('date'); // Y-m-d
    $main_data_id = $this->input->post('hospital_id');
    
    $slots = $this->registermodel->get_diagnostic_slots($main_data_id,$date);
    
    //echo $this->db->last_query();exit;
    
    echo json_encode($slots);
}
public function get_diagnostic_package_prices($test_id) {
    $row = $this->registermodel->common_fetch(
        'diagnostic_packages',
        ['id' => $test_id],
        'one_person,one_person_discount,two_person,two_person_discount,three_person,three_person_discount,four_person,four_person_discount,five_person,five_person_discount'
    );

    $prices = [];
    if (!empty($row)) {
        $row = $row[0]; // single record

        $prices = [
            [
                'persons_count'   => 1,
                'original_price'  => $row['one_person'],
                'discounted_price'=> $row['one_person_discount']
            ],
            [
                'persons_count'   => 2,
                'original_price'  => $row['two_person'],
                'discounted_price'=> $row['two_person_discount']
            ],
            [
                'persons_count'   => 3,
                'original_price'  => $row['three_person'],
                'discounted_price'=> $row['three_person_discount']
            ],
            [
                'persons_count'   => 4,
                'original_price'  => $row['four_person'],
                'discounted_price'=> $row['four_person_discount']
            ],
            [
                'persons_count'   => 5,
                'original_price'  => $row['five_person'],
                'discounted_price'=> $row['five_person_discount']
            ],
        ];
    }

    echo json_encode([
        'success'   => true,
        'message'   => 'Prices fetched successfully',
        'prices'    => $prices
    ]);
}
public function create_diagnostic_cashfree_order() {
    $fee         = $this->input->post('fee'); 
    $amount      = $this->input->post('consultation_fee'); 
    $customer_id = $this->input->post('user_id');
    $main_data_id = $this->input->post('main_data_id');
    $slot_id      = $this->input->post('time');
    $family_member_id = $this->input->post('family_member_id');
    
    $image = $this->input->post('image');
    
    $imp = implode(',',$family_member_id);
    $count = count($family_member_id);
    
    //$exp = explode('');

    // Get details for saving booking
    $user_details = $this->registermodel->common_fetch_select('users', ['id' => $customer_id], 'email,mobile,name', []);
    $diagnostic_data = $this->registermodel->common_fetch_select('main_data', ['id' => $main_data_id], 'cat_id,name,logo', []);
    $slot_details = $this->registermodel->common_fetch_select('diagnostic_slots', ['id' => $slot_id], 'time', []);
    //$family_member_details = $this->registermodel->common_fetch_select('family_members', ['id' => $family_member_id], 'name,mobile', []);

    $customer_phone = $user_details[0]['mobile'] ?? '';
    $customer_email = $user_details[0]['email'] ?? '';
    $customer_name = $user_details[0]['name'] ?? '';
    
    if (empty($slot_id)) {
        echo json_encode(['success' => false, 'message' => 'Please select time slot']);
        return;
    }
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    // --- Save booking row as pending ---
    $data = [
      'user_id'             => $this->input->post('user_id'),
      'main_data_id'        => $main_data_id,
      'diagnostic_name'     => $diagnostic_data[0]['name'],
      'logo'                => $diagnostic_data[0]['logo'],
      //'location'            => $diagnostic_data[0]['location'],
      'test_id'             => $this->input->post('applied_coupon_id'),
      'count'               => $count,
      'date'                => $this->input->post('date'),
      'slot_id'             => $slot_id,
      'time'                => $slot_details[0]['time'],
      'mobile'              => $customer_phone,
      'name'                => $customer_name,
      'family_member_id'    => $imp,
      'fee'                 => $fee,
      'consultation_fee'    => $this->input->post('consultation_fee'),
      'flat_discount'       => $this->input->post('flat_discount'),
      'payment_type'        => 'online',
      'booking_type'        => 'product_booking',
      'booking_status'      => 'booked',
      //'wallet_amount'     => $wallet_amount,
      'transaction_id'      => '',
      'booking_status'      => 'pending',
      'status'              => 'unpaid',
      'booked_by'              =>  $booked_by,
      'created_on'          => date('Y-m-d H:i:s')
    ];
    if($_FILES['image']['name']!==""){
        $config['upload_path']			= $this->bharosa_base_path . 'diagnostic_prescription_bookings/';
    	$config['allowed_types']        = 'jpeg|jpg|png|pdf';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/diagnostic_prescription_bookings/'.$uploadData['file_name'];
        $data['image']  = $photo;
    }else{
       $data['image']  = ''; 
    }
    $insert = $this->registermodel->common_insert('diagnostic_bookings',$data);
    $bkid = sprintf('%04d',$insert);
    $booking_id = 'BKID_'.$bkid;
    $update = $this->registermodel->common_update('diagnostic_bookings',['booking_id' => $booking_id],['id' => $insert]);

    // --- Create Cashfree order ---
    $payload = [
        "order_amount" => $amount,
        "order_currency" => "INR",
        "customer_details" => [
            "customer_id"   => $customer_id,
            "customer_phone"=> $customer_phone,
            "customer_email"=> $customer_email
        ],
        "order_meta" => [
            // ✅ Will receive order_id from Cashfree
            "return_url" => base_url("admin/register/cashfree_diagnostic_callback?order_id={order_id}")
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders");
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
        "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_id'])) {
        // ✅ Save Cashfree generated order_id in booking
        $this->registermodel->common_update(
            'diagnostic_bookings',
            ['transaction_id' => $res['order_id']],
            ['id' => $insert]
        );
    }

    // Send only required values to frontend
    echo json_encode([
        'order_id' => $res['order_id'] ?? null,
        'payment_session_id' => $res['payment_session_id'] ?? null
    ]);
}
public function cashfree_diagnostic_callback() {
    $order_id = $this->input->get('order_id');

    // Verify payment with Cashfree API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders/" . $order_id);
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders/" . $order_id);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
         "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
         "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01"
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_status']) && $res['order_status'] === 'PAID') {
        // ✅ Update booking row
        $this->db->where('transaction_id', $order_id)
                 ->update('diagnostic_bookings', [
                     'status' => 'paid',
                     'booking_status' => 'booked'
                 ]);

        // Mark slot as booked
        $booking_details = $this->registermodel->common_fetch_select(
            'diagnostic_bookings',
            ['transaction_id' => $order_id],
            'slot_id,user_id,booking_id,family_member_id,main_data_id,date,time,test_id',
            []
        );
        $update = $this->registermodel->common_update('diagnostic_slots',['booking_status' => 'booked'],['id' => $booking_details[0]['slot_id']]);
        $diagnostic_data = $this->registermodel->get_single_diagnostic_tests($booking_details[0]['test_id']);
        $this->registermodel->save_diagnostic_booking_snapshot($booking_details[0]['booking_id'], $diagnostic_data);
        
        
        $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
        //echo $this->db->last_query();exit;
        $diagnostic_details = $this->registermodel->common_fetch('diagnostics',['id' => $booking_details[0]['main_data_id']]);
        /*user_notification*/
        $data = array(
           'member_id'          => $booking_details[0]['user_id'],
           'title'              => 'Med Rayder',
           'message'            => "Your diagnostic booking (Booking ID: {$booking_details[0]['booking_id']}) has been successfully placed. You will receive confirmation once the lab accepts the booking. Please be ready at your scheduled date and time",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data['title']; 
        $message['body'] = $data['message'];
        $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
        /*user_notification*/
        
        /*diagnostic_notification*/
        $data1 = array(
           'member_id'          => $booking_details[0]['main_data_id'],
           'title'              => 'Med Rayder',
           'message'            => "You have received a new diagnostic booking (Booking ID: {$booking_details[0]['booking_id']}). Please review and accept the booking to proceed with the test appointment",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data1['title'];
        $message['body'] = $data1['message'];
        $this->sendNotification($diagnostic_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('diagnostic_notifications',$data1);
        /*diagnostic_notification*/

        // Redirect with toast message
        $this->session->set_flashdata('success', 'Payment Successful! Booking confirmed.');
        redirect('admin/register/diagnostic_booking');

    } else {
        // ❌ Delete booking if payment failed
        $this->db->where('transaction_id', $order_id)
                 ->delete('diagnostic_bookings');

        // Redirect with error toast
        $this->session->set_flashdata('error', 'Payment Failed! Please try again.');
        redirect('admin/register/diagnostic_booking');

    }
}
public function diagnostic_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('diagnostics',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/diagnostic_booking',$data);
	$this->load->view('admin/includes/footer');
}
/*diagnostic_booking*/

/*lab_test_prescription_booking*/
public function lab_test_prescription_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('lab_tests',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/lab_test_prescription_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function insert_lab_test_prescription_booking(){
    $config['upload_path']			= $this->bharosa_base_path . 'lab_test_prescription_bookings/';
	$config['allowed_types']        = 'jpeg|jpg|png|pdf';
	$config['file_name']            = time();
	//$config['max_size']             = 2048;
	//print_r($config);exit;
	$this->load->library('upload',$config);
	$this->upload->initialize($config,true);
	if (!$this->upload->do_upload('image')) {
        // File upload failed
        $error = $this->upload->display_errors();
        echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
        return;
    }
    
    // File upload success
    $uploadData = $this->upload->data();
    $photo = 'assets/admin/lab_test_prescription_bookings/'.$uploadData['file_name'];
    
    $user_id             = $this->input->post('user_id');
    $main_data_id        = $this->input->post('main_data_id');
    
    $user_details = $this->registermodel->common_fetch_select('users',['id' => $user_id],'name,mobile',[]);
    
    $lab_test_data = $this->registermodel->common_fetch_select('lab_tests', ['id' => $main_data_id], 'name,logo,location', []);
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    $data = [
        'user_id'          => $user_id,
        'main_data_id'     => $main_data_id,
        'address_id'       => $this->input->post('address'),
        'lab_test_name'    => $lab_test_data[0]['name'],
        'logo'             => $lab_test_data[0]['logo'],
        'family_member_id' => $this->input->post('family_member_id'),
        'name'             => $user_details[0]['name'],
        'mobile'           => $user_details[0]['mobile'],
        'booking_status'   => 'booked',
        'image'            => $photo,
        'booked_by'              =>  $booked_by,
        'created_on'       => date('Y-m-d H:i:s')
    ];
    $insert = $this->registermodel->common_insert('lab_test_prescription_bookings', $data);
    $bkid = sprintf('%04d', $insert);
    $booking_id = 'BKID_' . $bkid;
    $update = $this->registermodel->common_update('lab_test_prescription_bookings', ['booking_id' => $booking_id], ['id' => $insert]);
    
    $booking_details = $this->registermodel->common_fetch('lab_test_prescription_bookings',['booking_id' => $booking_id]);
    $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
    //echo $this->db->last_query();exit;
    $lab_tests_details = $this->registermodel->common_fetch('lab_tests',['id' => $booking_details[0]['main_data_id']]);
    /*user_notification*/
    $data = array(
       'member_id'          => $booking_details[0]['user_id'],
       'title'              => 'Med Rayder',
       'message'            => "Your lab test prescription booking (Booking ID: {$booking_details[0]['booking_id']}) has been placed successfully. Our team will review your prescription and contact you shortly to proceed with the tests",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data['title']; 
    $message['body'] = $data['message'];
    $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
    /*user_notification*/
    
    /*lab_test_notification*/
    $data1 = array(
       'member_id'          => $booking_details[0]['main_data_id'],
       'title'              => 'Med Rayder',
       'message'            => "You have received a new lab test prescription booking (Booking ID: {$booking_details[0]['booking_id']}). Please review the uploaded prescription and proceed with confirmation or follow-up",           
	   'created_on'	        => date('Y-m-d H:i:s')
	);
    $message = array();
    $message['title'] = $data1['title'];
    $message['body'] = $data1['message'];
    $this->sendNotification($lab_tests_details[0]['player_id'],$message['title'],$message['body']);//exit;
    $insert_notifications = $this->registermodel->common_insert('lab_test_notifications',$data1);
    /*lab_test_notification*/
    
    echo json_encode(['success' => true, 'message' => 'lab test disgnostic prescription order booked successfully']);
    return;
}
/*lab_test_prescription_booking*/

/*lab_test_booking*/
public function get_labb_tests($hospital_id) {
    $page   = (int)$this->input->post('page') ?: 1;
    $limit  = 10; // items per page
    $offset = ($page - 1) * $limit;
    $search = $this->input->post('search');

    // Select tests with subquery for total_test_count
    $this->db->select("lab_packages.*,
        (
            (SELECT COUNT(*) 
             FROM 	lab_package_tests hdbt 
             WHERE hdbt.package_id = lab_packages.id) 
        ) AS total_test_count", false);

    $this->db->from('lab_packages');
    $this->db->where([
        'main_data_id'   => $hospital_id,
        'status'         => 1,
        'delete_status'  => 1
    ]);

    if (!empty($search)) {
        $this->db->like('name', $search);
    }

    // clone query for total count
    $clone_db = clone $this->db;
    $total = $clone_db->count_all_results();

    // apply limit+offset for current page
    $this->db->limit($limit, $offset);
    $query = $this->db->get();
    $tests = $query->result_array();

    // check if more data available
    $has_more = ($total > ($page * $limit));

    if (!empty($tests)) {
        echo json_encode([
            'success'   => true,
            'packages'  => $tests,
            'total'     => $total,
            'page'      => $page,
            'limit'     => $limit,
            'has_more'  => $has_more
        ]);
    } else {
        echo json_encode([
            'success'   => false,
            'message'   => 'No lab packages found.',
            'packages'  => [],
            'total'     => 0,
            'page'      => $page,
            'limit'     => $limit,
            'has_more'  => false
        ]);
    }
}
public function get_lab_tests_subtests($test_id) {
    $data = $this->registermodel->get_lab_tests_subtests($test_id);

    echo json_encode([
        'success' => true,
        'tests'   => $data
    ]);
}
public function get_lab_test_dates($hospital_id){
    $dates = $this->registermodel->get_lab_test_dates($hospital_id);
    
    //echo $this->db->last_query();exit;

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'dates' => $dates
        ]));
}
public function get_lab_test_slots_by_date(){
    $date = $this->input->post('date'); // Y-m-d
    $main_data_id = $this->input->post('hospital_id');
    
    $slots = $this->registermodel->get_lab_test_slots($main_data_id,$date);
    
    //echo $this->db->last_query();exit;
    
    echo json_encode($slots);
}
public function get_lab_test_package_prices($test_id) {
    $row = $this->registermodel->common_fetch(
        'lab_packages',
        ['id' => $test_id],
        'one_person,one_person_discount,two_person,two_person_discount,three_person,three_person_discount,four_person,four_person_discount,five_person,five_person_discount'
    );

    $prices = [];
    if (!empty($row)) {
        $row = $row[0]; // single record

        $prices = [
            [
                'persons_count'   => 1,
                'original_price'  => $row['one_person'],
                'discounted_price'=> $row['one_person_discount']
            ],
            [
                'persons_count'   => 2,
                'original_price'  => $row['two_person'],
                'discounted_price'=> $row['two_person_discount']
            ],
            [
                'persons_count'   => 3,
                'original_price'  => $row['three_person'],
                'discounted_price'=> $row['three_person_discount']
            ],
            [
                'persons_count'   => 4,
                'original_price'  => $row['four_person'],
                'discounted_price'=> $row['four_person_discount']
            ],
            [
                'persons_count'   => 5,
                'original_price'  => $row['five_person'],
                'discounted_price'=> $row['five_person_discount']
            ],
        ];
    }

    echo json_encode([
        'success'   => true,
        'message'   => 'Prices fetched successfully',
        'prices'    => $prices
    ]);
}
public function create_lab_test_cashfree_order() {
    $fee         = $this->input->post('fee'); 
    $amount      = $this->input->post('consultation_fee'); 
    $customer_id = $this->input->post('user_id');
    $main_data_id = $this->input->post('main_data_id');
    $slot_id      = $this->input->post('time');
    $family_member_id = $this->input->post('family_member_id');
    
    $image = $this->input->post('image');
    
    $imp = implode(',',$family_member_id);
    $count = count($family_member_id);
    
    //$exp = explode('');

    // Get details for saving booking
    $user_details = $this->registermodel->common_fetch_select('users', ['id' => $customer_id], 'email,mobile,name', []);
    $lab_test_data = $this->registermodel->common_fetch_select('lab_tests', ['id' => $main_data_id], 'name,logo', []);
    $slot_details = $this->registermodel->common_fetch_select('lab_test_slots', ['id' => $slot_id], 'time', []);
    //$family_member_details = $this->registermodel->common_fetch_select('family_members', ['id' => $family_member_id], 'name,mobile', []);

    $customer_phone = $user_details[0]['mobile'] ?? '';
    $customer_email = $user_details[0]['email'] ?? '';
    $customer_name = $user_details[0]['name'] ?? '';
    
    if (empty($slot_id)) {
        echo json_encode(['success' => false, 'message' => 'Please select time slot']);
        return;
    }
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    // --- Save booking row as pending ---
    $data = [
      'user_id'             => $this->input->post('user_id'),
      'main_data_id'        => $main_data_id,
      'address_id'          => $this->input->post('address'),
      'lab_test_name'       => $lab_test_data[0]['name'],
      'logo'                => $lab_test_data[0]['logo'],
      //'location'            => $diagnostic_data[0]['location'],
      'test_id'             => $this->input->post('applied_coupon_id'),
      //'image'               => '',
      'count'               => $count,
      'date'                => $this->input->post('date'),
      'slot_id'             => $slot_id,
      'time'                => $slot_details[0]['time'],
      'mobile'              => $customer_phone,
      'name'                => $customer_name,
      'family_member_id'    => $imp,
      'fee'                 => $this->input->post('fee'),
      'consultation_fee'    => $this->input->post('consultation_fee'),
      'flat_discount'       => $this->input->post('flat_discount'),
      'payment_type'        => 'online',
      'booking_status'      => 'pending',
      'status'              => 'unpaid',
      'booked_by'           =>  $booked_by,
      //'wallet_amount'       => $wallet_amount,
      //'transaction_id'      => $transaction_id,
      'created_on'          => date('Y-m-d H:i:s')
    ];
    if($_FILES['image']['name']!==""){
        $config['upload_path']			= $this->bharosa_base_path . 'lab_test_prescription_bookings/';
    	$config['allowed_types']        = 'jpeg|jpg|png|pdf';
    	$config['file_name']            = time();
    	//$config['max_size']             = 2048;
    	//print_r($config);exit;
    	$this->load->library('upload',$config);
    	$this->upload->initialize($config,true);
    	if (!$this->upload->do_upload('image')) {
            // File upload failed
            $error = $this->upload->display_errors();
            echo json_encode(['success' => false, 'message' => 'File upload error: ' . $error]);
            return;
        }
        
        // File upload success
        $uploadData = $this->upload->data();
        $photo = 'assets/admin/lab_test_prescription_bookings/'.$uploadData['file_name'];
        $data['image']  = $photo;
    }else{
       $data['image']  = ''; 
    }
    $insert = $this->registermodel->common_insert('lab_test_bookings',$data);
    $bkid = sprintf('%04d',$insert);
    $booking_id = 'BKID_'.$bkid;
    $update = $this->registermodel->common_update('lab_test_bookings',['booking_id' => $booking_id],['id' => $insert]);

    // --- Create Cashfree order ---
    $payload = [
        "order_amount" => $amount,
        "order_currency" => "INR",
        "customer_details" => [
            "customer_id"   => $customer_id,
            "customer_phone"=> $customer_phone,
            "customer_email"=> $customer_email
        ],
        "order_meta" => [
            // ✅ Will receive order_id from Cashfree
            "return_url" => base_url("admin/register/cashfree_lab_test_callback?order_id={order_id}")
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders");
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
        "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_id'])) {
        // ✅ Save Cashfree generated order_id in booking
        $this->registermodel->common_update(
            'lab_test_bookings',
            ['transaction_id' => $res['order_id']],
            ['id' => $insert]
        );
    }

    // Send only required values to frontend
    echo json_encode([
        'order_id' => $res['order_id'] ?? null,
        'payment_session_id' => $res['payment_session_id'] ?? null
    ]);
}
public function cashfree_lab_test_callback() {
    $order_id = $this->input->get('order_id');

    // Verify payment with Cashfree API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders/" . $order_id);
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders/" . $order_id);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
         "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
         "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01"
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_status']) && $res['order_status'] === 'PAID') {
        // ✅ Update booking row
        $this->db->where('transaction_id', $order_id)
                 ->update('lab_test_bookings', [
                     'status' => 'paid',
                     'booking_status' => 'booked'
                 ]);

        // Mark slot as booked
        $booking_details = $this->registermodel->common_fetch_select(
            'lab_test_bookings',
            ['transaction_id' => $order_id],
            'slot_id,user_id,booking_id,family_member_id,main_data_id,date,time,test_id',
            []
        );
        $update = $this->registermodel->common_update('lab_test_slots',['booking_status' => 'booked'],['id' => $booking_details[0]['slot_id']]);
        $lab_test_data = $this->registermodel->get_single_lab_test($booking_details[0]['test_id']);
        $this->registermodel->save_lab_test_booking_snapshot($booking_details[0]['booking_id'], $lab_test_data);
        
        $booking_details = $this->registermodel->common_fetch('lab_test_bookings',['booking_id' => $booking_details[0]['booking_id']]);
        $user_details = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
        //echo $this->db->last_query();exit;
        $lab_tests_details = $this->registermodel->common_fetch('lab_tests',['id' => $booking_details[0]['main_data_id']]);
        /*user_notification*/
        $data = array(
           'member_id'          => $booking_details[0]['user_id'],
           'title'              => 'Med Rayder',
           'message'            => "Your lab test booking (Booking ID: {$booking_details[0]['booking_id']}) has been placed successfully. The lab will review and confirm your appointment shortly",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data['title']; 
        $message['body'] = $data['message'];
        $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('user_notifications',$data);
        /*user_notification*/
        
        /*lab_test_notification*/
        $data1 = array(
           'member_id'          => $booking_details[0]['main_data_id'],
           'title'              => 'Med Rayder',
           'message'            => "You have received a new lab test booking (Booking ID: {$booking_details[0]['booking_id']}). Please review and accept the booking to confirm the appointment",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data1['title'];
        $message['body'] = $data1['message'];
        $this->sendNotification($lab_tests_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('lab_test_notifications',$data1);
        /*lab_test_notification*/

        // Redirect with toast message
        $this->session->set_flashdata('success', 'Payment Successful! Booking confirmed.');
        redirect('admin/register/lab_test_booking');

    } else {
        // ❌ Delete booking if payment failed
        $this->db->where('transaction_id', $order_id)
                 ->delete('lab_test_bookings');

        // Redirect with error toast
        $this->session->set_flashdata('error', 'Payment Failed! Please try again.');
        redirect('admin/register/lab_test_booking');

    }
}
public function lab_test_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('lab_tests',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/lab_test_booking',$data);
	$this->load->view('admin/includes/footer');
}
/*lab_test_booking*/

/*online_doctor_booking*/

/*online_doctor_booking*/
public function get_online_doctorss($speciality_id){
    $doctors = $this->db->select('id, name,fee')
                               ->from('online_doctors')
                               ->where(['speciality_id' => $speciality_id,'availability' => 1,'status' => 1, 'delete_status' => 1])
                               ->get()
                               ->result_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'doctors' => $doctors
        ]));
}
public function get_online_doctor_dates($doctor_id){
    $dates = $this->registermodel->get_online_doctor_dates($doctor_id);
    
    //echo $this->db->last_query();exit;

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'dates' => $dates
        ]));
}
public function get_online_doctor_slots_by_date(){
    $date = $this->input->post('date'); // Y-m-d
    $doctor_id = $this->input->post('doctor_id');
    
    $slots = $this->registermodel->get_online_doctor_slots($doctor_id,$date);
    
    //echo $this->db->last_query();exit;
    
    echo json_encode($slots);
}
public function get_online_doctor_couponss(){
    $coupons = $this->db->select('id, name,percentage,description')
                               ->from('online_doctor_coupons')
                               ->where(['status' => 1, 'delete_status' => 1])
                               ->get()
                               ->result_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
            'success' => true,
            'coupons' => $coupons
        ]));
}
public function online_doctor_booking(){
    //check_permission(12);
    $sess_data = $this->session_data();
    $data['users'] = $this->registermodel->common_fetch('users',['status' => 1,'delete_status' => 1]);
    $data['hospitals'] = $this->registermodel->common_fetch('online_doctor_specialities',['status' => 1,'delete_status' => 1]);
    $this->load->view('admin/includes/header');
	$this->load->view('admin/user_bookings/online_doctor_booking',$data);
	$this->load->view('admin/includes/footer');
}
public function create_online_doctor_cashfree_order() {
    $fee         = $this->input->post('fee'); 
    $amount      = $this->input->post('consultation_fee'); 
    $customer_id = $this->input->post('user_id');
    $main_data_id = $this->input->post('main_data_id');
    $slot_id      = $this->input->post('time');
    $family_member_id = $this->input->post('family_member_id');

    // Get details for saving booking
    $user_details = $this->registermodel->common_fetch_select('users', ['id' => $customer_id], 'email,mobile', []);
    $slot_details = $this->registermodel->common_fetch_select('online_doctor_slots', ['id' => $slot_id], 'time', []);
    $family_member_details = $this->registermodel->common_fetch_select('family_members', ['id' => $family_member_id], 'name,mobile', []);

    $customer_phone = $user_details[0]['mobile'] ?? '';
    $customer_email = $user_details[0]['email'] ?? '';
    
    if (empty($slot_id)) {
        echo json_encode(['success' => false, 'message' => 'Please select time slot']);
        return;
    }
    $is_logged = $this->session->userdata('user_info');
    if($is_logged['login_type']=='admin'){
        $booked_by  = 'admin';
    }else{
        $booked_by  = $is_logged['user_id'];
    }
    // --- Save booking row as pending ---
    $data = [
      'user_id'             => $this->input->post('user_id'),
      'speciality_id'       => $this->input->post('speciality_id'),
      'doctor_id'           => $this->input->post('doctor_id'),
      'consult_type'        => 'online',
      'date'                => $this->input->post('date'),
      'slot_id'             => $slot_id,
      'time'                => $slot_details[0]['time'],
      'mobile'              => $family_member_details[0]['mobile'],
      'patient_name'        => $family_member_details[0]['name'],
      'family_member_id'    => $this->input->post('family_member_id'),
      'fee'                 => $fee,
      'consultation_fee'    => $this->input->post('consultation_fee'),
      'coupon_id'           => $this->input->post('applied_coupon_id'),
      'coupon_name'         => $this->input->post('applied_coupon_code'),
      'coupon_percentage'   => $this->input->post('applied_coupon_discount'),
      'coupon_discount'     => $this->input->post('applied_coupon_amount'),
      'payment_type'        => 'online',
      'booking_status'      => 'pending',
      'status'              => 'unpaid',
      //'wallet_amount'       => $wallet_amount,
      //'transaction_id'      => $transaction_id,
      'booked_by'              =>  $booked_by,
      'created_on'          => date('Y-m-d H:i:s')
    ];
    
    $insert = $this->registermodel->common_insert('online_doctor_bookings',$data);
    $bkid = sprintf('%04d',$insert);
    $booking_id = 'BKID_'.$bkid;
    $update = $this->registermodel->common_update('online_doctor_bookings',['booking_id' => $booking_id],['id' => $insert]);

    // --- Create Cashfree order ---
    $payload = [
        "order_amount" => $amount,
        "order_currency" => "INR",
        "customer_details" => [
            "customer_id"   => $customer_id,
            "customer_phone"=> $customer_phone,
            "customer_email"=> $customer_email
        ],
        "order_meta" => [
            // ✅ Will receive order_id from Cashfree
            "return_url" => base_url("admin/register/cashfree_online_doctor_callback?order_id={order_id}")
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders");
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
        "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_id'])) {
        // ✅ Save Cashfree generated order_id in booking
        $this->registermodel->common_update(
            'online_doctor_bookings',
            ['transaction_id' => $res['order_id']],
            ['id' => $insert]
        );
    }

    // Send only required values to frontend
    echo json_encode([
        'order_id' => $res['order_id'] ?? null,
        'payment_session_id' => $res['payment_session_id'] ?? null
    ]);
}
public function cashfree_online_doctor_callback() {
    $order_id = $this->input->get('order_id');

    // Verify payment with Cashfree API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://sandbox.cashfree.com/pg/orders/" . $order_id);
    //curl_setopt($ch, CURLOPT_URL, "https://api.cashfree.com/pg/orders/" . $order_id);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
         "x-client-id: TEST10757881de8f8e07b42058abdafe18875701",
         "x-client-secret: cfsk_ma_test_2152cc13bf8a77c6770613db5f44b738_f9bd4230",
        //"x-client-id: 1048122aa092bebd9eb15d51c562218401",
        //"x-client-secret: cfsk_ma_prod_fba5aa7897e4b2528dfb7416812bdd98_5bea7b28",
        "x-api-version: 2025-01-01"
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($response, true);

    if (isset($res['order_status']) && $res['order_status'] === 'PAID') {
        // ✅ Update booking row
        $this->db->where('transaction_id', $order_id)
                 ->update('online_doctor_bookings', [
                     'status' => 'paid',
                     'booking_status' => 'booked'
                 ]);

        // Mark slot as booked
        $booking_details = $this->registermodel->common_fetch_select(
            'online_doctor_bookings',
            ['transaction_id' => $order_id],
            'slot_id,user_id,booking_id,family_member_id,doctor_id,doctor_id,consult_type,date,time',
            []
        );
        if (!empty($booking_details)) {
            $this->registermodel->common_update(
                'online_doctor_slots',
                ['booking_status' => 'booked'],
                ['id' => $booking_details[0]['slot_id']]
            );
        }
        
        
        $update                     = $this->registermodel->common_update('online_doctor_slots',['booking_status' => 'booked'],['id' => $booking_details[0]['slot_id']]);
        $user_details               = $this->registermodel->common_fetch('users',['id' => $booking_details[0]['user_id']]);
        $family_member_details      = $this->registermodel->common_fetch('family_members',['id' => $booking_details[0]['family_member_id']]);
        $doctor_details             = $this->registermodel->common_fetch('online_doctors',['id' => $booking_details[0]['doctor_id']]);
        
        $date           = $booking_details[0]['date'];
        $time           = $booking_details[0]['time'];
        $booking_id     = $booking_details[0]['booking_id'];
        
        
        /*user_notification*/
        $data1 = array(
           'member_id'          => $booking_details[0]['user_id'],
           'title'              => 'Med Rayder',
           'message'            => "Online consultation with Dr. {$doctor_details[0]['name']} on {$date} at {$time} (Booking ID: {$booking_id}) has been booked successfully",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data1['title'];
        $message['body'] = $data1['message'];
        $this->sendNotification($user_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('user_notifications',$data1);
        /*user_notification*/
        
        /*doctor_notification*/
        $data2 = array(
           'member_id'          => $booking_details[0]['doctor_id'],
           'title'              => 'Med Rayder',
           'message'            => "{$family_member_details[0]['name']} has booked a consultation on {$date} at {$time} (Booking ID: {$booking_id})",           
    	   'created_on'	        => date('Y-m-d H:i:s')
    	);
        $message = array();
        $message['title'] = $data2['title'];
        $message['body'] = $data2['message'];
        $this->sendNotification($doctor_details[0]['player_id'],$message['title'],$message['body']);//exit;
        $insert_notifications = $this->registermodel->common_insert('online_doctor_notifications',$data2);
        /*doctor_notification*/

        // Redirect with toast message
        $this->session->set_flashdata('success', 'Payment Successful! Booking confirmed.');
        redirect('admin/register/online_doctor_booking');

    } else {
        // ❌ Delete booking if payment failed
        $this->db->where('transaction_id', $order_id)
                 ->delete('online_doctor_bookings');

        // Redirect with error toast
        $this->session->set_flashdata('error', 'Payment Failed! Please try again.');
        redirect('admin/register/online_doctor_booking');

    }
}
/*booking_for_an_user*/



}

?>