<?php
class Registermodel extends CI_Model{
/*default functions*/
public function common_fetch($table,$where){
	$this->db->where($where);
	$this->db->order_by('id','desc');
	$query = $this->db->get($table);
	return $query->result_array();
}
public function common_fetch_select($table, $where = [], $select = '*', $integerFields = []) {
    $this->db->select($select);
    $this->db->from($table);
    
    if (!empty($where)) {
        $this->db->where($where);
    }
    $this->db->order_by('id','desc');
    $query = $this->db->get();
    
    if ($query->num_rows() > 0) {
        $result = $query->result_array();
        
        // Type-cast requested fields to integer
        if (!empty($integerFields)) {
            foreach ($result as &$row) {
                foreach ($integerFields as $field) {
                    if (isset($row[$field])) {
                        $row[$field] = (int) $row[$field];
                    }
                }
            }
            unset($row);
        }
        
        return $result;
    } else {
        return [];
    }
}
public function common_fetch_select_asc($table, $where = [], $select = '*', $integerFields = []) {
    $this->db->select($select);
    $this->db->from($table);
    
    if (!empty($where)) {
        $this->db->where($where);
    }
    $this->db->order_by('id','asc');
    $query = $this->db->get();
    
    if ($query->num_rows() > 0) {
        $result = $query->result_array();
        
        // Type-cast requested fields to integer
        if (!empty($integerFields)) {
            foreach ($result as &$row) {
                foreach ($integerFields as $field) {
                    if (isset($row[$field])) {
                        $row[$field] = (int) $row[$field];
                    }
                }
            }
            unset($row);
        }
        
        return $result;
    } else {
        return [];
    }
}
public function common_fetch_asc($table,$where){
	$this->db->where($where);
	$this->db->order_by('id','asc');
	$query = $this->db->get($table);
	return $query->result_array();
}
public function common_fetch_rows($table,$where){
	$this->db->where($where);
	$this->db->order_by('id','desc');
	$query = $this->db->get($table);
	return $query->num_rows();
}
public function common_insert($table,$data){
	$this->db->insert($table,$data);
	$id = $this->db->insert_id();
	return $id;
}
public function common_update($table,$data,$where){
	$this->db->where($where);
	$this->db->update($table,$data);
}
public function common_delete($table,$where){
	$this->db->where($where);
	$this->db->delete($table);
}
/*default functions*/

/*home*/
public function get_ongoing_ambulance_bookings_home($sess_data){
    $today = date('Y-m-d');

    $this->db->from('ambulance_bookings b');
    $this->db->where('b.main_data_id', $sess_data);
    $this->db->where('b.booking_status', 'booked');
    
    $this->db->group_start();
    $this->db->where('b.accept_status', 'accepted');
    $this->db->or_where('b.accept_status', '');
    $this->db->group_end();

    return $this->db->count_all_results(); // Just count; no get()
}
public function get_completed_ambulance_bookings_home($sess_data){
    $this->db->from('ambulance_bookings b');
    $this->db->where('b.main_data_id', $sess_data);
    $this->db->where('b.booking_status', 'completed');
    
    $this->db->group_start();
    $this->db->where('b.accept_status', 'accepted');
    $this->db->or_where('b.accept_status', '');
    $this->db->group_end();

    return $this->db->count_all_results(); // Get count directly without running get()
}
public function get_ongoing_admit_bookings_home($sess_data){
    $this->db->from('admit_bookings b');
    $this->db->where('b.main_data_id', $sess_data);
    $this->db->where('b.booking_status', 'booked');
    return $this->db->count_all_results();
}
public function get_completed_admit_bookings_home($sess_data){
    $this->db->from('admit_bookings b');
    $this->db->where('b.main_data_id', $sess_data);
    $this->db->where('b.booking_status', 'completed');
    return $this->db->count_all_results();
}
public function get_ongoing_doctor_bookings_home($sess_data){
    $this->db->from('doctor_bookings b');
    $this->db->where('b.main_data_id', $sess_data);
    $this->db->where('b.booking_status', 'booked');
    return $this->db->count_all_results();
}
public function get_completed_doctor_bookings_home($sess_data){
    $this->db->from('doctor_bookings b');
    $this->db->where('b.main_data_id', $sess_data);
    $this->db->where('b.booking_status', 'completed');
    return $this->db->count_all_results();
}
public function get_ongoing_wellness_product_bookings_home($sess_data){
    $this->db->from('hospital_pharmacy_product_bookings pb');
    $this->db->where('pb.main_data_id', $sess_data);
    
    // Accept Status Filter
    $this->db->group_start();
    $this->db->where('pb.accept_status', 'accepted');
    $this->db->or_where('pb.accept_status', '');
    $this->db->group_end();
    
    // booking_status = 'booked' OR 'picked up'
    $this->db->group_start();
    $this->db->where('pb.booking_status', 'booked');
    $this->db->or_where('pb.booking_status', 'pickedup');
    $this->db->group_end();
    
    return $this->db->count_all_results();
}
public function get_completed_wellness_product_bookings_home($sess_data){
    $this->db->from('hospital_pharmacy_product_bookings pb');
    $this->db->where('pb.main_data_id', $sess_data);
    $this->db->where('pb.booking_status', 'completed');
    return $this->db->count_all_results();
}
public function get_ongoing_pharmacy_prescription_bookings_home($sess_data){
    $this->db->from('hospital_pharmacy_medicine_orders pb');
    $this->db->where('pb.main_data_id', $sess_data);
    
    // Accept Status Filter
    $this->db->group_start();
    $this->db->where('pb.accept_status', 'accepted');
    $this->db->or_where('pb.accept_status', '');
    $this->db->group_end();
    
    // booking_status = 'booked' OR 'picked up'
    $this->db->group_start();
    $this->db->where('pb.booking_status', 'booked');
    $this->db->or_where('pb.booking_status', 'pickedup');
    $this->db->group_end();
    
    return $this->db->count_all_results();
}
public function get_completed_pharmacy_prescription_bookings_home($sess_data){
    $this->db->from('hospital_pharmacy_medicine_orders pb');
    $this->db->where('pb.main_data_id', $sess_data);
    $this->db->where('pb.booking_status', 'completed');
    
    return $this->db->count_all_results();
}
public function get_ongoing_diagnostic_bookings_home($sess_data){
    $this->db->from('hospital_diagnostic_bookings db');
    $this->db->where('db.main_data_id', $sess_data);
     $this->db->where('db.booking_status', 'booked');
    // Accept Status Filter
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    return $this->db->count_all_results();
}
public function get_completed_diagnostic_bookings_home($sess_data){
    $this->db->from('hospital_diagnostic_bookings db');
    $this->db->where('db.main_data_id', $sess_data);
    $this->db->where('db.booking_status', 'completed');
    
    return $this->db->count_all_results();
}
public function get_ongoing_diagnostic_prescription_bookings_home($sess_data){
    $this->db->from('hospital_diagnostic_prescription_bookings db');
    $this->db->where('db.main_data_id', $sess_data);
     $this->db->where('db.booking_status', 'booked');
    // Accept Status Filter
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    return $this->db->count_all_results();
}
public function get_completed_diagnostic_prescription_bookings_home($sess_data){
    $this->db->from('hospital_diagnostic_prescription_bookings db');
    $this->db->where('db.main_data_id', $sess_data);
    $this->db->where('db.booking_status', 'completed');

    return $this->db->count_all_results();
}
/*home*/

/*users*/
public function get_users($limit, $start, $search){
    // 1. Fetch users
    $this->db->select('u.*, bg.name as blood_group, cc.name as coverage_category,uw.wallet_amount');
    $this->db->from('users u');
    $this->db->join('blood_groups bg', 'bg.id = u.blood_group', 'left');
    $this->db->join('coverage_categories cc', 'cc.id = u.coverage_category', 'left');
    $this->db->join('user_wallet uw', 'uw.user_id = u.id', 'left');
    $this->db->where('u.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('u.mobile', $search);
        $this->db->or_like('u.email', $search);
        $this->db->group_end();
    }

    $this->db->order_by('u.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();

    // 2. Collect user IDs
    $user_ids = array_column($users, 'id');

    $CI = &get_instance();

    // 3. Fetch all family members
    $family_members_map = [];
    if (!empty($user_ids)) {
        $CI->db->select('id, user_id, name, dob, gender, email, mobile, image as user_image');
        $CI->db->from('family_members');
        $CI->db->where_in('user_id', $user_ids);
        $family_members = $CI->db->get()->result_array();

        foreach ($family_members as $member) {
            $member['gender_label'] = ($member['gender'] == 1) ? 'Male' : (($member['gender'] == 2) ? 'Female' : 'Other');
            $family_members_map[$member['user_id']][] = $member;
        }
    }

    // 4. Fetch user addresses
    $user_addresses_map = [];
    if (!empty($user_ids)) {
        $CI->db->select('id, user_id, address, hno, building_no, landmark, lat, lon, address_type, pincode, state, default_address');
        $CI->db->from('user_addresses');
        $CI->db->where('status', 1);
        $CI->db->where('delete_status', 1);
        $CI->db->where_in('user_id', $user_ids);
        $user_addresses = $CI->db->get()->result_array();

        foreach ($user_addresses as $address) {
            $user_addresses_map[$address['user_id']][] = $address;
        }
    }

    // 5. Fetch health card (only one row per user)
    $health_cards_map = [];
    if (!empty($user_ids)) {
        $CI->db->select('user_id, name, duration, from_date, to_date, price, total_premium, gst, total_amount, transaction_id,invoice');
        $CI->db->from('health_card_holders');
        $CI->db->where_in('user_id', $user_ids);
        $CI->db->order_by('id', 'DESC');
        $cards = $CI->db->get()->result_array();

        foreach ($cards as $card) {
            if (!isset($health_cards_map[$card['user_id']])) {
                $health_cards_map[$card['user_id']] = $card; // only first/latest row per user
            }
        }
    }

    // 6. Final user formatting
    return array_map(function ($user) use ($family_members_map, $user_addresses_map, $health_cards_map) {
        $gender_label = ($user['gender'] == 1) ? 'Male' : (($user['gender'] == 2) ? 'Female' : 'Other');
        $modified_on = !empty($user['modified_on']) ? $user['modified_on'] : '';
        $wallet_amount = !empty($user['wallet_amount']) ? $user['wallet_amount'] : 0;

        return [
            'id' => (int)$user['id'],
            'name' => $user['name'],
            'mobile' => $user['mobile'],
            'email' => $user['email'],
            'dob' => $user['dob'],
            'gender' => $gender_label,
            'image' => $user['image'],
            'blood_group' => $user['blood_group'],
            'coverage_category' => $user['coverage_category'],
            'status' => $user['status'],
            'delete_status' => $user['delete_status'],
            'created_on' => $user['created_on'],
            'modified_on' => $modified_on,
            'family_members' => $family_members_map[$user['id']] ?? [],
            'count' => count($family_members_map[$user['id']] ?? []),
            'address' => $user_addresses_map[$user['id']] ?? [],
            'address_count' => count($user_addresses_map[$user['id']] ?? []),
            'subscription' => $health_cards_map[$user['id']] ?? (object)[],
            'wallet_amount' => $wallet_amount
        ];
    }, $users);
}
public function get_users_count($search){
    $this->db->from('users u');
    $this->db->where('u.delete_status', 1);
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('u.mobile', $search);
        $this->db->or_like('u.email', $search);
        $this->db->group_end();
    }
    return $this->db->count_all_results();
}
public function get_subscribed_users($limit, $start, $search){
    // 1. Fetch only users who have at least one health_card_holders record
    $this->db->select('u.*, bg.name as blood_group, cc.name as coverage_category, uw.wallet_amount');
    $this->db->from('users u');
    $this->db->join('blood_groups bg', 'bg.id = u.blood_group', 'left');
    $this->db->join('coverage_categories cc', 'cc.id = u.coverage_category', 'left');
    $this->db->join('user_wallet uw', 'uw.user_id = u.id', 'left');
    $this->db->join('health_card_holders hch', 'hch.user_id = u.id', 'inner'); // only subscribed users
    $this->db->where('u.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('u.mobile', $search);
        $this->db->or_like('u.email', $search);
        $this->db->group_end();
    }

    $this->db->group_by('u.id'); // ensure unique users
    $this->db->order_by('u.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();

    // 2. Collect user IDs
    $user_ids = array_column($users, 'id');

    $CI = &get_instance();

    // 3. Fetch all family members
    $family_members_map = [];
    if (!empty($user_ids)) {
        $CI->db->select('id, user_id, name, dob, gender, email, mobile, image as user_image');
        $CI->db->from('family_members');
        $CI->db->where_in('user_id', $user_ids);
        $family_members = $CI->db->get()->result_array();

        foreach ($family_members as $member) {
            $member['gender_label'] = ($member['gender'] == 1) ? 'Male' : (($member['gender'] == 2) ? 'Female' : 'Other');
            $family_members_map[$member['user_id']][] = $member;
        }
    }

    // 4. Fetch user addresses
    $user_addresses_map = [];
    if (!empty($user_ids)) {
        $CI->db->select('id, user_id, address, hno, building_no, landmark, lat, lon, address_type, pincode, state, default_address');
        $CI->db->from('user_addresses');
        $CI->db->where('status', 1);
        $CI->db->where('delete_status', 1);
        $CI->db->where_in('user_id', $user_ids);
        $user_addresses = $CI->db->get()->result_array();

        foreach ($user_addresses as $address) {
            $user_addresses_map[$address['user_id']][] = $address;
        }
    }

    // 5. Fetch latest subscription (1 per user)
    $health_cards_map = [];
    if (!empty($user_ids)) {
        $CI->db->select('user_id, name, duration, from_date, to_date, price, total_premium, gst, total_amount, transaction_id,invoice');
        $CI->db->from('health_card_holders');
        $CI->db->where_in('user_id', $user_ids);
        $CI->db->order_by('id', 'DESC');
        $cards = $CI->db->get()->result_array();

        foreach ($cards as $card) {
            if (!isset($health_cards_map[$card['user_id']])) {
                $health_cards_map[$card['user_id']] = $card; // latest record
            }
        }
    }

    // 6. Final formatting
    return array_map(function ($user) use ($family_members_map, $user_addresses_map, $health_cards_map) {
        $gender_label = ($user['gender'] == 1) ? 'Male' : (($user['gender'] == 2) ? 'Female' : 'Other');
        $modified_on = !empty($user['modified_on']) ? $user['modified_on'] : '';
        $wallet_amount = !empty($user['wallet_amount']) ? $user['wallet_amount'] : 0;

        return [
            'id' => (int)$user['id'],
            'name' => $user['name'],
            'mobile' => $user['mobile'],
            'email' => $user['email'],
            'dob' => $user['dob'],
            'gender' => $gender_label,
            'image' => $user['image'],
            'blood_group' => $user['blood_group'],
            'coverage_category' => $user['coverage_category'],
            'status' => $user['status'],
            'delete_status' => $user['delete_status'],
            'created_on' => $user['created_on'],
            'modified_on' => $modified_on,
            'family_members' => $family_members_map[$user['id']] ?? [],
            'count' => count($family_members_map[$user['id']] ?? []),
            'address' => $user_addresses_map[$user['id']] ?? [],
            'address_count' => count($user_addresses_map[$user['id']] ?? []),
            'subscription' => $health_cards_map[$user['id']] ?? (object)[],
            'wallet_amount' => $wallet_amount
        ];
    }, $users);
}
public function get_subscribed_users_count($search){
    $this->db->from('users u');
    $this->db->join('health_card_holders hch', 'hch.user_id = u.id', 'inner'); // only subscribed users
    $this->db->where('u.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('u.mobile', $search);
        $this->db->or_like('u.email', $search);
        $this->db->group_end();
    }

    $this->db->group_by('u.id'); // unique users only
    $query = $this->db->get();

    return $query->num_rows(); // count of unique subscribed users
}
public function get_unsubscribed_users($limit, $start, $search){
    // 1. Fetch only users who have NO record in health_card_holders
    $this->db->select('u.*, bg.name as blood_group, cc.name as coverage_category, uw.wallet_amount');
    $this->db->from('users u');
    $this->db->join('blood_groups bg', 'bg.id = u.blood_group', 'left');
    $this->db->join('coverage_categories cc', 'cc.id = u.coverage_category', 'left');
    $this->db->join('user_wallet uw', 'uw.user_id = u.id', 'left');
    $this->db->where('u.delete_status', 1);
    $this->db->where('NOT EXISTS (SELECT 1 FROM health_card_holders hch WHERE hch.user_id = u.id)', NULL, FALSE); // exclude subscribed

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('u.mobile', $search);
        $this->db->or_like('u.email', $search);
        $this->db->group_end();
    }

    $this->db->group_by('u.id'); // ensure unique users
    $this->db->order_by('u.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();

    // 2. Collect user IDs
    $user_ids = array_column($users, 'id');

    $CI = &get_instance();

    // 3. Fetch all family members
    $family_members_map = [];
    if (!empty($user_ids)) {
        $CI->db->select('id, user_id, name, dob, gender, email, mobile, image as user_image');
        $CI->db->from('family_members');
        $CI->db->where_in('user_id', $user_ids);
        $family_members = $CI->db->get()->result_array();

        foreach ($family_members as $member) {
            $member['gender_label'] = ($member['gender'] == 1) ? 'Male' : (($member['gender'] == 2) ? 'Female' : 'Other');
            $family_members_map[$member['user_id']][] = $member;
        }
    }

    // 4. Fetch user addresses
    $user_addresses_map = [];
    if (!empty($user_ids)) {
        $CI->db->select('id, user_id, address, hno, building_no, landmark, lat, lon, address_type, pincode, state, default_address');
        $CI->db->from('user_addresses');
        $CI->db->where('status', 1);
        $CI->db->where('delete_status', 1);
        $CI->db->where_in('user_id', $user_ids);
        $user_addresses = $CI->db->get()->result_array();

        foreach ($user_addresses as $address) {
            $user_addresses_map[$address['user_id']][] = $address;
        }
    }

    // 5. No subscriptions for unsubscribed users
    $health_cards_map = [];

    // 6. Final formatting
    return array_map(function ($user) use ($family_members_map, $user_addresses_map, $health_cards_map) {
        $gender_label = ($user['gender'] == 1) ? 'Male' : (($user['gender'] == 2) ? 'Female' : 'Other');
        $modified_on = !empty($user['modified_on']) ? $user['modified_on'] : '';
        $wallet_amount = !empty($user['wallet_amount']) ? $user['wallet_amount'] : 0;

        return [
            'id' => (int)$user['id'],
            'name' => $user['name'],
            'mobile' => $user['mobile'],
            'email' => $user['email'],
            'dob' => $user['dob'],
            'gender' => $gender_label,
            'image' => $user['image'],
            'blood_group' => $user['blood_group'],
            'coverage_category' => $user['coverage_category'],
            'status' => $user['status'],
            'delete_status' => $user['delete_status'],
            'created_on' => $user['created_on'],
            'modified_on' => $modified_on,
            'family_members' => $family_members_map[$user['id']] ?? [],
            'count' => count($family_members_map[$user['id']] ?? []),
            'address' => $user_addresses_map[$user['id']] ?? [],
            'address_count' => count($user_addresses_map[$user['id']] ?? []),
            'subscription' => (object)[], // always empty for unsubscribed
            'wallet_amount' => $wallet_amount
        ];
    }, $users);
}
public function get_unsubscribed_users_count($search){
    $this->db->from('users u');
    $this->db->where('u.delete_status', 1);
    $this->db->where("u.id NOT IN (SELECT user_id FROM health_card_holders)", NULL, FALSE);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('u.mobile', $search);
        $this->db->or_like('u.email', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*users*/

/*sales_hierarchy*/

/*state_heads*/
public function get_state_heads($limit, $start, $search){
    // 1. Fetch users
    $this->db->select('sh.*, s.name as state_name');
    $this->db->from('state_heads sh');
    $this->db->join('states s', 's.id = sh.state_id', 'left');
    $this->db->where('sh.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('sh.name', $search);
        $this->db->or_like('sh.unique_id', $search);
        $this->db->or_like('sh.mobile', $search);
        $this->db->or_like('sh.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('sh.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();
    
    return $users;
}
public function get_state_heads_count($search){
    $this->db->from('state_heads sh');
    $this->db->join('states s', 's.id = sh.state_id', 'left');
    $this->db->where('sh.delete_status', 1);
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('sh.name', $search);
        $this->db->or_like('sh.unique_id', $search);
        $this->db->or_like('sh.mobile', $search);
        $this->db->or_like('sh.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->group_end();
    }
    return $this->db->count_all_results();
}
/*state_heads*/

/*zonal_heads*/
public function get_zonal_heads($limit, $start, $search){
    // 1. Fetch users
    $this->db->select('zh.*, s.name as state_name,sh.name as state_head_name');
    $this->db->from('zonal_heads zh');
    $this->db->join('states s', 's.id = zh.state_id', 'left');
    $this->db->join('state_heads sh', 'sh.id = zh.state_head_id', 'left');
    $this->db->where('zh.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('zh.name', $search);
        $this->db->or_like('zh.unique_id', $search);
        $this->db->or_like('zh.mobile', $search);
        $this->db->or_like('zh.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->or_like('sh.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('zh.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();
    
    return $users;
}
public function get_zonal_heads_count($search){
    $this->db->from('zonal_heads zh');
    $this->db->join('states s', 's.id = zh.state_id', 'left');
    $this->db->join('state_heads sh', 'sh.id = zh.state_head_id', 'left');
    $this->db->where('zh.delete_status', 1);
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('zh.name', $search);
        $this->db->or_like('zh.unique_id', $search);
        $this->db->or_like('zh.mobile', $search);
        $this->db->or_like('zh.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->or_like('sh.name', $search);
        $this->db->group_end();
    }
    return $this->db->count_all_results();
}
/*zonal_heads*/

/*territory_heads*/
public function get_territory_heads($limit, $start, $search){
    $this->db->select('th.*, 
        s.name as state_name, 
        sh.name as state_head_name, 
        zh.name as zonal_head_name,
        GROUP_CONCAT(d.name ORDER BY d.name SEPARATOR ", ") as district_names'
    );
    $this->db->from('territory_heads th');
    $this->db->join('states s', 's.id = th.state_id', 'left');
    $this->db->join('state_heads sh', 'sh.id = th.state_head_id', 'left');
    $this->db->join('zonal_heads zh', 'zh.id = th.zonal_head_id', 'left');
    $this->db->join('districts d', 'FIND_IN_SET(d.id, th.district_id) > 0', 'left');
    $this->db->where('th.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('th.name', $search);
        $this->db->or_like('th.unique_id', $search);
        $this->db->or_like('th.mobile', $search);
        $this->db->or_like('th.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->or_like('sh.name', $search);
        $this->db->or_like('zh.name', $search);
        $this->db->or_like('d.name', $search); // 🔍 Add search by district name
        $this->db->group_end();
    }

    $this->db->group_by('th.id'); // Required due to GROUP_CONCAT
    $this->db->order_by('th.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();

    return $query->result_array();
}
public function get_territory_heads_count($search){
    $this->db->from('territory_heads th');
    $this->db->join('states s', 's.id = th.state_id', 'left');
    $this->db->join('state_heads sh', 'sh.id = th.state_head_id', 'left');
    $this->db->join('zonal_heads zh', 'zh.id = th.zonal_head_id', 'left');
    $this->db->join('districts d', 'd.id = th.district_id', 'left'); // Add this line to join districts
    $this->db->where('th.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('th.name', $search);
        $this->db->or_like('th.unique_id', $search);
        $this->db->or_like('th.mobile', $search);
        $this->db->or_like('th.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->or_like('sh.name', $search);
        $this->db->or_like('zh.name', $search);
        $this->db->or_like('d.name', $search); // Add this line to search district name
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*territory_heads*/

/*regional_managers*/
public function get_regional_managers($limit, $start, $search){
    $this->db->select('rm.*, s.name as state_name, d.name as district_name, sh.name as state_head_name, zh.name as zonal_head_name, th.name as territory_head_name');
    $this->db->from('regional_managers rm');
    $this->db->join('states s', 's.id = rm.state_id', 'left');
    $this->db->join('districts d', 'd.id = rm.district_id', 'left');
    $this->db->join('state_heads sh', 'sh.id = rm.state_head_id', 'left');
    $this->db->join('zonal_heads zh', 'zh.id = rm.zonal_head_id', 'left');
    $this->db->join('territory_heads th', 'th.id = rm.territory_head_id', 'left');
    $this->db->where('rm.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('rm.name', $search);
        $this->db->or_like('rm.unique_id', $search);
        $this->db->or_like('rm.mobile', $search);
        $this->db->or_like('rm.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('sh.name', $search);
        $this->db->or_like('zh.name', $search);
        $this->db->or_like('th.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('rm.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $managers = $query->result_array();

    // Fetch mandal names separately (optional)
    foreach ($managers as &$mgr) {
        if (!empty($mgr['mandal_id'])) {
            $mandal_ids = explode(',', $mgr['mandal_id']);
            $this->db->select('name');
            $this->db->from('mandals');
            $this->db->where_in('id', $mandal_ids);
            $mandals = $this->db->get()->result_array();
            $mgr['mandal_names'] = implode(', ', array_column($mandals, 'name'));
        } else {
            $mgr['mandal_names'] = '';
        }
    }

    return $managers;
}
public function get_regional_managers_count($search){
    $this->db->select('COUNT(DISTINCT rm.id) as total');
    $this->db->from('regional_managers rm');
    $this->db->join('states s', 's.id = rm.state_id', 'left');
    $this->db->join('districts d', 'd.id = rm.district_id', 'left');
    $this->db->join('state_heads sh', 'sh.id = rm.state_head_id', 'left');
    $this->db->join('zonal_heads zh', 'zh.id = rm.zonal_head_id', 'left');
    $this->db->join('territory_heads th', 'th.id = rm.territory_head_id', 'left');
    $this->db->where('rm.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('rm.name', $search);
        $this->db->or_like('rm.unique_id', $search);
        $this->db->or_like('rm.mobile', $search);
        $this->db->or_like('rm.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('sh.name', $search);
        $this->db->or_like('zh.name', $search);
        $this->db->or_like('th.name', $search);
        $this->db->group_end();
    }

    $query = $this->db->get();
    return $query->row()->total;
}
/*regional_managers*/

/*medical_advisors*/
public function get_medical_advisors($limit, $start, $search){
    // 1. Fetch users
    $this->db->select('ma.*, s.name as state_name, d.name as district_name,sh.name as state_head_name,zh.name as zonal_head_name,th.name as territory_head_name,rm.name as regional_manager_name,m.name as mandal_name,v.name as village_name');
    $this->db->from('executives ma');
    $this->db->join('states s', 's.id = ma.state_id', 'left');
    $this->db->join('districts d', 'd.id = ma.district_id', 'left');
    $this->db->join('mandals m', 'm.id = ma.mandal_id', 'left');
    $this->db->join('villages v', 'v.id = ma.village_id', 'left');
    $this->db->join('state_heads sh', 'sh.id = ma.state_head_id', 'left');
    $this->db->join('zonal_heads zh', 'zh.id = ma.zonal_head_id', 'left');
    $this->db->join('territory_heads th', 'th.id = ma.territory_head_id', 'left');
    $this->db->join('regional_managers rm', 'rm.id = ma.regional_manager_id', 'left');
    $this->db->where('ma.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('ma.name', $search);
        $this->db->or_like('ma.unique_id', $search);
        $this->db->or_like('ma.mobile', $search);
        $this->db->or_like('ma.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('m.name', $search);
        $this->db->or_like('v.name', $search);
        $this->db->or_like('sh.name', $search);
        $this->db->or_like('zh.name', $search);
        $this->db->or_like('th.name', $search);
        $this->db->or_like('rm.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('ma.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();
    
    return $users;
}
public function get_medical_advisors_count($search){
    $this->db->from('executives ma');
    $this->db->join('states s', 's.id = ma.state_id', 'left');
    $this->db->join('districts d', 'd.id = ma.district_id', 'left');
    $this->db->join('mandals m', 'm.id = ma.mandal_id', 'left');
    $this->db->join('villages v', 'v.id = ma.village_id', 'left');
    $this->db->join('state_heads sh', 'sh.id = ma.state_head_id', 'left');
    $this->db->join('zonal_heads zh', 'zh.id = ma.zonal_head_id', 'left');
    $this->db->join('territory_heads th', 'th.id = ma.territory_head_id', 'left');
    $this->db->join('regional_managers rm', 'rm.id = ma.regional_manager_id', 'left');
    $this->db->where('ma.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('ma.name', $search);
        $this->db->or_like('ma.unique_id', $search);
        $this->db->or_like('ma.mobile', $search);
        $this->db->or_like('ma.email', $search);
        $this->db->or_like('s.name', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('m.name', $search);
        $this->db->or_like('v.name', $search);
        $this->db->or_like('sh.name', $search);
        $this->db->or_like('zh.name', $search);
        $this->db->or_like('th.name', $search);
        $this->db->or_like('rm.name', $search);
        $this->db->group_end();
    }
    return $this->db->count_all_results();
}
/*medical_advisors*/

/*sales_target*/
public function get_sales_target($limit, $start, $search){
    // 1. Fetch users
    $this->db->select('st.*, m.name as month_name,rm.name as name');
    $this->db->from('regional_managers_sales_target st');
    $this->db->join('regional_managers rm', 'rm.id = st.regional_manager_id', 'left');
    $this->db->join('months m', 'm.id = st.month', 'left');
    //$this->db->where('st.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('rm.name', $search);
        $this->db->or_like('m.name', $search);
        $this->db->or_like('st.year', $search);
        $this->db->group_end();
    }

    $this->db->order_by('st.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();
    
    return $users;
}
public function get_sales_target_count($search){
    $this->db->from('regional_managers_sales_target st');
    $this->db->join('regional_managers rm', 'rm.id = st.regional_manager_id', 'left');
    $this->db->join('months m', 'm.id = st.month', 'left');
    //$this->db->where('st.delete_status', 1);
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('rm.name', $search);
        $this->db->or_like('m.name', $search);
        $this->db->or_like('st.year', $search);
        $this->db->group_end();
    }
    return $this->db->count_all_results();
}
/*sales_target*/

/*medical_advisor_sales_target*/
public function get_medical_advisor_sales_target($limit, $start, $search){
    // 1. Fetch users
    $this->db->select('st.*, m.name as month_name,rm.name as name');
    $this->db->from('executive_sales_target st');
    $this->db->join('executives rm', 'rm.id = st.executive_id', 'left');
    $this->db->join('months m', 'm.id = st.month', 'left');
    //$this->db->where('st.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('rm.name', $search);
        $this->db->or_like('m.name', $search);
        $this->db->or_like('st.year', $search);
        $this->db->group_end();
    }

    $this->db->order_by('st.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();
    
    return $users;
}
public function get_medical_advisor_sales_target_count($search){
    $this->db->from('executive_sales_target st');
    $this->db->join('executives rm', 'rm.id = st.executive_id', 'left');
    $this->db->join('months m', 'm.id = st.month', 'left');
    //$this->db->where('st.delete_status', 1);
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('rm.name', $search);
        $this->db->or_like('m.name', $search);
        $this->db->or_like('st.year', $search);
        $this->db->group_end();
    }
    return $this->db->count_all_results();
}
/*medical_advisor_sales_target*/

/*regional_manager_sales_target*/
public function get_regional_manager_sales_target($month_year, $limit, $start, $search){
    $month = $year = null;
    if (!empty($month_year)) {
        $parts = explode('-', $month_year);
        $month = $parts[0];
        $year  = $parts[1];
    }

    $this->db->select('
        st.*, m.name as month_name,
        e.name as name, s.name as state_name, d.name as district_name,
        GROUP_CONCAT(DISTINCT ma.name ORDER BY ma.name SEPARATOR ", ") AS mandal_names,
        IFNULL(sales_data.target_achieved, 0) as target_achieved,
        IFNULL(sales_data.total_amount, 0) as total_amount
    ');
    $this->db->from('regional_managers_sales_target st');
    $this->db->join('regional_managers e', 'e.id = st.regional_manager_id', 'left');
    $this->db->join('months m', 'm.id = st.month', 'left');
    $this->db->join('states s', 's.id = e.state_id', 'left');
    $this->db->join('districts d', 'd.id = e.district_id', 'left');
    $this->db->join('mandals ma', 'FIND_IN_SET(ma.id, e.mandal_id)', 'left');

    $this->db->join("(
        SELECT 
            regional_manager_id,
            COUNT(id) as target_achieved,
            SUM(total_amount) as total_amount,
            MONTH(month) as sale_month,
            YEAR(year) as sale_year
        FROM executive_sales_completed
        GROUP BY regional_manager_id, sale_month, sale_year
    ) as sales_data", 
    'sales_data.regional_manager_id = st.regional_manager_id 
     AND sales_data.sale_month = st.month 
     AND sales_data.sale_year = st.year', 
    'left');

    if (!empty($month) && !empty($year)) {
        $this->db->where('st.month', $month);
        $this->db->where('st.year', $year);
    }

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('e.name', $search);
        $this->db->group_end();
    }

    $this->db->group_by('st.id'); // Important when using GROUP_CONCAT
    $this->db->order_by('st.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return !empty($result) ? $result : []; // ✅ Return empty array if no result
}
public function get_regional_manager_sales_target_count($month_year, $search){
    $month = $year = null;
    if (!empty($month_year)) {
        $parts = explode('-', $month_year);
        $month = $parts[0];
        $year  = $parts[1];
    }

    $this->db->from('regional_managers_sales_target st');
    $this->db->join('regional_managers e', 'e.id = st.regional_manager_id', 'left');
    $this->db->join('months m', 'm.id = st.month', 'left');
    $this->db->join('states s', 's.id = e.state_id', 'left');
    $this->db->join('districts d', 'd.id = e.district_id', 'left');
    $this->db->join('mandals ma', 'FIND_IN_SET(ma.id, e.mandal_id)', 'left');

    // Subquery for executive sales completed grouped by RM, month, and year
    $sales_subquery = "(SELECT 
                regional_manager_id,
                COUNT(id) as target_achieved,
                SUM(total_amount) as total_amount,
                MONTH(month) as sale_month,
                YEAR(year) as sale_year
            FROM executive_sales_completed
            GROUP BY regional_manager_id, sale_month, sale_year
        ) as sales_data";

    $this->db->join($sales_subquery, 
        'sales_data.regional_manager_id = st.regional_manager_id 
         AND sales_data.sale_month = st.month 
         AND sales_data.sale_year = st.year', 
        'left'
    );

    // Filter by selected month and year
    if (!empty($month) && !empty($year)) {
        $this->db->where('st.month', $month);
        $this->db->where('st.year', $year);
    }

    // Apply search filter
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('e.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*regional_manager_sales_target*/

/*executive_sales_requests*/
public function get_executive_sales_requests($month_year,$limit, $start, $search){
    // 1. Fetch users
    $this->db->select('st.*, e.name as name,rm.name as regional_manager');
    $this->db->from('executive_sales_commission_requests st');
    $this->db->join('executives e', 'e.id = st.executive_id', 'left');
    $this->db->join('regional_managers rm', 'rm.id = e.regional_manager_id', 'left');
    $this->db->where('st.status', 'requested');
    
    if (!empty($month_year)) {
        $parts = explode('-', $month_year);
        $month = $parts[0];
        $year  = $parts[1];
        $this->db->where('MONTH(request_date)', $month);
        $this->db->where('YEAR(request_date)', $year);
    }

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('e.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('st.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();
    
    return $users;
}
public function get_executive_sales_requests_count($month_year,$search){
    $this->db->from('executive_sales_commission_requests st');
    $this->db->join('executives e', 'e.id = st.executive_id', 'left');
    $this->db->join('regional_managers rm', 'rm.id = e.regional_manager_id', 'left');
    $this->db->where('st.status', 'requested');
    if (!empty($month_year)) {
        $parts = explode('-', $month_year);
        $month = $parts[0];
        $year  = $parts[1];
        $this->db->where('MONTH(request_date)', $month);
        $this->db->where('YEAR(request_date)', $year);
    }
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('e.name', $search);
        $this->db->group_end();
    }
    return $this->db->count_all_results();
}
public function get_executive_sales_history($month_year, $id, $limit, $start, $search){
    $executive_id = base64_decode($id);

    // Extract month and year if provided
    $month = $year = null;
    if (!empty($month_year)) {
        $parts = explode('-', $month_year);
        $month = $parts[0];
        $year  = $parts[1];
    }

    // Select fields
    $this->db->select('
        st.*, 
        m.name as month_name,
        e.name as name,
        IFNULL(sales_data.target_achieved, 0) as target_achieved,
        IFNULL(sales_data.total_amount, 0) as total_amount
    ');
    $this->db->from('executive_sales_target st');
    $this->db->join('executives e', 'e.id = st.executive_id', 'left');
    $this->db->join('months m', 'm.id = st.month', 'left');

    // Join with monthly sales completed data
    $this->db->join("(SELECT 
                        executive_id,
                        month,
                        year,
                        COUNT(id) as target_achieved,
                        SUM(total_amount) as total_amount
                    FROM executive_sales_completed
                    WHERE executive_id = '{$executive_id}'
                    GROUP BY executive_id, month, year
                ) as sales_data", 
                'sales_data.executive_id = st.executive_id AND sales_data.month = st.month AND sales_data.year = st.year', 
                'left'
    );

    // Filter by executive
    $this->db->where('st.executive_id', $executive_id);

    // Filter by month-year
    if (!empty($month) && !empty($year)) {
        $this->db->where('st.month', $month);
        $this->db->where('st.year', $year);
    }

    // Search
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('e.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('st.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_executive_sales_history_count($month_year, $id, $search){
    $executive_id = base64_decode($id);

    $month = $year = null;
    if (!empty($month_year)) {
        $parts = explode('-', $month_year);
        $month = $parts[0];
        $year  = $parts[1];
    }

    $this->db->from('executive_sales_target st');
    $this->db->join('executives e', 'e.id = st.executive_id', 'left');
    $this->db->join('months m', 'm.id = st.month', 'left');

    $this->db->join("(SELECT 
                        executive_id,
                        month,
                        year,
                        COUNT(id) as target_achieved,
                        SUM(total_amount) as total_amount
                    FROM executive_sales_completed
                    WHERE executive_id = '{$executive_id}'
                    GROUP BY executive_id, month, year
                ) as sales_data", 
                'sales_data.executive_id = st.executive_id AND sales_data.month = st.month AND sales_data.year = st.year', 
                'left'
    );

    $this->db->where('st.executive_id', $executive_id);

    if (!empty($month) && !empty($year)) {
        $this->db->where('st.month', $month);
        $this->db->where('st.year', $year);
    }

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('e.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*executive_sales_requests*/

/*executive_sales_credit*/
public function get_executive_sales_credit($month_year,$limit, $start, $search){
    // 1. Fetch users
    $this->db->select('st.*, e.name as name,rm.name as regional_manager');
    $this->db->from('executive_sales_commission_requests st');
    $this->db->join('executives e', 'e.id = st.executive_id', 'left');
    $this->db->join('regional_managers rm', 'rm.id = e.regional_manager_id', 'left');
    $this->db->where('st.status', 'credited');
    
    if (!empty($month_year)) {
        $parts = explode('-', $month_year);
        $month = $parts[0];
        $year  = $parts[1];
        $this->db->where('MONTH(credit_date)', $month);
        $this->db->where('YEAR(credit_date)', $year);
    }

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('e.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('st.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();
    
    return $users;
}
public function get_executive_sales_credit_count($month_year,$search){
    $this->db->from('executive_sales_commission_requests st');
    $this->db->join('executives e', 'e.id = st.executive_id', 'left');
    $this->db->join('regional_managers rm', 'rm.id = e.regional_manager_id', 'left');
    $this->db->where('st.status', 'credited');
    if (!empty($month_year)) {
        $parts = explode('-', $month_year);
        $month = $parts[0];
        $year  = $parts[1];
        $this->db->where('MONTH(credit_date)', $month);
        $this->db->where('YEAR(credit_date)', $year);
    }
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('e.name', $search);
        $this->db->group_end();
    }
    return $this->db->count_all_results();
}
/*executive_sales_credit*/

/*sales_hierarchy*/

/*sub_admins*/
public function get_sub_admins($sess_data, $limit, $start, $search) {
    $this->db->select('
        s.id,
        s.name,
        s.mobile,
        s.image,
        s.status,
        s.delete_status,
        s.created_on,
        s.modified_on,
        GROUP_CONCAT(DISTINCT r.name ORDER BY r.id SEPARATOR ", ") AS permission_name
    ');
    $this->db->from('sub_admins s');
    $this->db->where(['s.main_data_id' => $sess_data, 's.delete_status' => 1]);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('s.name', $search);
        $this->db->or_like('s.mobile', $search);
        $this->db->group_end();
    }

    $this->db->join('permissions p', 'p.sub_admin_id = s.id', 'left');
    $this->db->join('roles r', 'r.id = p.role_id and r.id!=1', 'left');
    $this->db->group_by('s.id'); // Group by sub-admin
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_sub_admins_count($sess_data,$search){
    $this->db->where(['main_data_id' => $sess_data,'delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->or_like('mobile',$search);
        $this->db->group_end();
    }
    $query = $this->db->get('sub_admins');
    return $query->num_rows();
}
/*sub_admins*/

/*tele_callers*/
public function get_tele_callers($limit, $start, $search) {
    $this->db->select('
        s.id,
        s.name,
        s.mobile,
        s.image,
        s.status,
        s.delete_status,
        s.created_on,
        s.modified_on,
    ');
    $this->db->from('tele_callers s');
    $this->db->where(['s.delete_status' => 1]);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('s.name', $search);
        $this->db->or_like('s.mobile', $search);
        $this->db->group_end();
    }

    $this->db->group_by('s.id'); // Group by sub-admin
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_tele_callers_count($search){
    $this->db->where(['delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->or_like('mobile',$search);
        $this->db->group_end();
    }
    $query = $this->db->get('tele_callers');
    return $query->num_rows();
}
/*tele_callers*/

/*banners*/
public function get_banners($limit,$start,$search){
    $this->db->where(['delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('image',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get('banners');
    return $query->result_array();
}
public function get_banners_count($search){
    $this->db->where(['delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('image',$search);
        $this->db->group_end();
    }
    $query = $this->db->get('banners');
    return $query->num_rows();
}
/*banners*/

/*lab_test_banners*/
public function get_lab_test_banners($limit,$start,$search){
    $this->db->where(['delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('image',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get('lab_test_banners');
    return $query->result_array();
}
public function get_lab_test_banners_count($search){
    $this->db->where(['delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('image',$search);
        $this->db->group_end();
    }
    $query = $this->db->get('lab_test_banners');
    return $query->num_rows();
}
/*lab_test_banners*/

/*blood_groups*/
public function get_blood_groups($limit,$start,$search){
    $this->db->where(['delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get('blood_groups');
    return $query->result_array();
}
public function get_blood_groups_count($search){
    $this->db->where(['delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get('blood_groups');
    return $query->num_rows();
}
/*blood_groups*/

/*categories*/
public function get_categories($limit, $start, $search) {
    $this->db->select('c.*');
    $this->db->from('categories c');
    
    // WHERE conditions
    $this->db->where([
        'c.delete_status' => 1
    ]);
    
    // Search filters
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('c.name', $search);
        $this->db->group_end();
    }

    // GROUP BY required due to GROUP_CONCAT
    $this->db->order_by('c.id');

    // Pagination
    $this->db->limit($limit, $start);

    // Execute query
    $query = $this->db->get();
    return $query->result_array();
}
public function get_categories_count($search){
    $this->db->select('c.*')->from('categories c');
    $this->db->where(['c.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('c.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*categories*/

/*coverage_categories*/
public function get_coverage_categories($limit,$start,$search){
    $this->db->select('cc.*')->from('coverage_categories cc');
    $this->db->where(['cc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cc.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_coverage_categories_count($search){
    $this->db->select('cc.*')->from('coverage_categories cc');
    $this->db->where(['cc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cc.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*coverage_categories*/

/*states*/
public function get_states($limit,$start,$search){
    $this->db->select('s.*')->from('states s');
    $this->db->where(['s.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('s.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_states_count($search){
    $this->db->select('s.*')->from('states s');
    $this->db->where(['s.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('s.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*states*/

/*districts*/
public function get_districts($limit,$start,$search){
    $this->db->select('d.*,s.name as state_name')->from('districts d');
    $this->db->where(['d.delete_status' => 1]);
    $this->db->join('states s','s.id=d.state_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('d.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_districts_count($search){
    $this->db->select('d.*,s.name as state_name')->from('districts d');
    $this->db->where(['d.delete_status' => 1]);
    $this->db->join('states s','s.id=d.state_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('d.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*districts*/

/*cities*/
public function get_cities($limit,$start,$search){
    $this->db->select('c.*,s.name as state_name,d.name as district_name')->from('cities c');
    $this->db->where(['c.delete_status' => 1]);
    $this->db->join('states s','s.id=c.state_id','left');
    $this->db->join('districts d','d.id=c.district_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_cities_count($search){
    $this->db->select('c.*,s.name as state_name,d.name as district_name')->from('cities c');
    $this->db->where(['c.delete_status' => 1]);
    $this->db->join('states s','s.id=c.state_id','left');
    $this->db->join('districts d','d.id=c.district_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*cities*/

/*mandals*/
public function get_mandals($limit,$start,$search){
    $this->db->select('c.*,s.name as state_name,d.name as district_name')->from('mandals c');
    $this->db->where(['c.delete_status' => 1]);
    $this->db->join('states s','s.id=c.state_id','left');
    $this->db->join('districts d','d.id=c.district_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_mandals_count($search){
    $this->db->select('c.*,s.name as state_name,d.name as district_name')->from('mandals c');
    $this->db->where(['c.delete_status' => 1]);
    $this->db->join('states s','s.id=c.state_id','left');
    $this->db->join('districts d','d.id=c.district_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*mandals*/

/*villages*/
public function get_villages($limit,$start,$search){
    $this->db->select('c.*,s.name as state_name,d.name as district_name,m.name as mandal_name')->from('villages c');
    $this->db->where(['c.delete_status' => 1]);
    $this->db->join('states s','s.id=c.state_id','left');
    $this->db->join('districts d','d.id=c.district_id','left');
    $this->db->join('mandals m','m.id=c.mandal_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_villages_count($search){
    $this->db->select('c.*,s.name as state_name,d.name as district_name')->from('villages c');
    $this->db->where(['c.delete_status' => 1]);
    $this->db->join('states s','s.id=c.state_id','left');
    $this->db->join('districts d','d.id=c.district_id','left');
    $this->db->join('mandals m','m.id=c.mandal_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*villages*/

/*subscriptions*/
public function get_subscriptions($limit,$start,$search){
    $this->db->select('hc.*')->from('health_cards hc');
    $this->db->where(['hc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hc.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_subscriptions_count($search){
    $this->db->select('hc.*')->from('health_cards hc');
    $this->db->where(['hc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hc.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*subscriptions*/

/*medical_degrees*/
public function get_medical_degrees($limit,$start,$search){
    $this->db->select('md.*')->from('medical_degrees md');
    $this->db->where(['md.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('md.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_medical_degrees_count($search){
    $this->db->select('md.*')->from('medical_degrees md');
    $this->db->where(['md.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('md.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*medical_degrees*/

/*online_doctor_specialities*/
public function get_online_doctor_specialities($limit,$start,$search){
    $this->db->select('ods.*')->from('online_doctor_specialities ods');
    $this->db->where(['ods.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ods.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_online_doctor_specialities_count($search){
    $this->db->select('ods.*')->from('online_doctor_specialities ods');
    $this->db->where(['ods.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ods.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*online_doctor_specialities*/

/*specialities*/
public function get_specialities($limit,$start,$search){
    $this->db->select('s.*,c.name as cat_name')->from('specialities s');
    $this->db->where(['s.delete_status' => 1]);
    $this->db->join('categories c','c.id=s.cat_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('s.name',$search);
        $this->db->or_like('c.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_specialities_count($search){
    $this->db->select('s.*,c.name as cat_name')->from('specialities s');
    $this->db->where(['s.delete_status' => 1]);
    $this->db->join('categories c','c.id=s.cat_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('s.name',$search);
        $this->db->or_like('c.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*specialities*/

/*questions*/
public function get_questions($limit, $start, $search){
    // 1. Fetch users
    $this->db->select('q.*');
    $this->db->from('questions q');
    $this->db->where('q.delete_status', 1);

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('q.question', $search);
        $this->db->group_end();
    }

    $this->db->order_by('q.id', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $users = $query->result_array();

    // 2. Collect user IDs
    $user_ids = array_column($users, 'id');

    $CI = &get_instance();

    // 3. Fetch all family members
    $family_members_map = [];
    if (!empty($user_ids)) {
        $CI->db->select('id, options,question_id');
        $CI->db->from('question_options');
        $CI->db->where_in('question_id', $user_ids);
        $family_members = $CI->db->get()->result_array();

        foreach ($family_members as $member) {
            $family_members_map[$member['question_id']][] = $member;
        }
    }
    
    // 4. Final user formatting
    return array_map(function ($user) use ($family_members_map) {
        
        $modified_on = !empty($user['modified_on']) ? $user['modified_on'] : '';

        return [
            'id' => (int)$user['id'],
            'question' => $user['question'],
            'answer' => $user['answer'],
            'status' => $user['status'],
            'created_on' => $user['created_on'],
            'modified_on' => $modified_on,
            'family_members' => $family_members_map[$user['id']] ?? []
        ];
    }, $users);
}
public function get_questions_count($search){
    $this->db->from('questions q');
    $this->db->where('q.delete_status', 1);
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('q.question', $search);
        $this->db->group_end();
    }
    return $this->db->count_all_results();
}
/*questions*/

/*coupons*/
public function get_hospital_doctor_coupons($limit,$start,$search){
    $this->db->select('dc.*')->from('doctor_coupons dc');
    $this->db->where(['dc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('dc.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_hospital_doctor_coupons_count($search){
    $this->db->select('dc.*')->from('doctor_coupons dc');
    $this->db->where(['dc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('dc.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_hospital_diagnostic_coupons($limit,$start,$search){
    $this->db->select('hdc.*')->from('hospital_diagnostic_coupons hdc');
    $this->db->where(['hdc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hdc.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_hospital_diagnostic_coupons_count($search){
    $this->db->select('hdc.*')->from('hospital_diagnostic_coupons hdc');
    $this->db->where(['hdc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hdc.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_online_doctor_coupons($limit,$start,$search){
    $this->db->select('odc.*')->from('online_doctor_coupons odc');
    $this->db->where(['odc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('odc.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_online_doctor_coupons_count($search){
    $this->db->select('odc.*')->from('online_doctor_coupons odc');
    $this->db->where(['odc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('odc.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_diagnostic_coupons($limit,$start,$search){
    $this->db->select('dc.*')->from('diagnostic_coupons dc');
    $this->db->where(['dc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('dc.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_diagnostic_coupons_count($search){
    $this->db->select('dc.*')->from('diagnostic_coupons dc');
    $this->db->where(['dc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('dc.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_lab_test_coupons($limit,$start,$search){
    $this->db->select('ltc.*')->from('lab_test_coupons ltc');
    $this->db->where(['ltc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ltc.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_lab_test_coupons_count($search){
    $this->db->select('ltc.*')->from('lab_test_coupons ltc');
    $this->db->where(['ltc.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ltc.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*coupons*/

/*hospitals*/
public function get_hospitals($limit,$start,$search){
    $this->db->select('md.*,c.name as cat_name,s.name as state_name,d.name as district_name,ci.name as city_name')->from('main_data md');
    $this->db->where(['md.delete_status' => 1]);
    $this->db->join('categories c','c.id=md.cat_id','left');
    $this->db->join('states s','s.id=md.state_id','left');
    $this->db->join('districts d','d.id=md.district_id','left');
    $this->db->join('cities ci','ci.id=md.city_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('md.name',$search);
        $this->db->or_like('md.mobile',$search);
        $this->db->or_like('md.email',$search);
        $this->db->or_like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->or_like('ci.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_hospitals_count($search){
    $this->db->select('md.*,c.name as cat_name,s.name as state_name,d.name as district_name,ci.name as city_name')->from('main_data md');
    $this->db->where(['md.delete_status' => 1]);
    $this->db->join('categories c','c.id=md.cat_id','left');
    $this->db->join('states s','s.id=md.state_id','left');
    $this->db->join('districts d','d.id=md.district_id','left');
    $this->db->join('cities ci','ci.id=md.city_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('md.name',$search);
        $this->db->or_like('md.mobile',$search);
        $this->db->or_like('md.email',$search);
        $this->db->or_like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->or_like('ci.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_public_relation_agents($sess_data,$limit,$start,$search){
    $this->db->where(['main_data_id' => $sess_data,'delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->or_like('mobile',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get('pr_agents');
    return $query->result_array();
}
public function get_public_relation_agents_count($sess_data,$search){
    $this->db->where(['main_data_id' => $sess_data,'delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->or_like('mobile',$search);
        $this->db->group_end();
    }
    $query = $this->db->get('pr_agents');
    return $query->num_rows();
}
public function get_ambulances($sess_data,$limit,$start,$search){
    $this->db->where(['main_data_id' => $sess_data,'delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->or_like('mobile',$search);
        $this->db->or_like('vehicle_number',$search);
        $this->db->or_like('driver_status',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get('ambulance_drivers');
    return $query->result_array();
}
public function get_ambulances_count($sess_data,$search){
    $this->db->where(['main_data_id' => $sess_data,'delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->or_like('mobile',$search);
        $this->db->or_like('vehicle_number',$search);
        $this->db->or_like('driver_status',$search);
        $this->db->group_end();
    }
    $query = $this->db->get('ambulance_drivers');
    return $query->num_rows();
}
public function get_doctors($sess_data, $limit, $start, $search) {
    $this->db->select('doctors.*, specialities.name AS speciality, GROUP_CONCAT(DISTINCT md.name ORDER BY md.name SEPARATOR ", ") AS qualification');
    $this->db->from('doctors');
    
    // JOINs
    $this->db->join('specialities', 'specialities.id = doctors.speciality_id', 'left');
    $this->db->join('medical_degrees md', 'FIND_IN_SET(md.id, doctors.qualification)', 'left');
    
    // WHERE conditions
    $this->db->where([
        'doctors.main_data_id' => $sess_data,
        'doctors.delete_status' => 1
    ]);
    
    // Search filters
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('doctors.name', $search);
        $this->db->or_like('specialities.name', $search);
        $this->db->or_like('doctors.consult_type', $search);
        $this->db->or_like('doctors.mobile', $search);
        $this->db->group_end();
    }

    // GROUP BY required due to GROUP_CONCAT
    $this->db->group_by('doctors.id');

    // Pagination
    $this->db->limit($limit, $start);

    // Execute query
    $query = $this->db->get();
    return $query->result_array();
}
public function get_doctors_count($sess_data,$search){
    $this->db->select('doctors.*,specialities.name as speciality')->from('doctors');
    $this->db->where(['doctors.main_data_id' => $sess_data,'doctors.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('doctors.name',$search);
        $this->db->or_like('specialities.name',$search);
        $this->db->or_like('doctors.consult_type',$search);
        $this->db->or_like('doctors.mobile', $search);
        $this->db->group_end();
    }
    $this->db->join('specialities','specialities.id=doctors.speciality_id','left');
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_diagnostic($sess_data,$limit,$start,$search){
    $this->db->select('hdp.*')->from('hospital_diagnostic_packages hdp');
    $this->db->where(['hdp.main_data_id' => $sess_data,'hdp.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hdp.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_diagnostic_count($sess_data,$search){
    $this->db->select('hdp.*')->from('hospital_diagnostic_packages hdp');
    $this->db->where(['hdp.main_data_id' => $sess_data,'hdp.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hdp.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_tests_by_diagnostic_id($id){
    // Get all main tests for the diagnostic
    $tests = $this->db->get_where('hospital_diagnostic_tests', [
        'package_id' => base64_decode($id),
        'status' => 1,
        'delete_status' => 1
    ])->result_array();

    foreach ($tests as &$test) {
        // Fetch full sub-test rows instead of just names
        $test['sub_tests'] = $this->db->get_where('hospital_diagnostic_sub_tests', [
            'test_id' => $test['id'],
            'status' => 1,
            'delete_status' => 1
        ])->result_array();
    }

    return $tests;
}
public function get_state_hospitals($id,$limit,$start,$search){
    $this->db->select('md.*,c.name as cat_name,s.name as state_name,d.name as district_name,ci.name as city_name')->from('main_data md');
    $this->db->where(["md.state_id" => $id,"md.delete_status" => 1]);
    $this->db->join('categories c','c.id=md.cat_id','left');
    $this->db->join('states s','s.id=md.state_id','left');
    $this->db->join('districts d','d.id=md.district_id','left');
    $this->db->join('cities ci','ci.id=md.city_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('md.name',$search);
        $this->db->or_like('md.mobile',$search);
        $this->db->or_like('md.email',$search);
        $this->db->or_like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->or_like('ci.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_state_hospitals_count($id,$search){
    $this->db->select('md.*,c.name as cat_name,s.name as state_name,d.name as district_name,ci.name as city_name')->from('main_data md');
    $this->db->where(["md.state_id" => $id,"md.delete_status" => 1]);
    $this->db->join('categories c','c.id=md.cat_id','left');
    $this->db->join('states s','s.id=md.state_id','left');
    $this->db->join('districts d','d.id=md.district_id','left');
    $this->db->join('cities ci','ci.id=md.city_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('md.name',$search);
        $this->db->or_like('md.mobile',$search);
        $this->db->or_like('md.email',$search);
        $this->db->or_like('c.name',$search);
        $this->db->or_like('s.name',$search);
        $this->db->or_like('d.name',$search);
        $this->db->or_like('ci.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*hospitals*/

/*pharmacies*/
public function get_pharmacies($limit,$start,$search){
    $this->db->select('p.*')->from('pharmacies p');
    $this->db->where(['p.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('p.name',$search);
        $this->db->or_like('p.mobile',$search);
        $this->db->or_like('p.email',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_pharmacies_count($search){
    $this->db->select('p.*')->from('pharmacies p');
    $this->db->where(['p.delete_status' => 1]);

    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('p.name',$search);
        $this->db->or_like('p.mobile',$search);
        $this->db->or_like('p.email',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*pharmacies*/

/*diagnostics*/
public function get_main_diagnostics($limit,$start,$search){
    $this->db->select('d.*')->from('diagnostics d');
    $this->db->where(['d.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('d.name',$search);
        $this->db->or_like('d.mobile',$search);
        $this->db->or_like('d.email',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_main_diagnostics_count($search){
    $this->db->select('d.*')->from('diagnostics d');
    $this->db->where(['d.delete_status' => 1]);

    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('d.name',$search);
        $this->db->or_like('d.mobile',$search);
        $this->db->or_like('d.email',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_main_diagnostic_packages($sess_data,$limit,$start,$search){
    $this->db->select('hdp.*')->from('diagnostic_packages hdp');
    $this->db->where(['hdp.main_data_id' => $sess_data,'hdp.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hdp.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_main_diagnostic_packages_count($sess_data,$search){
    $this->db->select('hdp.*')->from('diagnostic_packages hdp');
    $this->db->where(['hdp.main_data_id' => $sess_data,'hdp.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hdp.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_tests_by_main_diagnostic_id($id){
    // Get all main tests for the diagnostic
    $tests = $this->db->get_where('diagnostic_tests', [
        'package_id' => base64_decode($id),
        'status' => 1,
        'delete_status' => 1
    ])->result_array();

    foreach ($tests as &$test) {
        // Fetch full sub-test rows instead of just names
        $test['sub_tests'] = $this->db->get_where('diagnostic_sub_tests', [
            'test_id' => $test['id'],
            'status' => 1,
            'delete_status' => 1
        ])->result_array();
    }

    return $tests;
}
/*diagnostics*/

/*lab_tests*/
public function get_lab_tests($limit,$start,$search){
    $this->db->select('d.*')->from('lab_tests d');
    $this->db->where(['d.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('d.name',$search);
        $this->db->or_like('d.mobile',$search);
        $this->db->or_like('d.email',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_lab_tests_count($search){
    $this->db->select('d.*')->from('lab_tests d');
    $this->db->where(['d.delete_status' => 1]);

    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('d.name',$search);
        $this->db->or_like('d.mobile',$search);
        $this->db->or_like('d.email',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_lab_agents($sess_data,$limit,$start,$search){
    $this->db->where(['main_data_id' => $sess_data,'delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->or_like('mobile',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get('lab_agents');
    return $query->result_array();
}
public function get_lab_agents_count($sess_data,$search){
    $this->db->where(['main_data_id' => $sess_data,'delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('name',$search);
        $this->db->or_like('mobile',$search);
        $this->db->group_end();
    }
    $query = $this->db->get('lab_agents');
    return $query->num_rows();
}
public function get_lab_test_packages($sess_data,$limit,$start,$search){
    $this->db->select('hdp.*')->from('lab_packages hdp');
    $this->db->where(['hdp.main_data_id' => $sess_data,'hdp.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hdp.name',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_lab_test_packages_count($sess_data,$search){
    $this->db->select('hdp.*')->from('lab_packages hdp');
    $this->db->where(['hdp.main_data_id' => $sess_data,'hdp.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('hdp.name',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
public function get_tests_by_main_lab_id($id){
    // Get all main tests for the diagnostic
    $tests = $this->db->get_where('lab_package_tests', [
        'package_id' => base64_decode($id),
        'status' => 1,
        'delete_status' => 1
    ])->result_array();

    foreach ($tests as &$test) {
        // Fetch full sub-test rows instead of just names
        $test['sub_tests'] = $this->db->get_where('lab_sub_tests', [
            'test_id' => $test['id'],
            'status' => 1,
            'delete_status' => 1
        ])->result_array();
    }

    return $tests;
}
/*lab_tests*/

/*online_doctors*/
public function get_online_doctors($limit, $start, $search){
    $this->db->select('online_doctors.*, online_doctor_specialities.name AS speciality, GROUP_CONCAT(DISTINCT md.name ORDER BY md.name SEPARATOR ", ") AS qualification');
    $this->db->from('online_doctors');
    
    // JOINs
    $this->db->join('online_doctor_specialities', 'online_doctor_specialities.id = online_doctors.speciality_id', 'left');
    $this->db->join('medical_degrees md', 'FIND_IN_SET(md.id, online_doctors.qualification)', 'left');
    
    // WHERE conditions
    $this->db->where([
        'online_doctors.delete_status' => 1
    ]);
    
    // Search filters
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('online_doctors.name', $search);
        $this->db->or_like('online_doctor_specialities.name', $search);
        $this->db->or_like('online_doctors.mobile',$search);
        //$this->db->or_like('online_doctors.consult_type', $search);
        $this->db->group_end();
    }

    // GROUP BY required due to GROUP_CONCAT
    $this->db->group_by('online_doctors.id');

    // Pagination
    $this->db->limit($limit, $start);

    // Execute query
    $query = $this->db->get();
    return $query->result_array();
}
public function get_online_doctors_count($search){
    $this->db->select('online_doctors.*,online_doctor_specialities.name as speciality')->from('online_doctors');
    $this->db->where(['online_doctors.delete_status' => 1]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('online_doctors.name',$search);
        $this->db->or_like('online_doctor_specialities.name',$search);
        $this->db->or_like('online_doctors.mobile',$search);
        //$this->db->or_like('online_doctors.consult_type',$search);
        $this->db->group_end();
    }
    $this->db->join('online_doctor_specialities','online_doctor_specialities.id=online_doctors.speciality_id','left');
    $query = $this->db->get();
    return $query->num_rows();
}
/*online_doctors*/

/*ambulance_bookings*/
public function get_ongoing_ambulance_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.user_id, b.main_data_id, b.date, b.mobile,b.name,b.address_id,b.booking_status,b.trip_status,b.ambulance_driver_id,b.accept_status,b.created_on,u.hno,u.address,u.building_no,u.pincode,u.state,u.landmark,u.address_type,u.default_address,u.lat,u.lon,IFNULL(a.name, "") AS ambulance_driver_name,us.image,md.name as hospital_name');

    $this->db->from('ambulance_bookings b');
    
    $this->db->where('b.booking_status', 'booked');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('b.name',$search);
        $this->db->or_like('a.name',$search);
        $this->db->group_end();
    }
    
    // accept_status = 'accepted' OR ''
    $this->db->group_start();
    $this->db->where('b.accept_status', 'accepted');
    $this->db->or_where('b.accept_status', '');
    $this->db->group_end();
    
    $this->db->join('user_addresses u','u.id=b.address_id','left');
    $this->db->join('ambulance_drivers a','a.id=b.ambulance_driver_id','left');
    $this->db->join('users us','us.id=b.user_id','left');
    $this->db->join('main_data md','md.id=b.main_data_id','left');
    // Avoid duplicates in case of joins
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    // Format and return result
    return array_map(function ($row) {
        return [
            'id'                    => intval($row['id']),
            'booking_id'            => $row['booking_id'],
            'user_id'               => intval($row['user_id']),
            'main_data_id'          => intval($row['main_data_id']),
            'date'                  => date('d-m-Y', strtotime($row['date'])),
            'mobile'                => intval($row['mobile']),
            'name'                  => $row['name'],
            'ambulance_driver_name' => $row['ambulance_driver_name'],
            'accept_status'         => $row['accept_status'],
            'trip_status'           => $row['trip_status'],
            'ambulance_driver_id'   => intval($row['ambulance_driver_id']),
            'address_id'            => intval($row['address_id']),
            'hno'                   => $row['hno'],
            'address'               => $row['address'],
            'building_no'           => $row['building_no'],
            'pincode'               => intval($row['pincode']),
            'state'                 => $row['state'],
            'landmark'              => $row['landmark'],
            'address_type'          => $row['address_type'],
            'default_address'       => intval($row['default_address']),
            'booking_status'        => $row['booking_status'],
            'lat'                   => $row['lat'],
            'lon'                   => $row['lon'],
            'image'                 => $row['image'],
            'created_on'            => $row['created_on'],
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_ongoing_ambulance_bookings_count($search){
    $this->db->select('COUNT(DISTINCT b.id) AS total');
    $this->db->from('ambulance_bookings b');
    
    $this->db->where('b.booking_status', 'booked');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('b.name', $search);
        $this->db->or_like('a.name', $search);
        $this->db->group_end();
    }

    $this->db->group_start();
    $this->db->where('b.accept_status', 'accepted');
    $this->db->or_where('b.accept_status', '');
    $this->db->group_end();

    $this->db->join('user_addresses u', 'u.id = b.address_id', 'left');
    $this->db->join('ambulance_drivers a', 'a.id = b.ambulance_driver_id', 'left');
    $this->db->join('users us', 'us.id = b.user_id', 'left');
    $this->db->join('main_data md','md.id=b.main_data_id','left');
    $query = $this->db->get();
    $row = $query->row_array();
    return isset($row['total']) ? intval($row['total']) : 0;
}
public function get_completed_ambulance_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.user_id, b.main_data_id, b.date, b.mobile,b.name,b.address_id,b.booking_status,b.trip_status,b.ambulance_driver_id,b.accept_status,b.created_on,u.hno,u.address,u.building_no,u.pincode,u.state,u.landmark,u.address_type,u.default_address,u.lat,u.lon,IFNULL(a.name, "") AS ambulance_driver_name,us.image,md.name as hospital_name');

    $this->db->from('ambulance_bookings b');
    
    $this->db->where('b.booking_status', 'completed');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('b.name',$search);
        $this->db->or_like('a.name',$search);
        $this->db->group_end();
    }
    
    // accept_status = 'accepted' OR ''
    $this->db->group_start();
    $this->db->where('b.accept_status', 'accepted');
    $this->db->or_where('b.accept_status', '');
    $this->db->group_end();
    
    $this->db->join('user_addresses u','u.id=b.address_id','left');
    $this->db->join('ambulance_drivers a','a.id=b.ambulance_driver_id','left');
    $this->db->join('users us','us.id=b.user_id','left');
    $this->db->join('main_data md','md.id=b.main_data_id','left');
    // Avoid duplicates in case of joins
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    // Format and return result
    return array_map(function ($row) {
        return [
            'id'                    => intval($row['id']),
            'booking_id'            => $row['booking_id'],
            'user_id'               => intval($row['user_id']),
            'main_data_id'          => intval($row['main_data_id']),
            'date'                  => date('d-m-Y', strtotime($row['date'])),
            'mobile'                => intval($row['mobile']),
            'name'                  => $row['name'],
            'ambulance_driver_name' => $row['ambulance_driver_name'],
            'accept_status'         => $row['accept_status'],
            'trip_status'           => $row['trip_status'],
            'ambulance_driver_id'   => intval($row['ambulance_driver_id']),
            'address_id'            => intval($row['address_id']),
            'hno'                   => $row['hno'],
            'address'               => $row['address'],
            'building_no'           => $row['building_no'],
            'pincode'               => intval($row['pincode']),
            'state'                 => $row['state'],
            'landmark'              => $row['landmark'],
            'address_type'          => $row['address_type'],
            'default_address'       => intval($row['default_address']),
            'booking_status'        => $row['booking_status'],
            'lat'                   => $row['lat'],
            'lon'                   => $row['lon'],
            'image'                 => $row['image'],
            'created_on'            => $row['created_on'],
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_completed_ambulance_bookings_count($search){
    $this->db->select('b.id');

    $this->db->from('ambulance_bookings b');
    
    $this->db->where('b.booking_status', 'completed');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('b.name', $search);
        $this->db->or_like('a.name', $search);
        $this->db->group_end();
    }

    $this->db->group_start();
    $this->db->where('b.accept_status', 'accepted');
    $this->db->or_where('b.accept_status', '');
    $this->db->group_end();

    $this->db->join('user_addresses u', 'u.id=b.address_id', 'left');
    $this->db->join('ambulance_drivers a', 'a.id=b.ambulance_driver_id', 'left');
    $this->db->join('users us', 'us.id=b.user_id', 'left');
    $this->db->join('main_data md','md.id=b.main_data_id','left');
    // Get result and count rows manually
    $query = $this->db->get();
    return $query->num_rows();
}
/*ambulance_bookings*/

/*admit_bookings*/
public function get_ongoing_admit_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.user_id, b.main_data_id,b.pr_id, b.date,b.time,b.booking_status,b.created_on,fm.mobile,fm.name,fm.image,fm.email,fm.dob,IFNULL(pr.name, "") AS pr_name,IFNULL(pr.image, "") AS pr_image,pr.mobile as pr_mobile,md.name as hospital_name');

    $this->db->from('admit_bookings b');
    $this->db->where('b.booking_status', 'booked');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('md.name',$search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('fm.name',$search);
        $this->db->or_like('pr.name',$search);
        $this->db->group_end();
    }
    
    $this->db->join('family_members fm','fm.id=b.family_member_id','left');
    
    $this->db->join('pr_agents pr','pr.id=b.pr_id','left');
    $this->db->join('main_data md','md.id=b.main_data_id','left');
    
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    // Format and return result
    return array_map(function ($row) {
        return [
            'id'                    => intval($row['id']),
            'booking_id'            => $row['booking_id'],
            'user_id'               => intval($row['user_id']),
            'main_data_id'          => intval($row['main_data_id']),
            'pr_id'                 => intval($row['pr_id']),
            //'slot_id'               => intval($row['slot_id']),
            'date'                  => date('d-m-Y', strtotime($row['date'])),
            'time'                  => $row['time'],
            'mobile'                => intval($row['mobile']),
            'name'                  => $row['name'],
            'image'                 => $row['image'],
            'email'                 => $row['email'],
            'dob'                   => $row['dob'],
            'pr_name'               => $row['pr_name'],
            'pr_image'              => $row['pr_image'],
            'pr_mobile'             => intval($row['pr_mobile']),
            'booking_status'        => $row['booking_status'],
            'created_on'            => $row['created_on'],
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_ongoing_admit_bookings_count($search){
    $this->db->select('b.id, b.booking_id, b.user_id, b.main_data_id,b.pr_id, b.date,b.time,b.booking_status,b.created_on,fm.mobile,fm.name,fm.image,fm.email,fm.dob,IFNULL(pr.name, "") AS pr_name,IFNULL(pr.image, "") AS pr_image,pr.mobile as pr_mobile,md.name as hospital_name');
    
    // ✅ Add this line
    $this->db->from('admit_bookings b');

    $this->db->where('b.booking_status', 'booked');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('fm.name', $search);
        $this->db->or_like('pr.name', $search);
        $this->db->group_end();
    }

    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('pr_agents pr', 'pr.id = b.pr_id', 'left');
    $this->db->join('main_data md', 'md.id = b.main_data_id', 'left');

    return $this->db->count_all_results();
}
public function get_completed_admit_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.user_id, b.main_data_id,b.pr_id, b.date,IFNULL(b.completed_date, "") AS completed_date,b.time,b.booking_status,b.created_on,fm.mobile,fm.name,fm.image,fm.email,fm.dob,IFNULL(pr.name, "") AS pr_name,IFNULL(pr.image, "") AS pr_image,pr.mobile as pr_mobile,md.name as hospital_name');

    $this->db->from('admit_bookings b');

    $this->db->where('b.booking_status', 'completed');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('md.name',$search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('fm.name',$search);
        $this->db->or_like('pr.name',$search);
        $this->db->group_end();
    }
    
    $this->db->join('family_members fm','fm.id=b.family_member_id','left');
    
    $this->db->join('pr_agents pr','pr.id=b.pr_id','left');
    
    $this->db->join('main_data md','md.id=b.main_data_id','left');
    
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    // Format and return result
    return array_map(function ($row) {
        return [
            'id'                    => intval($row['id']),
            'booking_id'            => $row['booking_id'],
            'user_id'               => intval($row['user_id']),
            'main_data_id'          => intval($row['main_data_id']),
            'pr_id'                 => intval($row['pr_id']),
            //'slot_id'             => intval($row['slot_id']),
            'date'                  => date('d-m-Y', strtotime($row['date'])),
            'completed_date'        => !empty($row['completed_date']) ? date('d-m-Y', strtotime($row['completed_date'])) : 'N/A',
            'time'                  => $row['time'],
            'mobile'                => intval($row['mobile']),
            'name'                  => $row['name'],
            'image'                 => $row['image'],
            'email'                 => $row['email'],
            'dob'                   => $row['dob'],
            'pr_name'               => $row['pr_name'],
            'pr_image'              => $row['pr_image'],
            'pr_mobile'             => intval($row['pr_mobile']),
            'booking_status'        => $row['booking_status'],
            'created_on'            => $row['created_on'],
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_completed_admit_bookings_count($search) {
    $this->db->select('b.id, b.booking_id, b.user_id, b.main_data_id, b.pr_id, b.date, 
                       IFNULL(b.completed_date, "") AS completed_date, 
                       b.time, b.booking_status, b.created_on,
                       fm.mobile, fm.name, fm.image, fm.email, fm.dob,
                       IFNULL(pr.name, "") AS pr_name, IFNULL(pr.image, "") AS pr_image, pr.mobile as pr_mobile,
                       md.name as hospital_name');

    $this->db->from('admit_bookings b');

    // ✅ Add the missing status filter
    $this->db->where('b.booking_status', 'completed');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('fm.name', $search);
        $this->db->or_like('pr.name', $search);
        $this->db->group_end();
    }

    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('pr_agents pr', 'pr.id = b.pr_id', 'left');
    $this->db->join('main_data md', 'md.id = b.main_data_id', 'left');

    return $this->db->count_all_results();
}
public function get_completed_admit_reports($booking_id,$limit,$start,$search){
    $this->db->select('ar.*')->from('admit_booking_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_completed_admit_reports_count($booking_id,$search){
    $this->db->select('ar.*')->from('admit_booking_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*admit_bookings*/

/*op_bookings*/
public function get_ongoing_op_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.consult_type, b.user_id, b.speciality_id, b.booking_status, b.doctor_id, b.slot_id, b.time, b.date, b.mobile,b.call_status, b.family_member_id, b.fee, b.consultation_fee, b.coupon_id, b.coupon_name, b.coupon_percentage, b.coupon_discount, b.payment_type,b.transaction_id, b.created_on, fm.name as patient_name, s.name AS speciality_name, d.name AS doctor_name, d.image as doctor_image, d.mobile as doctor_mobile, d.exp as doctor_exp,GROUP_CONCAT(DISTINCT md.name ORDER BY md.name SEPARATOR ", ") AS qualification,fm.email, fm.gender, fm.dob, fm.image,bg.name as blood_group,mda.name as hospital_name');

    $this->db->from('doctor_bookings b');
    $this->db->join('specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('medical_degrees md', 'FIND_IN_SET(md.id, d.qualification)', 'left');
    $this->db->join('main_data mda','mda.id=b.main_data_id','left');
    // Filter active bookings for the doctor
    
    $this->db->where('b.booking_status', 'booked');
    $this->db->where('b.consult_type', 'offline');
    
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('mda.name', $search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('fm.name',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    // Format and return result
    return array_map(function ($row) {
        return [
            'id'                => intval($row['id']),
            'booking_id'        => $row['booking_id'],
            'consult_type'      => $row['consult_type'],
            'user_id'           => intval($row['user_id']),
            'speciality_id'     => intval($row['speciality_id']),
            'doctor_id'         => intval($row['doctor_id']),
            'slot_id'           => intval($row['slot_id']),
            'time'              => $row['time'],
            'booking_status'    => $row['booking_status'],
            'date'              => date('d-m-Y', strtotime($row['date'])),
            'mobile'            => intval($row['mobile']),
            'call_status'       => intval($row['call_status']),
            'family_member_id'  => intval($row['family_member_id']),
            'fee'               => intval($row['fee']),
            'consultation_fee'  => intval($row['consultation_fee']),
            'coupon_id'         => intval($row['coupon_id']),
            'coupon_name'       => $row['coupon_name'],
            'coupon_percentage' => intval($row['coupon_percentage']),
            'coupon_discount'   => intval($row['coupon_discount']),
            'payment_type'      => $row['payment_type'],
            'transaction_id'    => $row['transaction_id'],
            'created_on'        => $row['created_on'],
            'speciality_name'   => $row['speciality_name'],
            'name'              => $row['doctor_name'],
            'doctor_image'      => $row['doctor_image'],
            'doctor_mobile'     => $row['doctor_mobile'],
            'doctor_exp'        => $row['doctor_exp'],
            'qualification'     => $row['qualification'],
            'image'             => $row['image'],
            'patient_name'      => $row['patient_name'],
            'email'             => $row['email'],
            'gender'            => $row['gender'],
            'dob'               => $row['dob'],
            'blood_group'       => $row['blood_group'],
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_ongoing_op_bookings_count($search) {
    $this->db->from('doctor_bookings b');
    $this->db->where('b.booking_status', 'booked');
    $this->db->where('b.consult_type', 'offline');

    $this->db->join('specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('main_data mda', 'mda.id = b.main_data_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('mda.name', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('fm.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_completed_op_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.consult_type, b.user_id, b.speciality_id, b.booking_status, b.doctor_id, b.slot_id, b.time, b.date, b.mobile,b.call_status, b.family_member_id, b.fee, b.consultation_fee, b.coupon_id, b.coupon_name, b.coupon_percentage, b.coupon_discount, b.payment_type,b.transaction_id, b.created_on, fm.name as patient_name, s.name AS speciality_name, d.name AS doctor_name, d.image as doctor_image, d.mobile as doctor_mobile, d.exp as doctor_exp,GROUP_CONCAT(DISTINCT md.name ORDER BY md.name SEPARATOR ", ") AS qualification,fm.email, fm.gender, fm.dob, fm.image,bg.name as blood_group,mda.name as hospital_name');

    $this->db->from('doctor_bookings b');
    $this->db->join('specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('medical_degrees md', 'FIND_IN_SET(md.id, d.qualification)', 'left');
    $this->db->join('main_data mda','mda.id=b.main_data_id','left');
    // Filter active bookings for the doctor
    
    $this->db->where('b.booking_status', 'completed');
    $this->db->where('b.consult_type', 'offline');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('mda.name', $search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('fm.name',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();
    
    $final_result = [];

    foreach ($result as $row) {
        $booking_id = $row['booking_id'];

        // Fetch medicines
        $medicines = $this->db
        ->select('medicine, medicine_time')
        ->get_where('doctor_booking_medicines', ['booking_id' => $booking_id])
        ->result_array();

        
        // Fetch tests
        $tests = $this->db
        ->select('test, test_instruction')
        ->get_where('doctor_booking_tests', ['booking_id' => $booking_id])
        ->result_array();
        
        // Fetch notes
        
        $notes = $this->db
            ->select('notes')
            ->get_where('doctor_booking_notes', ['booking_id' => $booking_id])
            ->result_array();
        
        // Extract just the 'notes' values into a simple array
        $note_values = array_column($notes, 'notes');
        
        // Assign directly to your output array
        $data = $note_values;
        
        $final_result[] = [
            'id'                => intval($row['id']),
            'booking_id'        => $row['booking_id'],
            'consult_type'      => $row['consult_type'],
            'user_id'           => intval($row['user_id']),
            'speciality_id'     => intval($row['speciality_id']),
            'doctor_id'         => intval($row['doctor_id']),
            'slot_id'           => intval($row['slot_id']),
            'time'              => $row['time'],
            'booking_status'    => $row['booking_status'],
            'date'              => date('d-m-Y', strtotime($row['date'])),
            'mobile'            => intval($row['mobile']),
            'call_status'       => intval($row['call_status']),
            'family_member_id'  => intval($row['family_member_id']),
            'fee'               => intval($row['fee']),
            'consultation_fee'  => intval($row['consultation_fee']),
            'coupon_id'         => intval($row['coupon_id']),
            'coupon_name'       => $row['coupon_name'],
            'coupon_percentage' => intval($row['coupon_percentage']),
            'coupon_discount'   => intval($row['coupon_discount']),
            'payment_type'      => $row['payment_type'],
            'transaction_id'    => $row['transaction_id'],
            'created_on'        => $row['created_on'],
            'speciality_name'   => $row['speciality_name'],
            'name'              => $row['doctor_name'],
            'doctor_image'      => $row['doctor_image'],
            'doctor_mobile'     => $row['doctor_mobile'],
            'doctor_exp'        => $row['doctor_exp'],
            'qualification'     => $row['qualification'],
            'image'             => $row['image'],
            'patient_name'      => $row['patient_name'],
            'email'             => $row['email'],
            'gender'            => $row['gender'],
            'dob'               => $row['dob'],
            'blood_group'       => $row['blood_group'],
            'medicines'         => !empty($medicines) ? $medicines : [],
            'tests'             => !empty($tests) ? $tests : [],
            'notes'             => !empty($notes) ? $notes : [],
            'hospital_name'         => $row['hospital_name']
        ];
    }
    return $final_result;
}
public function get_completed_op_bookings_count($search) {
    $this->db->from('doctor_bookings b');
    $this->db->where('b.booking_status', 'completed');
    $this->db->where('b.consult_type', 'offline');

    $this->db->join('specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('main_data mda', 'mda.id = b.main_data_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('mda.name', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('fm.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*op_bookings*/

/*doctor_bookings*/
public function get_ongoing_doctor_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.consult_type, b.user_id, b.speciality_id, b.booking_status, b.doctor_id, b.slot_id, b.time, b.date, b.mobile,b.call_status, b.family_member_id, b.fee, b.consultation_fee, b.coupon_id, b.coupon_name, b.coupon_percentage, b.coupon_discount, b.payment_type,b.transaction_id, b.created_on, fm.name as patient_name, s.name AS speciality_name, d.name AS doctor_name, d.image as doctor_image, d.mobile as doctor_mobile, d.exp as doctor_exp,GROUP_CONCAT(DISTINCT md.name ORDER BY md.name SEPARATOR ", ") AS qualification,fm.email, fm.gender, fm.dob, fm.image,bg.name as blood_group,mda.name as hospital_name');

    $this->db->from('doctor_bookings b');
    $this->db->join('specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('medical_degrees md', 'FIND_IN_SET(md.id, d.qualification)', 'left');
    $this->db->join('main_data mda','mda.id=b.main_data_id','left');
    // Filter active bookings for the doctor
    
    $this->db->where('b.booking_status', 'booked');
    $this->db->where('b.consult_type', 'online');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('mda.name', $search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('fm.name',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    // Format and return result
    return array_map(function ($row) {
        return [
            'id'                => intval($row['id']),
            'booking_id'        => $row['booking_id'],
            'consult_type'      => $row['consult_type'],
            'user_id'           => intval($row['user_id']),
            'speciality_id'     => intval($row['speciality_id']),
            'doctor_id'         => intval($row['doctor_id']),
            'slot_id'           => intval($row['slot_id']),
            'time'              => $row['time'],
            'booking_status'    => $row['booking_status'],
            'date'              => date('d-m-Y', strtotime($row['date'])),
            'mobile'            => intval($row['mobile']),
            'call_status'       => intval($row['call_status']),
            'family_member_id'  => intval($row['family_member_id']),
            'fee'               => intval($row['fee']),
            'consultation_fee'  => intval($row['consultation_fee']),
            'coupon_id'         => intval($row['coupon_id']),
            'coupon_name'       => $row['coupon_name'],
            'coupon_percentage' => intval($row['coupon_percentage']),
            'coupon_discount'   => intval($row['coupon_discount']),
            'payment_type'      => $row['payment_type'],
            'transaction_id'    => $row['transaction_id'],
            'created_on'        => $row['created_on'],
            'speciality_name'   => $row['speciality_name'],
            'name'              => $row['doctor_name'],
            'doctor_image'      => $row['doctor_image'],
            'doctor_mobile'     => $row['doctor_mobile'],
            'doctor_exp'        => $row['doctor_exp'],
            'qualification'     => $row['qualification'],
            'image'             => $row['image'],
            'patient_name'      => $row['patient_name'],
            'email'             => $row['email'],
            'gender'            => $row['gender'],
            'dob'               => $row['dob'],
            'blood_group'       => $row['blood_group'],
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_ongoing_doctor_bookings_count($search){
    $this->db->from('doctor_bookings b');
    $this->db->where('b.booking_status', 'booked');
    $this->db->where('b.consult_type', 'online');

    // JOINs for search support
    $this->db->join('specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('main_data mda', 'mda.id = b.main_data_id', 'left');

    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('mda.name', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('fm.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_completed_doctor_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.consult_type, b.user_id, b.speciality_id, b.booking_status, b.doctor_id, b.slot_id, b.time, b.date, b.mobile,b.call_status, b.family_member_id, b.fee, b.consultation_fee, b.coupon_id, b.coupon_name, b.coupon_percentage, b.coupon_discount, b.payment_type,b.transaction_id, b.created_on, fm.name as patient_name, s.name AS speciality_name, d.name AS doctor_name, d.image as doctor_image, d.mobile as doctor_mobile, d.exp as doctor_exp,GROUP_CONCAT(DISTINCT md.name ORDER BY md.name SEPARATOR ", ") AS qualification,fm.email, fm.gender, fm.dob, fm.image,bg.name as blood_group,mda.name as hospital_name');

    $this->db->from('doctor_bookings b');
    $this->db->join('specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('medical_degrees md', 'FIND_IN_SET(md.id, d.qualification)', 'left');
    $this->db->join('main_data mda','mda.id=b.main_data_id','left');
    // Filter active bookings for the doctor
    
    $this->db->where('b.booking_status', 'completed');
    $this->db->where('b.consult_type', 'online');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('mda.name', $search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('fm.name',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();
    
    $final_result = [];

    foreach ($result as $row) {
        $booking_id = $row['booking_id'];

        // Fetch medicines
        $medicines = $this->db
        ->select('medicine, medicine_time')
        ->get_where('doctor_booking_medicines', ['booking_id' => $booking_id])
        ->result_array();

        
        // Fetch tests
        $tests = $this->db
        ->select('test, test_instruction')
        ->get_where('doctor_booking_tests', ['booking_id' => $booking_id])
        ->result_array();
        
        // Fetch notes
        
        $notes = $this->db
            ->select('notes')
            ->get_where('doctor_booking_notes', ['booking_id' => $booking_id])
            ->result_array();
        
        // Extract just the 'notes' values into a simple array
        $note_values = array_column($notes, 'notes');
        
        // Assign directly to your output array
        $data = $note_values;
        
        $final_result[] = [
            'id'                => intval($row['id']),
            'booking_id'        => $row['booking_id'],
            'consult_type'      => $row['consult_type'],
            'user_id'           => intval($row['user_id']),
            'speciality_id'     => intval($row['speciality_id']),
            'doctor_id'         => intval($row['doctor_id']),
            'slot_id'           => intval($row['slot_id']),
            'time'              => $row['time'],
            'booking_status'    => $row['booking_status'],
            'date'              => date('d-m-Y', strtotime($row['date'])),
            'mobile'            => intval($row['mobile']),
            'call_status'       => intval($row['call_status']),
            'family_member_id'  => intval($row['family_member_id']),
            'fee'               => intval($row['fee']),
            'consultation_fee'  => intval($row['consultation_fee']),
            'coupon_id'         => intval($row['coupon_id']),
            'coupon_name'       => $row['coupon_name'],
            'coupon_percentage' => intval($row['coupon_percentage']),
            'coupon_discount'   => intval($row['coupon_discount']),
            'payment_type'      => $row['payment_type'],
            'transaction_id'    => $row['transaction_id'],
            'created_on'        => $row['created_on'],
            'speciality_name'   => $row['speciality_name'],
            'name'              => $row['doctor_name'],
            'doctor_image'      => $row['doctor_image'],
            'doctor_mobile'     => $row['doctor_mobile'],
            'doctor_exp'        => $row['doctor_exp'],
            'qualification'     => $row['qualification'],
            'image'             => $row['image'],
            'patient_name'      => $row['patient_name'],
            'email'             => $row['email'],
            'gender'            => $row['gender'],
            'dob'               => $row['dob'],
            'blood_group'       => $row['blood_group'],
            'medicines'         => !empty($medicines) ? $medicines : [],
            'tests'             => !empty($tests) ? $tests : [],
            'notes'             => !empty($notes) ? $notes : [],
            'hospital_name'         => $row['hospital_name']
        ];
    }
    return $final_result;
}
public function get_completed_doctor_bookings_count($search){
    $this->db->from('doctor_bookings b');
    $this->db->where('b.booking_status', 'completed');
    $this->db->where('b.consult_type', 'online');

    // JOINs for extended search/filtering
    $this->db->join('specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('main_data mda', 'mda.id = b.main_data_id', 'left');

    // Optional search
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('mda.name', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('fm.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*doctor_bookings*/

/*pharmacy_prescription_bookings*/
public function get_ongoing_pharmacy_prescription_bookings($limit, $start, $search){
    $this->db->select('
        pb.id,
        pb.booking_id,
        pb.created_on,
        pb.order_type,
        pb.user_id,
        pb.main_data_id,
        pb.address_id,
        pb.mobile,
        pb.name,
        pb.image,
        pb.booking_status,
        pb.booking_type,
        pb.accept_status,
        u.image AS user_image,
        a.hno,a.address, a.building_no, a.pincode, a.state,a.landmark,a.address_type,a.default_address,a.lat,a.lon,md.name as hospital_name
    ');

    $this->db->from('hospital_pharmacy_medicine_orders pb');
    $this->db->join('users u', 'u.id = pb.user_id', 'left');
    // Join address table only where pb.address_id != 0
    $this->db->join('user_addresses a', 'a.id = pb.address_id AND pb.address_id != 0', 'left');
    $this->db->join('main_data md', 'md.id = pb.main_data_id', 'left');
    

    $this->db->group_start();
    $this->db->where('pb.accept_status', 'accepted');
    $this->db->or_where('pb.accept_status', '');
    $this->db->group_end();

    $this->db->group_start();
    $this->db->where('pb.booking_status', 'booked');
    $this->db->or_where('pb.booking_status', 'pickedup');
    $this->db->group_end();

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('pb.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('pb.mobile', $search);
        $this->db->or_like('pb.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('pb.created_on', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $raw = $query->result();

    $result = [];
    foreach ($raw as $row) {
        $id = $row->booking_id;
        if (!isset($result[$id])) {
            $result[$id] = [
                'id'                => (int)$row->id,
                'booking_id'        => $row->booking_id,
                'created_on'        => $row->created_on,
                'order_type'        => $row->order_type,
                'user_id'           => (int)$row->user_id,
                'main_data_id'      => (int)$row->main_data_id,
                'address_id'        => (int)$row->address_id,
                'name'              => $row->name,
                'mobile'            => $row->mobile,
                'image'             => $row->image,
                'user_image'        => $row->user_image,
                'booking_type'      => $row->booking_type,
                'booking_status'    => $row->booking_status,
                'accept_status'     => $row->accept_status,
                'hno'               => $row->hno,
                'address'           => $row->address,
                'building_no'       => $row->building_no,
                'pincode'           => intval($row->pincode),
                'state'             => $row->state,
                'landmark'          => $row->landmark,
                'address_type'      => $row->address_type,
                'default_address'   => intval($row->default_address),
                'lat'               => $row->lat,
                'lon'               => $row->lon,
                'hospital_name'     => $row->hospital_name
            ];
        }
    }

    return array_values($result);
}
public function get_ongoing_pharmacy_prescription_bookings_count($search) {
    $this->db->from('hospital_pharmacy_medicine_orders pb');
    $this->db->join('users u', 'u.id = pb.user_id', 'left');
    $this->db->join('user_addresses a', 'a.id = pb.address_id AND pb.address_id != 0', 'left');
    $this->db->join('main_data md', 'md.id = pb.main_data_id', 'left');

    // Accept Status Filter
    $this->db->group_start();
    $this->db->where('pb.accept_status', 'accepted');
    $this->db->or_where('pb.accept_status', '');
    $this->db->group_end();

    // Booking Status Filter
    $this->db->group_start();
    $this->db->where('pb.booking_status', 'booked');
    $this->db->or_where('pb.booking_status', 'pickedup');
    $this->db->group_end();

    // Search Filter
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('pb.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('pb.mobile', $search);
        $this->db->or_like('pb.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_completed_pharmacy_prescription_bookings($limit, $start, $search){
    $this->db->select('
        pb.id,
        pb.booking_id,
        pb.created_on,
        pb.order_type,
        pb.user_id,
        pb.main_data_id,
        pb.address_id,
        pb.mobile,
        pb.name,
        pb.image,
        pb.booking_status,
        pb.booking_type,
        pb.accept_status,
        u.image AS user_image,
        a.hno,a.address, a.building_no, a.pincode, a.state,a.landmark,a.address_type,a.default_address,a.lat,a.lon,md.name as hospital_name
    ');

    $this->db->from('hospital_pharmacy_medicine_orders pb');
    $this->db->join('users u', 'u.id = pb.user_id', 'left');
    // Join address table only where pb.address_id != 0
    $this->db->join('user_addresses a', 'a.id = pb.address_id AND pb.address_id != 0', 'left');
    $this->db->join('main_data md','md.id=pb.main_data_id','left');
    $this->db->where('pb.booking_status', 'completed');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('pb.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('pb.mobile', $search);
        $this->db->or_like('pb.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('pb.created_on', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $raw = $query->result();

    $result = [];
    foreach ($raw as $row) {
        $id = $row->booking_id;
        if (!isset($result[$id])) {
            $result[$id] = [
                'id'                => (int)$row->id,
                'booking_id'        => $row->booking_id,
                'created_on'        => $row->created_on,
                'order_type'        => $row->order_type,
                'user_id'           => (int)$row->user_id,
                'main_data_id'      => (int)$row->main_data_id,
                'address_id'        => (int)$row->address_id,
                'name'              => $row->name,
                'mobile'            => $row->mobile,
                'image'             => $row->image,
                'user_image'        => $row->user_image,
                'booking_type'      => $row->booking_type,
                'booking_status'    => $row->booking_status,
                'accept_status'     => $row->accept_status,
                'hno'               => $row->hno,
                'address'           => $row->address,
                'building_no'       => $row->building_no,
                'pincode'           => intval($row->pincode),
                'state'             => $row->state,
                'landmark'          => $row->landmark,
                'address_type'      => $row->address_type,
                'default_address'   => intval($row->default_address),
                'lat'               => $row->lat,
                'lon'               => $row->lon,
                'hospital_name'     => $row->hospital_name
            ];
        }
    }

    return array_values($result);
}
public function get_completed_pharmacy_prescription_bookings_count($search) {
    $this->db->from('hospital_pharmacy_medicine_orders pb');
    $this->db->join('users u', 'u.id = pb.user_id', 'left');
    $this->db->join('user_addresses a', 'a.id = pb.address_id AND pb.address_id != 0', 'left');
    $this->db->join('main_data md','md.id = pb.main_data_id','left');

    $this->db->where('pb.booking_status', 'completed');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('pb.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('pb.mobile', $search);
        $this->db->or_like('pb.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*pharmacy_prescription_bookings*/

/*diagnostic_bookings*/
public function get_ongoing_diagnostic_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.booking_status,
        db.booking_type,
        (SELECT name FROM hospital_diagnostic_booking_packages hdbp WHERE hdbp.booking_id = db.booking_id LIMIT 1) AS name,
        db.count,
        db.image,
        db.mobile,
        db.accept_status,
        db.slot_id,
        db.date,
        db.time,
        db.fee,
        db.consultation_fee,
        db.coupon_id,
        db.coupon_name,
        db.coupon_percentage,
        db.coupon_discount,
        db.payment_type,
        db.transaction_id,
        db.family_member_id,
        d.name as hospital_name,
        (
            (SELECT COUNT(*) FROM hospital_diagnostic_booking_tests hdbt WHERE hdbt.booking_id = db.booking_id) +
            (SELECT COUNT(*) FROM hospital_diagnostic_booking_subtests hdbst WHERE hdbst.booking_id = db.booking_id)
        ) AS total_test_count
    ');
    $this->db->from('hospital_diagnostic_bookings db');
    $this->db->where('db.booking_status', 'booked');
    
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    $this->db->join('main_data d', 'd.id=db.main_data_id', 'left');

    $today = date('Y-m-d');
    $this->db->order_by("CASE WHEN db.date = '{$today}' THEN 0 ELSE 1 END", "ASC");
    $this->db->order_by('db.date', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        $CI->db->select("
            p.id AS package_id, p.name AS package_name,
            t.id AS test_id, t.name AS test_name,
            st.id AS sub_test_id, st.name AS sub_test_name
        ");
        $CI->db->from('hospital_diagnostic_booking_packages p');
        $CI->db->join('hospital_diagnostic_booking_tests t', 't.booking_package_id = p.id AND t.booking_id = p.booking_id', 'left');
        $CI->db->join('hospital_diagnostic_booking_subtests st', 'st.booking_test_id = t.id AND st.booking_id = t.booking_id', 'left');
        $CI->db->where('p.booking_id', $row['booking_id']);
        $test_result = $CI->db->get()->result_array();

        $packages = [];
        foreach ($test_result as $test_row) {
            $pkg_id = (int)$test_row['package_id'];
            if (!isset($packages[$pkg_id])) {
                $packages[$pkg_id] = [
                    'package_name' => $test_row['package_name'],
                    'tests' => []
                ];
            }

            $test_id = (int)$test_row['test_id'];
            if ($test_id && !isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id] = [
                    'test_name' => $test_row['test_name'],
                    'sub_tests' => []
                ];
            }

            $sub_test_id = (int)$test_row['sub_test_id'];
            if ($sub_test_id && isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id]['sub_tests'][] = $test_row['sub_test_name'];
            }
        }

        $formatted_tests = [];
        foreach ($packages as $pkg) {
            foreach ($pkg['tests'] as $test) {
                $formatted_tests[] = [
                    'package_name' => $pkg['package_name'],
                    'test_name' => $test['test_name'],
                    'sub_tests' => $test['sub_tests']
                ];
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'count' => (int)$row['count'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'total_test_count' => (int)$row['total_test_count'],
            'accept_status' => $row['accept_status'],
            'slot_id' => (int)$row['slot_id'],
            'date' => $row['date'],
            'time' => $row['time'],
            'fee' => (int)$row['fee'],
            'consultation_fee' => (int)$row['consultation_fee'],
            'coupon_id' => (int)$row['coupon_id'],
            'coupon_name' => !empty($row['coupon_name']) ? $row['coupon_name'] : 'N/A',
            'coupon_percentage' => (int)$row['coupon_percentage'],
            'coupon_discount' => (int)$row['coupon_discount'],
            'payment_type' => $row['payment_type'],
            'transaction_id' => !empty($row['transaction_id']) ? $row['transaction_id'] : 'N/A',
            'family_members' => $family_members,
            'test_details' => $formatted_tests,
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_ongoing_diagnostic_bookings_count($search) {
    $this->db->from('hospital_diagnostic_bookings db');
    $this->db->join('main_data d', 'd.id = db.main_data_id', 'left');

    // Booking Status = 'booked'
    $this->db->where('db.booking_status', 'booked');

    // Accept Status = 'accepted' or empty
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    // Search filters (if provided)
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_completed_diagnostic_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.booking_status,
        db.booking_type,
        (SELECT name FROM hospital_diagnostic_booking_packages hdbp WHERE hdbp.booking_id = db.booking_id LIMIT 1) AS name,
        db.count,
        db.image,
        db.mobile,
        db.accept_status,
        db.slot_id,
        db.date,
        db.time,
        db.fee,
        db.consultation_fee,
        db.coupon_id,
        db.coupon_name,
        db.coupon_percentage,
        db.coupon_discount,
        db.payment_type,
        db.transaction_id,
        db.family_member_id,
        db.completed_date,
        d.name as hospital_name,
        (
            (SELECT COUNT(*) FROM hospital_diagnostic_booking_tests hdbt WHERE hdbt.booking_id = db.booking_id) +
            (SELECT COUNT(*) FROM hospital_diagnostic_booking_subtests hdbst WHERE hdbst.booking_id = db.booking_id)
        ) AS total_test_count
    ');
    $this->db->from('hospital_diagnostic_bookings db');

    $this->db->where('db.booking_status', 'completed');
    
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    $this->db->join('main_data d', 'd.id=db.main_data_id', 'left');

    $today = date('Y-m-d');
    $this->db->order_by("CASE WHEN db.date = '{$today}' THEN 0 ELSE 1 END", "ASC");
    $this->db->order_by('db.date', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        $CI->db->select("
            p.id AS package_id, p.name AS package_name,
            t.id AS test_id, t.name AS test_name,
            st.id AS sub_test_id, st.name AS sub_test_name
        ");
        $CI->db->from('hospital_diagnostic_booking_packages p');
        $CI->db->join('hospital_diagnostic_booking_tests t', 't.booking_package_id = p.id AND t.booking_id = p.booking_id', 'left');
        $CI->db->join('hospital_diagnostic_booking_subtests st', 'st.booking_test_id = t.id AND st.booking_id = t.booking_id', 'left');
        $CI->db->where('p.booking_id', $row['booking_id']);
        $test_result = $CI->db->get()->result_array();

        $packages = [];
        foreach ($test_result as $test_row) {
            $pkg_id = (int)$test_row['package_id'];
            if (!isset($packages[$pkg_id])) {
                $packages[$pkg_id] = [
                    'package_name' => $test_row['package_name'],
                    'tests' => []
                ];
            }

            $test_id = (int)$test_row['test_id'];
            if ($test_id && !isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id] = [
                    'test_name' => $test_row['test_name'],
                    'sub_tests' => []
                ];
            }

            $sub_test_id = (int)$test_row['sub_test_id'];
            if ($sub_test_id && isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id]['sub_tests'][] = $test_row['sub_test_name'];
            }
        }

        $formatted_tests = [];
        foreach ($packages as $pkg) {
            foreach ($pkg['tests'] as $test) {
                $formatted_tests[] = [
                    'package_name' => $pkg['package_name'],
                    'test_name' => $test['test_name'],
                    'sub_tests' => $test['sub_tests']
                ];
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'count' => (int)$row['count'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'total_test_count' => (int)$row['total_test_count'],
            'accept_status' => $row['accept_status'],
            'slot_id' => (int)$row['slot_id'],
            'date' => $row['date'],
            'time' => $row['time'],
            'fee' => (int)$row['fee'],
            'consultation_fee' => (int)$row['consultation_fee'],
            'coupon_id' => (int)$row['coupon_id'],
            'coupon_name' => !empty($row['coupon_name']) ? $row['coupon_name'] : 'N/A',
            'coupon_percentage' => (int)$row['coupon_percentage'],
            'coupon_discount' => (int)$row['coupon_discount'],
            'payment_type' => $row['payment_type'],
            'transaction_id' => !empty($row['transaction_id']) ? $row['transaction_id'] : 'N/A',
            'family_members' => $family_members,
            'test_details' => $formatted_tests,
            'completed_date'        => !empty($row['completed_date']) ? date('d-m-Y', strtotime($row['completed_date'])) : 'N/A',
            'hospital_name'     => $row['hospital_name']
        ];
    }, $result);
}
public function get_completed_diagnostic_bookings_count($search) {
    $this->db->from('hospital_diagnostic_bookings db');
    $this->db->join('main_data d', 'd.id = db.main_data_id', 'left');

    // Filter: completed bookings only
    $this->db->where('db.booking_status', 'completed');

    // Search filters (if provided)
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_completed_diagnostic_bookings_reports($booking_id,$booking_type,$limit,$start,$search){
    $this->db->select('ar.*')->from('hospital_diagnostic_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_completed_diagnostic_bookings_reports_count($booking_id,$booking_type,$search){
    $this->db->select('ar.*')->from('hospital_diagnostic_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*diagnostic_bookings*/

/*diagnostic_prescription_bookings*/
public function get_ongoing_diagnostic_prescription_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.name,
        db.booking_status,
        db.booking_type,
        db.image,
        db.mobile,
        db.accept_status,
        db.family_member_id,
        d.name as hospital_name
    ');
    $this->db->from('hospital_diagnostic_prescription_bookings db');
    $this->db->where('db.booking_status', 'booked');
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    $this->db->join('main_data d', 'd.id=db.main_data_id', 'left');


    $this->db->order_by('db.created_on', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'accept_status' => $row['accept_status'],
            'family_members' => $family_members,
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_ongoing_diagnostic_prescription_bookings_count($search) {
    $this->db->from('hospital_diagnostic_prescription_bookings db');
    $this->db->join('main_data d', 'd.id=db.main_data_id', 'left');

    $this->db->where('db.booking_status', 'booked');

    // Accept Status Filter
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    // Apply search filters if present
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_completed_diagnostic_prescription_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.name,
        db.booking_status,
        db.booking_type,
        db.image,
        db.mobile,
        db.accept_status,
        db.family_member_id,
        db.completed_date,
        d.name as hospital_name
    ');
    $this->db->from('hospital_diagnostic_prescription_bookings db');
    
    $this->db->where('db.booking_status', 'completed');
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    $this->db->join('main_data d', 'd.id=db.main_data_id', 'left');


    $this->db->order_by('db.created_on', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'accept_status' => $row['accept_status'],
            'family_members' => $family_members,
            'completed_date'        => !empty($row['completed_date']) ? date('d-m-Y', strtotime($row['completed_date'])) : 'N/A',
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_completed_diagnostic_prescription_bookings_count($search){
    $sess_data = $this->session->userdata('main_data_id');

    $this->db->from('hospital_diagnostic_prescription_bookings db');
    $this->db->join('main_data d', 'd.id = db.main_data_id', 'left');

    
    $this->db->where('db.booking_status', 'completed');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_completed_diagnostic_prescription_bookings_reports($sess_data,$booking_id,$booking_type,$limit,$start,$search){
    $this->db->select('ar.*')->from('hospital_diagnostic_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_completed_diagnostic_prescription_bookings_reports_count($sess_data,$booking_id,$booking_type,$search){
    $this->db->select('ar.*')->from('hospital_diagnostic_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*diagnostic_prescription_bookings*/

/*main_pharmacy_prescription_bookings*/
public function get_main_ongoing_pharmacy_prescription_bookings($limit, $start, $search){
    $this->db->select('
        pb.id,
        pb.booking_id,
        pb.created_on,
        pb.order_type,
        pb.user_id,
        pb.main_data_id,
        pb.address_id,
        pb.mobile,
        pb.name,
        pb.image,
        pb.booking_status,
        pb.booking_type,
        pb.accept_status,
        u.image AS user_image,
        a.hno,a.address, a.building_no, a.pincode, a.state,a.landmark,a.address_type,a.default_address,a.lat,a.lon,md.name as hospital_name
    ');

    $this->db->from('pharmacy_medicine_orders pb');
    $this->db->join('users u', 'u.id = pb.user_id', 'left');
    // Join address table only where pb.address_id != 0
    $this->db->join('user_addresses a', 'a.id = pb.address_id AND pb.address_id != 0', 'left');
    $this->db->join('pharmacies md', 'md.id = pb.main_data_id', 'left');
    

    $this->db->group_start();
    $this->db->where('pb.accept_status', 'accepted');
    $this->db->or_where('pb.accept_status', '');
    $this->db->group_end();

    $this->db->group_start();
    $this->db->where('pb.booking_status', 'booked');
    $this->db->or_where('pb.booking_status', 'pickedup');
    $this->db->group_end();

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('pb.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('pb.mobile', $search);
        $this->db->or_like('pb.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('pb.created_on', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $raw = $query->result();

    $result = [];
    foreach ($raw as $row) {
        $id = $row->booking_id;
        if (!isset($result[$id])) {
            $result[$id] = [
                'id'                => (int)$row->id,
                'booking_id'        => $row->booking_id,
                'created_on'        => $row->created_on,
                'order_type'        => $row->order_type,
                'user_id'           => (int)$row->user_id,
                'main_data_id'      => (int)$row->main_data_id,
                'address_id'        => (int)$row->address_id,
                'name'              => $row->name,
                'mobile'            => $row->mobile,
                'image'             => $row->image,
                'user_image'        => $row->user_image,
                'booking_type'      => $row->booking_type,
                'booking_status'    => $row->booking_status,
                'accept_status'     => $row->accept_status,
                'hno'               => $row->hno,
                'address'           => $row->address,
                'building_no'       => $row->building_no,
                'pincode'           => intval($row->pincode),
                'state'             => $row->state,
                'landmark'          => $row->landmark,
                'address_type'      => $row->address_type,
                'default_address'   => intval($row->default_address),
                'lat'               => $row->lat,
                'lon'               => $row->lon,
                'hospital_name'     => $row->hospital_name
            ];
        }
    }

    return array_values($result);
}
public function get_main_ongoing_pharmacy_prescription_bookings_count($search){
    $this->db->from('pharmacy_medicine_orders pb');
    $this->db->join('users u', 'u.id = pb.user_id', 'left');
    $this->db->join('user_addresses a', 'a.id = pb.address_id AND pb.address_id != 0', 'left');
    $this->db->join('pharmacies md', 'md.id = pb.main_data_id', 'left');

    // Accept Status Filter
    $this->db->group_start();
    $this->db->where('pb.accept_status', 'accepted');
    $this->db->or_where('pb.accept_status', '');
    $this->db->group_end();

    // Booking Status Filter
    $this->db->group_start();
    $this->db->where('pb.booking_status', 'booked');
    $this->db->or_where('pb.booking_status', 'pickedup');
    $this->db->group_end();

    // Search Filter
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('pb.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('pb.mobile', $search);
        $this->db->or_like('pb.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_main_completed_pharmacy_prescription_bookings($limit, $start, $search){
    $this->db->select('
        pb.id,
        pb.booking_id,
        pb.created_on,
        pb.order_type,
        pb.user_id,
        pb.main_data_id,
        pb.address_id,
        pb.mobile,
        pb.name,
        pb.image,
        pb.booking_status,
        pb.booking_type,
        pb.accept_status,
        u.image AS user_image,
        a.hno,a.address, a.building_no, a.pincode, a.state,a.landmark,a.address_type,a.default_address,a.lat,a.lon,md.name as hospital_name
    ');

    $this->db->from('pharmacy_medicine_orders pb');
    $this->db->join('users u', 'u.id = pb.user_id', 'left');
    // Join address table only where pb.address_id != 0
    $this->db->join('user_addresses a', 'a.id = pb.address_id AND pb.address_id != 0', 'left');
    $this->db->join('pharmacies md','md.id=pb.main_data_id','left');
    $this->db->where('pb.booking_status', 'completed');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('pb.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('pb.mobile', $search);
        $this->db->or_like('pb.name', $search);
        $this->db->group_end();
    }

    $this->db->order_by('pb.created_on', 'DESC');
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $raw = $query->result();

    $result = [];
    foreach ($raw as $row) {
        $id = $row->booking_id;
        if (!isset($result[$id])) {
            $result[$id] = [
                'id'                => (int)$row->id,
                'booking_id'        => $row->booking_id,
                'created_on'        => $row->created_on,
                'order_type'        => $row->order_type,
                'user_id'           => (int)$row->user_id,
                'main_data_id'      => (int)$row->main_data_id,
                'address_id'        => (int)$row->address_id,
                'name'              => $row->name,
                'mobile'            => $row->mobile,
                'image'             => $row->image,
                'user_image'        => $row->user_image,
                'booking_type'      => $row->booking_type,
                'booking_status'    => $row->booking_status,
                'accept_status'     => $row->accept_status,
                'hno'               => $row->hno,
                'address'           => $row->address,
                'building_no'       => $row->building_no,
                'pincode'           => intval($row->pincode),
                'state'             => $row->state,
                'landmark'          => $row->landmark,
                'address_type'      => $row->address_type,
                'default_address'   => intval($row->default_address),
                'lat'               => $row->lat,
                'lon'               => $row->lon,
                'hospital_name'     => $row->hospital_name
            ];
        }
    }

    return array_values($result);
}
public function get_main_completed_pharmacy_prescription_bookings_count($search){
    $this->db->from('pharmacy_medicine_orders pb');
    $this->db->join('users u', 'u.id = pb.user_id', 'left');
    $this->db->join('user_addresses a', 'a.id = pb.address_id AND pb.address_id != 0', 'left');
    $this->db->join('pharmacies md','md.id = pb.main_data_id','left');

    $this->db->where('pb.booking_status', 'completed');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('pb.booking_id', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('pb.mobile', $search);
        $this->db->or_like('pb.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*pharmacy_prescription_bookings*/

/*main_diagnostic_bookings*/
public function get_main_ongoing_diagnostic_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.booking_status,
        db.booking_type,
        (SELECT name FROM diagnostic_booking_packages hdbp WHERE hdbp.booking_id = db.booking_id LIMIT 1) AS name,
        db.count,
        db.image,
        db.mobile,
        db.accept_status,
        db.slot_id,
        db.date,
        db.time,
        db.fee,
        db.consultation_fee,
        db.coupon_id,
        db.coupon_name,
        db.coupon_percentage,
        db.coupon_discount,
        db.payment_type,
        db.transaction_id,
        db.family_member_id,
        d.name as hospital_name,
        (
            (SELECT COUNT(*) FROM diagnostic_booking_tests hdbt WHERE hdbt.booking_id = db.booking_id) +
            (SELECT COUNT(*) FROM diagnostic_booking_subtests hdbst WHERE hdbst.booking_id = db.booking_id)
        ) AS total_test_count
    ');
    $this->db->from('diagnostic_bookings db');
    $this->db->where('db.booking_status', 'booked');
    
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    $this->db->join('diagnostics d', 'd.id=db.main_data_id', 'left');

    $today = date('Y-m-d');
    $this->db->order_by("CASE WHEN db.date = '{$today}' THEN 0 ELSE 1 END", "ASC");
    $this->db->order_by('db.date', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        $CI->db->select("
            p.id AS package_id, p.name AS package_name,
            t.id AS test_id, t.name AS test_name,
            st.id AS sub_test_id, st.name AS sub_test_name
        ");
        $CI->db->from('diagnostic_booking_packages p');
        $CI->db->join('diagnostic_booking_tests t', 't.booking_package_id = p.id AND t.booking_id = p.booking_id', 'left');
        $CI->db->join('diagnostic_booking_subtests st', 'st.booking_test_id = t.id AND st.booking_id = t.booking_id', 'left');
        $CI->db->where('p.booking_id', $row['booking_id']);
        $test_result = $CI->db->get()->result_array();

        $packages = [];
        foreach ($test_result as $test_row) {
            $pkg_id = (int)$test_row['package_id'];
            if (!isset($packages[$pkg_id])) {
                $packages[$pkg_id] = [
                    'package_name' => $test_row['package_name'],
                    'tests' => []
                ];
            }

            $test_id = (int)$test_row['test_id'];
            if ($test_id && !isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id] = [
                    'test_name' => $test_row['test_name'],
                    'sub_tests' => []
                ];
            }

            $sub_test_id = (int)$test_row['sub_test_id'];
            if ($sub_test_id && isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id]['sub_tests'][] = $test_row['sub_test_name'];
            }
        }

        $formatted_tests = [];
        foreach ($packages as $pkg) {
            foreach ($pkg['tests'] as $test) {
                $formatted_tests[] = [
                    'package_name' => $pkg['package_name'],
                    'test_name' => $test['test_name'],
                    'sub_tests' => $test['sub_tests']
                ];
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'count' => (int)$row['count'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'total_test_count' => (int)$row['total_test_count'],
            'accept_status' => $row['accept_status'],
            'slot_id' => (int)$row['slot_id'],
            'date' => $row['date'],
            'time' => $row['time'],
            'fee' => (int)$row['fee'],
            'consultation_fee' => (int)$row['consultation_fee'],
            'coupon_id' => (int)$row['coupon_id'],
            'coupon_name' => !empty($row['coupon_name']) ? $row['coupon_name'] : 'N/A',
            'coupon_percentage' => (int)$row['coupon_percentage'],
            'coupon_discount' => (int)$row['coupon_discount'],
            'payment_type' => $row['payment_type'],
            'transaction_id' => !empty($row['transaction_id']) ? $row['transaction_id'] : 'N/A',
            'family_members' => $family_members,
            'test_details' => $formatted_tests,
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_main_ongoing_diagnostic_bookings_count($search){
    $this->db->from('diagnostic_bookings db');
    $this->db->join('diagnostics d', 'd.id = db.main_data_id', 'left');

    // Booking Status = 'booked'
    $this->db->where('db.booking_status', 'booked');

    // Accept Status = 'accepted' or empty
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    // Search filters (if provided)
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_main_completed_diagnostic_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.booking_status,
        db.booking_type,
        (SELECT name FROM diagnostic_booking_packages hdbp WHERE hdbp.booking_id = db.booking_id LIMIT 1) AS name,
        db.count,
        db.image,
        db.mobile,
        db.accept_status,
        db.slot_id,
        db.date,
        db.time,
        db.fee,
        db.consultation_fee,
        db.coupon_id,
        db.coupon_name,
        db.coupon_percentage,
        db.coupon_discount,
        db.payment_type,
        db.transaction_id,
        db.family_member_id,
        db.completed_date,
        d.name as hospital_name,
        (
            (SELECT COUNT(*) FROM diagnostic_booking_tests hdbt WHERE hdbt.booking_id = db.booking_id) +
            (SELECT COUNT(*) FROM diagnostic_booking_subtests hdbst WHERE hdbst.booking_id = db.booking_id)
        ) AS total_test_count
    ');
    $this->db->from('diagnostic_bookings db');

    $this->db->where('db.booking_status', 'completed');
    
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    $this->db->join('diagnostics d', 'd.id=db.main_data_id', 'left');

    $today = date('Y-m-d');
    $this->db->order_by("CASE WHEN db.date = '{$today}' THEN 0 ELSE 1 END", "ASC");
    $this->db->order_by('db.date', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        $CI->db->select("
            p.id AS package_id, p.name AS package_name,
            t.id AS test_id, t.name AS test_name,
            st.id AS sub_test_id, st.name AS sub_test_name
        ");
        $CI->db->from('diagnostic_booking_packages p');
        $CI->db->join('diagnostic_booking_tests t', 't.booking_package_id = p.id AND t.booking_id = p.booking_id', 'left');
        $CI->db->join('diagnostic_booking_subtests st', 'st.booking_test_id = t.id AND st.booking_id = t.booking_id', 'left');
        $CI->db->where('p.booking_id', $row['booking_id']);
        $test_result = $CI->db->get()->result_array();

        $packages = [];
        foreach ($test_result as $test_row) {
            $pkg_id = (int)$test_row['package_id'];
            if (!isset($packages[$pkg_id])) {
                $packages[$pkg_id] = [
                    'package_name' => $test_row['package_name'],
                    'tests' => []
                ];
            }

            $test_id = (int)$test_row['test_id'];
            if ($test_id && !isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id] = [
                    'test_name' => $test_row['test_name'],
                    'sub_tests' => []
                ];
            }

            $sub_test_id = (int)$test_row['sub_test_id'];
            if ($sub_test_id && isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id]['sub_tests'][] = $test_row['sub_test_name'];
            }
        }

        $formatted_tests = [];
        foreach ($packages as $pkg) {
            foreach ($pkg['tests'] as $test) {
                $formatted_tests[] = [
                    'package_name' => $pkg['package_name'],
                    'test_name' => $test['test_name'],
                    'sub_tests' => $test['sub_tests']
                ];
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'count' => (int)$row['count'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'total_test_count' => (int)$row['total_test_count'],
            'accept_status' => $row['accept_status'],
            'slot_id' => (int)$row['slot_id'],
            'date' => $row['date'],
            'time' => $row['time'],
            'fee' => (int)$row['fee'],
            'consultation_fee' => (int)$row['consultation_fee'],
            'coupon_id' => (int)$row['coupon_id'],
            'coupon_name' => !empty($row['coupon_name']) ? $row['coupon_name'] : 'N/A',
            'coupon_percentage' => (int)$row['coupon_percentage'],
            'coupon_discount' => (int)$row['coupon_discount'],
            'payment_type' => $row['payment_type'],
            'transaction_id' => !empty($row['transaction_id']) ? $row['transaction_id'] : 'N/A',
            'family_members' => $family_members,
            'test_details' => $formatted_tests,
            'completed_date'        => !empty($row['completed_date']) ? date('d-m-Y', strtotime($row['completed_date'])) : 'N/A',
            'hospital_name'     => $row['hospital_name']
        ];
    }, $result);
}
public function get_main_completed_diagnostic_bookings_count($search) {
    $this->db->from('diagnostic_bookings db');
    $this->db->join('diagnostics d', 'd.id = db.main_data_id', 'left');

    // Filter: completed bookings only
    $this->db->where('db.booking_status', 'completed');

    // Search filters (if provided)
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_main_completed_diagnostic_bookings_reports($booking_id,$booking_type,$limit,$start,$search){
    $this->db->select('ar.*')->from('diagnostic_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_main_completed_diagnostic_bookings_reports_count($booking_id,$booking_type,$search){
    $this->db->select('ar.*')->from('diagnostic_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*main_diagnostic_bookings*/

/*main_diagnostic_prescription_bookings*/
public function get_main_ongoing_diagnostic_prescription_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.name,
        db.booking_status,
        db.booking_type,
        db.image,
        db.mobile,
        db.accept_status,
        db.family_member_id,
        d.name as hospital_name
    ');
    $this->db->from('diagnostic_prescription_bookings db');
    $this->db->where('db.booking_status', 'booked');
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    $this->db->join('diagnostics d', 'd.id=db.main_data_id', 'left');


    $this->db->order_by('db.created_on', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'accept_status' => $row['accept_status'],
            'family_members' => $family_members,
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_main_ongoing_diagnostic_prescription_bookings_count($search){
    $this->db->from('diagnostic_prescription_bookings db');
    $this->db->join('diagnostics d', 'd.id=db.main_data_id', 'left');

    $this->db->where('db.booking_status', 'booked');

    // Accept Status Filter
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    // Apply search filters if present
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_main_completed_diagnostic_prescription_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.name,
        db.booking_status,
        db.booking_type,
        db.image,
        db.mobile,
        db.accept_status,
        db.family_member_id,
        db.completed_date,
        d.name as hospital_name
    ');
    $this->db->from('diagnostic_prescription_bookings db');
    
    $this->db->where('db.booking_status', 'completed');
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    $this->db->join('diagnostics d', 'd.id=db.main_data_id', 'left');


    $this->db->order_by('db.created_on', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'accept_status' => $row['accept_status'],
            'family_members' => $family_members,
            'completed_date'        => !empty($row['completed_date']) ? date('d-m-Y', strtotime($row['completed_date'])) : 'N/A',
            'hospital_name'         => $row['hospital_name']
        ];
    }, $result);
}
public function get_main_completed_diagnostic_prescription_bookings_count($search){
    $sess_data = $this->session->userdata('main_data_id');

    $this->db->from('diagnostic_prescription_bookings db');
    $this->db->join('diagnostics d', 'd.id = db.main_data_id', 'left');

    
    $this->db->where('db.booking_status', 'completed');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_main_completed_diagnostic_prescription_bookings_reports($booking_id,$booking_type,$limit,$start,$search){
    $this->db->select('ar.*')->from('diagnostic_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_main_completed_diagnostic_prescription_bookings_reports_count($booking_id,$booking_type,$search){
    $this->db->select('ar.*')->from('diagnostic_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*main_diagnostic_prescription_bookings*/

/*main_lab_test_bookings*/
public function get_main_ongoing_lab_test_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.booking_status,
        db.booking_type,
        (SELECT name FROM lab_test_booking_packages hdbp WHERE hdbp.booking_id = db.booking_id LIMIT 1) AS name,
        db.count,
        db.image,
        db.mobile,
        db.accept_status,
        db.slot_id,
        db.date,
        db.time,
        db.fee,
        db.consultation_fee,
        db.coupon_id,
        db.coupon_name,
        db.coupon_percentage,
        db.coupon_discount,
        db.payment_type,
        db.transaction_id,
        db.family_member_id,
        d.name as hospital_name,
        la.name as lab_agent,
        (
            (SELECT COUNT(*) FROM lab_test_booking_tests hdbt WHERE hdbt.booking_id = db.booking_id) +
            (SELECT COUNT(*) FROM lab_test_booking_subtests hdbst WHERE hdbst.booking_id = db.booking_id)
        ) AS total_test_count
    ');
    $this->db->from('lab_test_bookings db');
    $this->db->where('db.booking_status', 'booked');
    
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    $this->db->join('lab_tests d', 'd.id=db.main_data_id', 'left');
    $this->db->join('lab_agents la', 'la.id=db.agent_id', 'left');

    $today = date('Y-m-d');
    $this->db->order_by("CASE WHEN db.date = '{$today}' THEN 0 ELSE 1 END", "ASC");
    $this->db->order_by('db.date', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        $CI->db->select("
            p.id AS package_id, p.name AS package_name,
            t.id AS test_id, t.name AS test_name,
            st.id AS sub_test_id, st.name AS sub_test_name
        ");
        $CI->db->from('lab_test_booking_packages p');
        $CI->db->join('lab_test_booking_tests t', 't.booking_package_id = p.id AND t.booking_id = p.booking_id', 'left');
        $CI->db->join('lab_test_booking_subtests st', 'st.booking_test_id = t.id AND st.booking_id = t.booking_id', 'left');
        $CI->db->where('p.booking_id', $row['booking_id']);
        $test_result = $CI->db->get()->result_array();

        $packages = [];
        foreach ($test_result as $test_row) {
            $pkg_id = (int)$test_row['package_id'];
            if (!isset($packages[$pkg_id])) {
                $packages[$pkg_id] = [
                    'package_name' => $test_row['package_name'],
                    'tests' => []
                ];
            }

            $test_id = (int)$test_row['test_id'];
            if ($test_id && !isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id] = [
                    'test_name' => $test_row['test_name'],
                    'sub_tests' => []
                ];
            }

            $sub_test_id = (int)$test_row['sub_test_id'];
            if ($sub_test_id && isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id]['sub_tests'][] = $test_row['sub_test_name'];
            }
        }

        $formatted_tests = [];
        foreach ($packages as $pkg) {
            foreach ($pkg['tests'] as $test) {
                $formatted_tests[] = [
                    'package_name' => $pkg['package_name'],
                    'test_name' => $test['test_name'],
                    'sub_tests' => $test['sub_tests']
                ];
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'count' => (int)$row['count'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'total_test_count' => (int)$row['total_test_count'],
            'accept_status' => $row['accept_status'],
            'slot_id' => (int)$row['slot_id'],
            'date' => $row['date'],
            'time' => $row['time'],
            'fee' => (int)$row['fee'],
            'consultation_fee' => (int)$row['consultation_fee'],
            'coupon_id' => (int)$row['coupon_id'],
            'coupon_name' => !empty($row['coupon_name']) ? $row['coupon_name'] : 'N/A',
            'coupon_percentage' => (int)$row['coupon_percentage'],
            'coupon_discount' => (int)$row['coupon_discount'],
            'payment_type' => $row['payment_type'],
            'transaction_id' => !empty($row['transaction_id']) ? $row['transaction_id'] : 'N/A',
            'family_members' => $family_members,
            'test_details' => $formatted_tests,
            'hospital_name'         => $row['hospital_name'],
            'lab_agent'     => $row['lab_agent']
        ];
    }, $result);
}
public function get_main_ongoing_lab_test_bookings_count($search){
    $this->db->from('lab_test_bookings db');
    $this->db->join('lab_tests d', 'd.id = db.main_data_id', 'left');

    // Booking Status = 'booked'
    $this->db->where('db.booking_status', 'booked');

    // Accept Status = 'accepted' or empty
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    // Search filters (if provided)
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_main_completed_lab_test_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.booking_status,
        db.booking_type,
        (SELECT name FROM lab_test_booking_packages hdbp WHERE hdbp.booking_id = db.booking_id LIMIT 1) AS name,
        db.count,
        db.image,
        db.mobile,
        db.accept_status,
        db.slot_id,
        db.date,
        db.time,
        db.fee,
        db.consultation_fee,
        db.coupon_id,
        db.coupon_name,
        db.coupon_percentage,
        db.coupon_discount,
        db.payment_type,
        db.transaction_id,
        db.family_member_id,
        db.completed_date,
        d.name as hospital_name,
        la.name as lab_agent,
        (
            (SELECT COUNT(*) FROM lab_test_booking_tests hdbt WHERE hdbt.booking_id = db.booking_id) +
            (SELECT COUNT(*) FROM lab_test_booking_subtests hdbst WHERE hdbst.booking_id = db.booking_id)
        ) AS total_test_count
    ');
    $this->db->from('lab_test_bookings db');

    $this->db->where('db.booking_status', 'completed');
    
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    $this->db->join('lab_tests d', 'd.id=db.main_data_id', 'left');
    $this->db->join('lab_agents la', 'la.id=db.agent_id', 'left');

    $today = date('Y-m-d');
    $this->db->order_by("CASE WHEN db.date = '{$today}' THEN 0 ELSE 1 END", "ASC");
    $this->db->order_by('db.date', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        $CI->db->select("
            p.id AS package_id, p.name AS package_name,
            t.id AS test_id, t.name AS test_name,
            st.id AS sub_test_id, st.name AS sub_test_name
        ");
        $CI->db->from('lab_test_booking_packages p');
        $CI->db->join('lab_test_booking_tests t', 't.booking_package_id = p.id AND t.booking_id = p.booking_id', 'left');
        $CI->db->join('lab_test_booking_subtests st', 'st.booking_test_id = t.id AND st.booking_id = t.booking_id', 'left');
        $CI->db->where('p.booking_id', $row['booking_id']);
        $test_result = $CI->db->get()->result_array();

        $packages = [];
        foreach ($test_result as $test_row) {
            $pkg_id = (int)$test_row['package_id'];
            if (!isset($packages[$pkg_id])) {
                $packages[$pkg_id] = [
                    'package_name' => $test_row['package_name'],
                    'tests' => []
                ];
            }

            $test_id = (int)$test_row['test_id'];
            if ($test_id && !isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id] = [
                    'test_name' => $test_row['test_name'],
                    'sub_tests' => []
                ];
            }

            $sub_test_id = (int)$test_row['sub_test_id'];
            if ($sub_test_id && isset($packages[$pkg_id]['tests'][$test_id])) {
                $packages[$pkg_id]['tests'][$test_id]['sub_tests'][] = $test_row['sub_test_name'];
            }
        }

        $formatted_tests = [];
        foreach ($packages as $pkg) {
            foreach ($pkg['tests'] as $test) {
                $formatted_tests[] = [
                    'package_name' => $pkg['package_name'],
                    'test_name' => $test['test_name'],
                    'sub_tests' => $test['sub_tests']
                ];
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'count' => (int)$row['count'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'total_test_count' => (int)$row['total_test_count'],
            'accept_status' => $row['accept_status'],
            'slot_id' => (int)$row['slot_id'],
            'date' => $row['date'],
            'time' => $row['time'],
            'fee' => (int)$row['fee'],
            'consultation_fee' => (int)$row['consultation_fee'],
            'coupon_id' => (int)$row['coupon_id'],
            'coupon_name' => !empty($row['coupon_name']) ? $row['coupon_name'] : 'N/A',
            'coupon_percentage' => (int)$row['coupon_percentage'],
            'coupon_discount' => (int)$row['coupon_discount'],
            'payment_type' => $row['payment_type'],
            'transaction_id' => !empty($row['transaction_id']) ? $row['transaction_id'] : 'N/A',
            'family_members' => $family_members,
            'test_details' => $formatted_tests,
            'completed_date'        => !empty($row['completed_date']) ? date('d-m-Y', strtotime($row['completed_date'])) : 'N/A',
            'hospital_name'     => $row['hospital_name'],
            'lab_agent'         => $row['lab_agent']
        ];
    }, $result);
}
public function get_main_completed_lab_test_bookings_count($search) {
    $this->db->from('lab_test_bookings db');
    $this->db->join('lab_tests d', 'd.id = db.main_data_id', 'left');

    // Filter: completed bookings only
    $this->db->where('db.booking_status', 'completed');

    // Search filters (if provided)
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->or_like('db.date', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_main_completed_lab_test_bookings_reports($booking_id,$booking_type,$limit,$start,$search){
    $this->db->select('ar.*')->from('lab_test_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_main_completed_lab_test_bookings_reports_count($booking_id,$booking_type,$search){
    $this->db->select('ar.*')->from('lab_test_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*main_lab_test_bookings*/

/*main_lab_test_prescription_bookings*/
public function get_main_ongoing_lab_test_prescription_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.name,
        db.booking_status,
        db.booking_type,
        db.image,
        db.mobile,
        db.accept_status,
        db.family_member_id,
        d.name as hospital_name,
        la.name as lab_agent
    ');
    $this->db->from('lab_test_prescription_bookings db');
    $this->db->where('db.booking_status', 'booked');
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    $this->db->join('lab_tests d', 'd.id=db.main_data_id', 'left');
    $this->db->join('lab_agents la', 'la.id=db.agent_id', 'left');


    $this->db->order_by('db.created_on', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'accept_status' => $row['accept_status'],
            'family_members' => $family_members,
            'hospital_name' => $row['hospital_name'],
            'lab_agent'     => $row['lab_agent']
        ];

    }, $result);
}
public function get_main_ongoing_lab_test_prescription_bookings_count($search){
    $this->db->from('lab_test_prescription_bookings db');
    $this->db->join('lab_tests d', 'd.id=db.main_data_id', 'left');

    $this->db->where('db.booking_status', 'booked');

    // Accept Status Filter
    $this->db->group_start();
    $this->db->where('db.accept_status', 'accepted');
    $this->db->or_where('db.accept_status', '');
    $this->db->group_end();

    // Apply search filters if present
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_main_completed_lab_test_prescription_bookings($limit, $start, $search){
    $this->db->select('
        db.id,
        db.booking_id,
        db.created_on,
        db.user_id,
        db.main_data_id,
        db.name,
        db.booking_status,
        db.booking_type,
        db.image,
        db.mobile,
        db.accept_status,
        db.family_member_id,
        db.completed_date,
        d.name as hospital_name,
        la.name as lab_agent
    ');
    $this->db->from('lab_test_prescription_bookings db');
    
    $this->db->where('db.booking_status', 'completed');
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    $this->db->join('lab_tests d', 'd.id=db.main_data_id', 'left');
    $this->db->join('lab_agents la', 'la.id=db.agent_id', 'left');


    $this->db->order_by('db.created_on', 'DESC');

    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $result = $query->result_array();

    $CI = &get_instance();

    return array_map(function ($row) use ($CI) {
        $family_members = [];
        if (!empty($row['family_member_id'])) {
            $ids = explode(',', $row['family_member_id']);
            $clean_ids = array_map('intval', array_filter($ids));
            if (!empty($clean_ids)) {
                $CI->db->select('id, name, dob, gender, email, mobile, image as user_image');
                $CI->db->from('family_members');
                $CI->db->where_in('id', $clean_ids);
                $family_members = $CI->db->get()->result_array();
                foreach ($family_members as &$member) {
                    $member['id'] = (int)$member['id'];
                }
            }
        }

        return [
            'id' => (int)$row['id'],
            'booking_id' => $row['booking_id'],
            'created_on' => $row['created_on'],
            'user_id' => (int)$row['user_id'],
            'diagnostic_id' => (int)$row['main_data_id'],
            'name' => $row['name'],
            'mobile' => $row['mobile'],
            'image' => $row['image'],
            'booking_status' => $row['booking_status'],
            'booking_type' => $row['booking_type'],
            'accept_status' => $row['accept_status'],
            'family_members' => $family_members,
            'completed_date'        => !empty($row['completed_date']) ? date('d-m-Y', strtotime($row['completed_date'])) : 'N/A',
            'hospital_name'         => $row['hospital_name'],
            'lab_agent'             => $row['lab_agent']
        ];
    }, $result);
}
public function get_main_completed_lab_test_prescription_bookings_count($search){
    $sess_data = $this->session->userdata('main_data_id');

    $this->db->from('lab_test_prescription_bookings db');
    $this->db->join('lab_tests d', 'd.id = db.main_data_id', 'left');

    
    $this->db->where('db.booking_status', 'completed');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('db.booking_id', $search);
        $this->db->or_like('d.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_main_completed_lab_test_prescription_bookings_reports($booking_id,$booking_type,$limit,$start,$search){
    $this->db->select('ar.*')->from('lab_test_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $this->db->limit($limit,$start);
    $query = $this->db->get();
    return $query->result_array();
}
public function get_main_completed_lab_test_prescription_bookings_reports_count($booking_id,$booking_type,$search){
    $this->db->select('ar.*')->from('lab_test_reports ar');
    $this->db->where(['ar.booking_id' => $booking_id,'ar.booking_type' => $booking_type]);
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('ar.booking_id',$search);
        $this->db->group_end();
    }
    $query = $this->db->get();
    return $query->num_rows();
}
/*main_lab_test_prescription_bookings*/

/*online_doctor_ongoing_doctor_bookings*/
public function get_online_doctor_ongoing_doctor_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.consult_type, b.user_id, b.speciality_id, b.booking_status, b.doctor_id, b.slot_id, b.time, b.date, b.mobile,b.call_status, b.family_member_id, b.fee, b.consultation_fee, b.coupon_id, b.coupon_name, b.coupon_percentage, b.coupon_discount, b.payment_type,b.transaction_id, b.created_on, fm.name as patient_name, s.name AS speciality_name, d.name AS doctor_name, d.image as doctor_image, d.mobile as doctor_mobile, d.exp as doctor_exp,GROUP_CONCAT(DISTINCT md.name ORDER BY md.name SEPARATOR ", ") AS qualification,fm.email, fm.gender, fm.dob, fm.image,bg.name as blood_group');

    $this->db->from('online_doctor_bookings b');
    $this->db->join('online_doctor_specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('online_doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('medical_degrees md', 'FIND_IN_SET(md.id, d.qualification)', 'left');
    //$this->db->join('main_data mda','mda.id=b.main_data_id','left');
    // Filter active bookings for the doctor
    
    $this->db->where('b.booking_status', 'booked');
    $this->db->where('b.consult_type', 'online');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('fm.name',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    // Format and return result
    return array_map(function ($row) {
        return [
            'id'                => intval($row['id']),
            'booking_id'        => $row['booking_id'],
            'consult_type'      => $row['consult_type'],
            'user_id'           => intval($row['user_id']),
            'speciality_id'     => intval($row['speciality_id']),
            'doctor_id'         => intval($row['doctor_id']),
            'slot_id'           => intval($row['slot_id']),
            'time'              => $row['time'],
            'booking_status'    => $row['booking_status'],
            'date'              => date('d-m-Y', strtotime($row['date'])),
            'mobile'            => intval($row['mobile']),
            'call_status'       => intval($row['call_status']),
            'family_member_id'  => intval($row['family_member_id']),
            'fee'               => intval($row['fee']),
            'consultation_fee'  => intval($row['consultation_fee']),
            'coupon_id'         => intval($row['coupon_id']),
            'coupon_name'       => $row['coupon_name'],
            'coupon_percentage' => intval($row['coupon_percentage']),
            'coupon_discount'   => intval($row['coupon_discount']),
            'payment_type'      => $row['payment_type'],
            'transaction_id'    => $row['transaction_id'],
            'created_on'        => $row['created_on'],
            'speciality_name'   => $row['speciality_name'],
            'name'              => $row['doctor_name'],
            'doctor_image'      => $row['doctor_image'],
            'doctor_mobile'     => $row['doctor_mobile'],
            'doctor_exp'        => $row['doctor_exp'],
            'qualification'     => $row['qualification'],
            'image'             => $row['image'],
            'patient_name'      => $row['patient_name'],
            'email'             => $row['email'],
            'gender'            => $row['gender'],
            'dob'               => $row['dob'],
            'blood_group'       => $row['blood_group']
        ];
    }, $result);
}
public function get_online_doctor_ongoing_doctor_bookings_count($search){
    $this->db->from('online_doctor_bookings b');
    $this->db->where('b.booking_status', 'booked');
    $this->db->where('b.consult_type', 'online');

    // JOINs for search support
    $this->db->join('online_doctor_specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('online_doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');

    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('fm.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function get_online_doctor_completed_doctor_bookings($limit,$start,$search){
    $this->db->select('b.id, b.booking_id, b.consult_type, b.user_id, b.speciality_id, b.booking_status, b.doctor_id, b.slot_id, b.time, b.date, b.mobile,b.call_status, b.family_member_id, b.fee, b.consultation_fee, b.coupon_id, b.coupon_name, b.coupon_percentage, b.coupon_discount, b.payment_type,b.transaction_id, b.created_on, fm.name as patient_name, s.name AS speciality_name, d.name AS doctor_name, d.image as doctor_image, d.mobile as doctor_mobile, d.exp as doctor_exp,GROUP_CONCAT(DISTINCT md.name ORDER BY md.name SEPARATOR ", ") AS qualification,fm.email, fm.gender, fm.dob, fm.image,bg.name as blood_group');

    $this->db->from('online_doctor_bookings b');
    $this->db->join('online_doctor_specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('online_doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');
    $this->db->join('medical_degrees md', 'FIND_IN_SET(md.id, d.qualification)', 'left');
    // Filter active bookings for the doctor
    
    $this->db->where('b.booking_status', 'completed');
    $this->db->where('b.consult_type', 'online');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('b.booking_id',$search);
        $this->db->or_like('b.date',$search);
        $this->db->or_like('b.mobile',$search);
        $this->db->or_like('fm.name',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->group_by('b.id');

    // Custom ordering: today's bookings first, then older dates
    $today = date('Y-m-d');
    $this->db->order_by("CASE 
        WHEN b.date = '{$today}' THEN 0 
        ELSE 1 
    END", "ASC"); // Today comes first
    $this->db->order_by('b.date', 'DESC'); // Then remaining in descending order

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();
    
    $final_result = [];

    foreach ($result as $row) {
        $booking_id = $row['booking_id'];

        // Fetch medicines
        $medicines = $this->db
        ->select('medicine, medicine_time')
        ->get_where('online_doctor_booking_medicines', ['booking_id' => $booking_id])
        ->result_array();

        
        // Fetch tests
        $tests = $this->db
        ->select('test, test_instruction')
        ->get_where('online_doctor_booking_tests', ['booking_id' => $booking_id])
        ->result_array();
        
        // Fetch notes
        
        $notes = $this->db
            ->select('notes')
            ->get_where('online_doctor_booking_notes', ['booking_id' => $booking_id])
            ->result_array();
        
        // Extract just the 'notes' values into a simple array
        $note_values = array_column($notes, 'notes');
        
        // Assign directly to your output array
        $data = $note_values;
        
        $final_result[] = [
            'id'                => intval($row['id']),
            'booking_id'        => $row['booking_id'],
            'consult_type'      => $row['consult_type'],
            'user_id'           => intval($row['user_id']),
            'speciality_id'     => intval($row['speciality_id']),
            'doctor_id'         => intval($row['doctor_id']),
            'slot_id'           => intval($row['slot_id']),
            'time'              => $row['time'],
            'booking_status'    => $row['booking_status'],
            'date'              => date('d-m-Y', strtotime($row['date'])),
            'mobile'            => intval($row['mobile']),
            'call_status'       => intval($row['call_status']),
            'family_member_id'  => intval($row['family_member_id']),
            'fee'               => intval($row['fee']),
            'consultation_fee'  => intval($row['consultation_fee']),
            'coupon_id'         => intval($row['coupon_id']),
            'coupon_name'       => $row['coupon_name'],
            'coupon_percentage' => intval($row['coupon_percentage']),
            'coupon_discount'   => intval($row['coupon_discount']),
            'payment_type'      => $row['payment_type'],
            'transaction_id'    => $row['transaction_id'],
            'created_on'        => $row['created_on'],
            'speciality_name'   => $row['speciality_name'],
            'name'              => $row['doctor_name'],
            'doctor_image'      => $row['doctor_image'],
            'doctor_mobile'     => $row['doctor_mobile'],
            'doctor_exp'        => $row['doctor_exp'],
            'qualification'     => $row['qualification'],
            'image'             => $row['image'],
            'patient_name'      => $row['patient_name'],
            'email'             => $row['email'],
            'gender'            => $row['gender'],
            'dob'               => $row['dob'],
            'blood_group'       => $row['blood_group'],
            'medicines'         => !empty($medicines) ? $medicines : [],
            'tests'             => !empty($tests) ? $tests : [],
            'notes'             => !empty($notes) ? $notes : []
        ];
    }
    return $final_result;
}
public function get_online_doctor_completed_doctor_bookings_count($search){
    $this->db->from('online_doctor_bookings b');
    $this->db->where('b.booking_status', 'completed');
    $this->db->where('b.consult_type', 'online');

    // JOINs for extended search/filtering
    $this->db->join('online_doctor_specialities s', 's.id = b.speciality_id', 'left');
    $this->db->join('online_doctors d', 'd.id = b.doctor_id', 'left');
    $this->db->join('family_members fm', 'fm.id = b.family_member_id', 'left');
    $this->db->join('blood_groups bg', 'bg.id = fm.blood_group', 'left');


    // Optional search
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('b.booking_id', $search);
        $this->db->or_like('b.date', $search);
        $this->db->or_like('b.mobile', $search);
        $this->db->or_like('fm.name', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*online_doctor_ongoing_doctor_bookings*/

/*contact_us*/

/*user_contact_us*/
public function get_user_contact_us($limit,$start,$search){
    $this->db->select('cu.*');

    $this->db->from('contact_us cu');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_user_contact_us_count($search){
    $this->db->from('contact_us cu');

    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*user_contact_us*/

/*hospital_contact_us*/
public function get_hospital_contact_us($limit,$start,$search){
    $this->db->select('cu.*,md.name as hospital_name');

    $this->db->from('hospital_contact_us cu');
    $this->db->join('main_data md','md.id=cu.user_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_hospital_contact_us_count($search){
    $this->db->from('hospital_contact_us cu');
    $this->db->join('main_data md','md.id=cu.user_id','left');
    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*hospital_contact_us*/

/*hospital_doctor_contact_us*/
public function get_hospital_doctor_contact_us($limit,$start,$search){
    $this->db->select('cu.*,d.main_data_id,md.name as hospital_name');

    $this->db->from('doctor_contact_us cu');
    $this->db->join('doctors d','d.id=cu.user_id','left');
    $this->db->join('main_data md','md.id=d.main_data_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_hospital_doctor_contact_us_count($search){
    $this->db->from('doctor_contact_us cu');
    $this->db->join('doctors d','d.id=cu.user_id','left');
    $this->db->join('main_data md','md.id=d.main_data_id','left');
    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*hospital_doctor_contact_us*/

/*hospital_ambulance_driver_contact_us*/
public function get_hospital_ambulance_driver_contact_us($limit,$start,$search){
    $this->db->select('cu.*,d.main_data_id,md.name as hospital_name');

    $this->db->from('ambulance_drivers_contact_us cu');
    $this->db->join('ambulance_drivers d','d.id=cu.user_id','left');
    $this->db->join('main_data md','md.id=d.main_data_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_hospital_ambulance_driver_contact_us_count($search){
    $this->db->from('ambulance_drivers_contact_us cu');
    $this->db->join('ambulance_drivers d','d.id=cu.user_id','left');
    $this->db->join('main_data md','md.id=d.main_data_id','left');
    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*hospital_ambulance_driver_contact_us*/

/*pharmacy_contact_us*/
public function get_pharmacy_contact_us($limit,$start,$search){
    $this->db->select('cu.*,md.name as hospital_name');

    $this->db->from('pharmacy_contact_us cu');
    $this->db->join('pharmacies md','md.id=cu.user_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_pharmacy_contact_us_count($search){
    $this->db->from('pharmacy_contact_us cu');
    $this->db->join('pharmacies md','md.id=cu.user_id','left');
    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*pharmacy_contact_us*/

/*diagnostic_contact_us*/
public function get_diagnostic_contact_us($limit,$start,$search){
    $this->db->select('cu.*,md.name as hospital_name');

    $this->db->from('diagnostic_contact_us cu');
    $this->db->join('diagnostics md','md.id=cu.user_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_diagnostic_contact_us_count($search){
    $this->db->from('diagnostic_contact_us cu');
    $this->db->join('diagnostics md','md.id=cu.user_id','left');
    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*diagnostic_contact_us*/

/*lab_test_contact_us*/
public function get_lab_test_contact_us($limit,$start,$search){
    $this->db->select('cu.*,md.name as hospital_name');

    $this->db->from('lab_test_contact_us cu');
    $this->db->join('lab_tests md','md.id=cu.user_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_lab_test_contact_us_count($search){
    $this->db->from('lab_test_contact_us cu');
    $this->db->join('lab_tests md','md.id=cu.user_id','left');
    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*lab_test_contact_us*/

/*lab_agent_contact_us*/
public function get_lab_agent_contact_us($limit,$start,$search){
    $this->db->select('cu.*,d.main_data_id,md.name as hospital_name');

    $this->db->from('lab_agent_contact_us cu');
    $this->db->join('lab_agents d','d.id=cu.user_id','left');
    $this->db->join('lab_tests md','md.id=d.main_data_id','left');
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_lab_agent_contact_us_count($search){
    $this->db->from('lab_agent_contact_us cu');
    $this->db->join('lab_agents d','d.id=cu.user_id','left');
    $this->db->join('lab_tests md','md.id=d.main_data_id','left');
    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*lab_agent_contact_us*/

/*online_doctor_contact_us*/
public function get_online_doctor_contact_us($limit,$start,$search){
    $this->db->select('cu.*');

    $this->db->from('online_doctor_contact_us cu');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_online_doctor_contact_us_count($search){
    $this->db->from('online_doctor_contact_us cu');

    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*online_doctor_contact_us*/

/*executive_contact_us*/
public function get_executive_contact_us($limit,$start,$search){
    $this->db->select('cu.*');

    $this->db->from('executive_contact_us cu');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_executive_contact_us_count($search){
    $this->db->from('executive_contact_us cu');

    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*executive_contact_us*/

/*regional_manager_contact_us*/
public function get_regional_manager_contact_us($limit,$start,$search){
    $this->db->select('cu.*');

    $this->db->from('regional_manager_contact_us cu');
    
    if(!empty($search)){
        $this->db->group_start();
        $this->db->like('cu.name',$search);
        $this->db->or_like('cu.email',$search);
        $this->db->or_like('cu.mobile',$search);
        $this->db->group_end();
    }

    // Avoid duplicates in case of joins
    $this->db->order_by('cu.id');

    // Pagination
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $result = $query->result_array();

    return $result;
}
public function get_regional_manager_contact_us_count($search){
    $this->db->from('regional_manager_contact_us cu');

    // Optional search filtering
    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('cu.name', $search);
        $this->db->or_like('cu.email', $search);
        $this->db->or_like('cu.mobile', $search);
        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
/*regional_manager_contact_us*/

/*contact_us*/



/*notifications*/

/*user_notifications*/
public function get_user_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name', false);

    
    $this->db->from('user_notifications un');
    $this->db->join('users u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_user_notifications_count($search){
    $this->db->from('user_notifications un');
    $this->db->join('users u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_users($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'user']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_user($user_id, $title, $message){
    $device = $this->db->get_where('users', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*user_notifications*/

/*hospital_notifications*/
public function get_hospital_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name', false);

    
    $this->db->from('main_data_notifications un');
    $this->db->join('main_data u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_hospital_notifications_count($search){
    $this->db->from('main_data_notifications un');
    $this->db->join('main_data u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_hospitals($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'hospital']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_hospital($user_id, $title, $message){
    $device = $this->db->get_where('main_data', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*hospital_notifications*/

/*hospital_doctor_notifications*/
public function get_hospital_doctor_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name,md.name as hospital_name', false);

    
    $this->db->from('doctor_notifications un');
    $this->db->join('doctors u', 'u.id = un.member_id', 'left');
    $this->db->join('main_data md', 'md.id = u.main_data_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_hospital_doctor_notifications_count($search){
    $this->db->from('doctor_notifications un');
    $this->db->join('doctors u', 'u.id = un.member_id', 'left');
    $this->db->join('main_data md', 'md.id = u.main_data_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_hospital_doctors($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'hospital_doctor']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_hospital_doctor($user_id, $title, $message){
    $device = $this->db->get_where('doctors', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*hospital_doctor_notifications*/

/*hospital_ambulance_notifications*/
public function get_hospital_ambulance_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name,md.name as hospital_name', false);

    
    $this->db->from('driver_notifications un');
    $this->db->join('ambulance_drivers u', 'u.id = un.member_id', 'left');
    $this->db->join('main_data md', 'md.id = u.main_data_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_hospital_ambulance_notifications_count($search){
    $this->db->from('driver_notifications un');
    $this->db->join('ambulance_drivers u', 'u.id = un.member_id', 'left');
    $this->db->join('main_data md', 'md.id = u.main_data_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_hospital_drivers($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'ambulance_driver']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_hospital_driver($user_id, $title, $message){
    $device = $this->db->get_where('ambulance_drivers', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*hospital_ambulance_notifications*/

/*pharmacy_notifications*/
public function get_pharmacy_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name', false);

    
    $this->db->from('pharmacy_notifications un');
    $this->db->join('pharmacies u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_pharmacy_notifications_count($search){
    $this->db->from('pharmacy_notifications un');
    $this->db->join('pharmacies u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_pharmacies($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'pharmacy']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_pharmacy($user_id, $title, $message){
    $device = $this->db->get_where('pharmacies', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*pharmacy_notifications*/

/*diagnostic_notifications*/
public function get_diagnostic_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name', false);

    
    $this->db->from('diagnostic_notifications un');
    $this->db->join('diagnostics u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_diagnostic_notifications_count($search){
    $this->db->from('diagnostic_notifications un');
    $this->db->join('diagnostics u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_diagnostics($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'diagnostic_center']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_diagnostic($user_id, $title, $message){
    $device = $this->db->get_where('diagnostics', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*diagnostic_notifications*/

/*lab_test_notifications*/
public function get_lab_test_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name', false);

    
    $this->db->from('lab_test_notifications un');
    $this->db->join('lab_tests u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_lab_test_notifications_count($search){
    $this->db->from('lab_test_notifications un');
    $this->db->join('lab_tests u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_lab_tests($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'lab_center']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_lab_test($user_id, $title, $message){
    $device = $this->db->get_where('lab_tests', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*lab_test_notifications*/

/*lab_agent_notifications*/
public function get_lab_agent_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name,md.name as hospital_name', false);

    
    $this->db->from('lab_agent_notifications un');
    $this->db->join('lab_agents u', 'u.id = un.member_id', 'left');
    $this->db->join('lab_tests md', 'md.id = u.main_data_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_lab_agent_notifications_count($search){
    $this->db->from('lab_agent_notifications un');
    $this->db->join('lab_agents u', 'u.id = un.member_id', 'left');
    $this->db->join('lab_tests md', 'md.id = u.main_data_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('md.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_lab_agents($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'lab_agent']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_lab_agent($user_id, $title, $message){
    $device = $this->db->get_where('lab_agents', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*lab_agent_notifications*/

/*online_doctor_notifications*/
public function get_online_doctor_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name', false);

    
    $this->db->from('online_doctor_notifications un');
    $this->db->join('online_doctors u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_online_doctor_notifications_count($search){
    $this->db->from('online_doctor_notifications un');
    $this->db->join('online_doctors u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
// public function send_to_all_online_doctors($title, $message){
//     $content = [
//         "en" => $message
//     ];

//     $fields = [
//         'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
//         'included_segments' => ['Subscribed Users'], // or use filters below
//         'filters' => [
//             ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'online_doctor']
//         ],
//         'headings' => ["en" => $title],
//         'contents' => $content
//     ];

//     $this->send_push_request($fields);
// }
// public function send_to_single_online_doctor($user_id, $title, $message){
//     $device = $this->db->get_where('online_doctors', ['id' => $user_id])->row();

//     if ($device && $device->player_id) {
//         $content = ["en" => $message];

//         $fields = [
//             'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
//             'include_player_ids' => [$device->player_id],
//             'headings' => ["en" => $title],
//             'contents' => $content
//         ];

//         $this->send_push_request($fields);
//     }
// }
public function send_to_all_online_doctors($title, $message, $platform) {
    // OneSignal App IDs
    $android_app_id = 'cebaa375-de95-4fb8-9403-71089f304ffe';
    $ios_app_id     = 'f61be1d9-da0b-4daf-95d2-150f825a4087';

    $content = ["en" => $message];

    $fields = [
        'app_id' => ($platform === 'ios') ? $ios_app_id : $android_app_id,
        'included_segments' => ['Subscribed Users'],
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'online_doctor']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    //$this->send_push_request($fields);
    if($platform=='android'){
        $this->send_push_request($fields);
    }else{
        $this->send_push_request_online_doctor_ios($fields);
    }
}
public function send_to_single_online_doctor($doctor_id, $title, $message, $platform) {
    $android_app_id = 'cebaa375-de95-4fb8-9403-71089f304ffe';
    $ios_app_id     = 'f61be1d9-da0b-4daf-95d2-150f825a4087';

    $doctor = $this->db->get_where('online_doctors', ['id' => $doctor_id])->row();

    if (empty($doctor->player_id)) return;

    $content = ["en" => $message];

    $fields = [
        'app_id' => ($platform === 'ios') ? $ios_app_id : $android_app_id,
        'include_player_ids' => [$doctor->player_id],
        'headings' => ["en" => $title],
        'contents' => $content
    ];
    
    //print_r($fields);exit;
    
    if($platform=='android'){
        $this->send_push_request($fields);
    }else{
        $this->send_push_request_online_doctor_ios($fields);
    }
}

/*online_doctor_notifications*/

/*executive_notifications*/
public function get_executive_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name', false);

    
    $this->db->from('executive_notifications un');
    $this->db->join('executives u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_executive_notifications_count($search){
    $this->db->from('executive_notifications un');
    $this->db->join('executives u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_executives($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'executive']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_executive($user_id, $title, $message){
    $device = $this->db->get_where('executives', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*executive_notifications*/

/*regional_manager_notifications*/
public function get_regional_manager_notifications($limit, $start, $search){
    // Use CASE to show "All" when member_id is 'all'
    $this->db->select('un.*');
    $this->db->select('CASE WHEN un.member_id = "all" THEN "All" ELSE u.name END as name', false);

    
    $this->db->from('regional_manager_notifications un');
    $this->db->join('regional_managers u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Allow search on the virtual name "All"
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    $this->db->order_by('un.id', 'DESC');
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    return $query->result_array();
}
public function get_regional_manager_notifications_count($search){
    $this->db->from('regional_manager_notifications un');
    $this->db->join('regional_managers u', 'u.id = un.member_id', 'left');

    if (!empty($search)) {
        $this->db->group_start();
        $this->db->like('u.name', $search);
        $this->db->or_like('un.title', $search);
        $this->db->or_like('un.message', $search);

        // Also search for "All" if entered
        if (strtolower(trim($search)) === 'all') {
            $this->db->or_where('un.member_id', 'all');
        }

        $this->db->group_end();
    }

    return $this->db->count_all_results();
}
public function send_to_all_regional_managers($title, $message){
    $content = [
        "en" => $message
    ];

    $fields = [
        'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
        'included_segments' => ['Subscribed Users'], // or use filters below
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'regional_manager']
        ],
        'headings' => ["en" => $title],
        'contents' => $content
    ];

    $this->send_push_request($fields);
}
public function send_to_single_regional_manager($user_id, $title, $message){
    $device = $this->db->get_where('regional_managers', ['id' => $user_id])->row();

    if ($device && $device->player_id) {
        $content = ["en" => $message];

        $fields = [
            'app_id' => 'cebaa375-de95-4fb8-9403-71089f304ffe',
            'include_player_ids' => [$device->player_id],
            'headings' => ["en" => $title],
            'contents' => $content
        ];

        $this->send_push_request($fields);
    }
}
/*regional_manager_notifications*/

private function send_push_request($fields) {
    $fields = json_encode($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic os_v2_app_z25kg5o6svh3rfadoeej6mcp7y6ua2qygeoewimkum6gid4guz7bejfb7bpi3sfhqunafvh5tipyfwkrs77thwvap5q5bbkknd4jfdy'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

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

private function send_push_request_online_doctor_ios($fields) {
    $fields = json_encode($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic os_v2_app_6yn6dwo2bng27foscuhyewsaq4lpfrkfpveesbv5caghzfhdviu6tic6kseohgttjicmhlbk2xyksvql7aynav7qybilfgawqkvhfei'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);
    curl_close($ch);
}
/*notifications*/

/*payments*/
/*hospital_diagnostic_payments*/
public function get_hospital_diagnostic_revenue_summary($hospital_id, $start_date, $end_date){
    // Step 1: Get total diagnostic booking amount (created within date range and status booked/completed)
    $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']);
    $booking = $this->db->get()->row_array();

    $total_amount = isset($booking['total_amount']) ? (float) $booking['total_amount'] : 0;

    // Step 2: Get total transferred amount
    //$this->db->select('SUM(transferred_amount) as transferred_amount');
    //$this->db->from('hospital_diagnostic_payment_settlements');
    //$this->db->where('hospital_id', $hospital_id);
    // Uncomment below if settlements should be filtered by date range
    // $this->db->where('DATE(payment_date) >=', $start_date);
    // $this->db->where('DATE(payment_date) <=', $end_date);
    //$payment = $this->db->get()->row_array();

    //$transferred_amount = isset($payment['transferred_amount']) ? (float) $payment['transferred_amount'] : 0;

    // Step 3: Calculate pending amount (never negative)
    //$pending = max(0, $total_amount - $transferred_amount);

    // Step 4: Get hospital name
    $this->db->select('name');
    $this->db->from('main_data');
    $this->db->where('id', $hospital_id);
    $hospital = $this->db->get()->row_array();

    return [
        'hospital_id'        => $hospital_id,
        'hospital_name'      => $hospital['name'] ?? 'N/A',
        'total_amount'       => $total_amount,
        //'transferred_amount' => $transferred_amount,
        //'pending'            => $pending
    ];
}
/*hospital_diagnostic_payments*/
/*payments*/

/*booking_for_an_user*/
/*ambulance_booking*/
public function check_user_distance($lat1, $lon1, $lat2, $lon2) {
    $earthRadius = 6371; // Earth radius in KM

    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);

    $a = sin($dLat/2) * sin($dLat/2) +
         cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
         sin($dLon/2) * sin($dLon/2);

    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $distance = $earthRadius * $c; // KM

    return $distance; 
}
/*ambulance_booking*/

/*op_booking*/
public function get_hospital_specialities($hospital_id){
    $this->db->select('mds.id,mds.speciality_id,s.name')->from('main_data_specialities mds');
    $this->db->where(['mds.main_data_id' => $hospital_id,'mds.status' => 1,'mds.delete_status' => 1]);
    $this->db->join('specialities s','s.id=mds.speciality_id','left');
    $query = $this->db->get();
    return $query->result_array();
}
public function get_doctor_dates($main_data_id,$doctor_id) {
    $today = date('Y-m-d');

    $this->db->select('DISTINCT(date),doctors.offline_fee', false);
    $this->db->from('doctor_slots');
    $this->db->where('doctor_slots.main_data_id', $main_data_id);
    $this->db->where('doctor_slots.doctor_id', $doctor_id);
    $this->db->where('doctor_slots.date >=', $today);
    $this->db->where('doctor_slots.status', 1);
    $this->db->where('doctor_slots.delete_status', 1);
    $this->db->join('doctors','doctors.id=doctor_slots.doctor_id','left');
    $this->db->order_by('date', 'ASC');
    
    $query = $this->db->get();
    $result = $query->result_array();

    $dates = [];
    foreach ($result as $row) {
        $dates[] = [
            'date'         => $row['date'],
            'format_date'  => date('D d M Y', strtotime($row['date'])),
            'convert_date' => date('d-m-Y', strtotime($row['date'])),
            'offline_fee'  => $row['offline_fee']
        ];
    }

    return $dates;
}
public function get_doctor_slots($main_data_id, $doctor_id, $date) {
    $today = date('Y-m-d');
    $current_time_24hr = date('H:i');

    $this->db->select('id, time, session, booking_status, date');
    $this->db->from('doctor_slots');
    $this->db->where('main_data_id', $main_data_id);
    //$this->db->where('speciality_id', $speciality_id);
    $this->db->where('doctor_id', $doctor_id);
    $this->db->where('date', $date);
    $this->db->where('status', 1);
    $this->db->where('delete_status', 1);

    // Filter only future slots if date is today
    if ($date == $today) {
        $this->db->where("STR_TO_DATE(time, '%h:%i %p') >=", $current_time_24hr);
    }

    $this->db->order_by("STR_TO_DATE(time, '%h:%i %p')", "ASC", false);

    $query = $this->db->get();
    $raw_slots = $query->result_array();

    $slots = ['morning' => [], 'afternoon' => [], 'evening' => []];
    $added_times = []; // To avoid duplicates

    foreach ($raw_slots as $row) {
        $time_24hr = date('H:i', strtotime($row['time']));
        if (in_array($row['time'], $added_times)) continue; // prevent duplicates
        $added_times[] = $row['time'];

        $row['id'] = (int)$row['id'];
        $row['format_date'] = date('d M Y', strtotime($row['date']));

        if ($time_24hr >= 0 && $time_24hr < 12) {
            $slots['morning'][] = $row;
        } elseif ($time_24hr >= 12 && $time_24hr < 17) {
            $slots['afternoon'][] = $row;
        } else {
            $slots['evening'][] = $row;
        }
    }

    return $slots;
}
/*op_booking*/

/*doctor_booking*/
public function get_hospital_online_doctor_dates($main_data_id,$doctor_id) {
    $today = date('Y-m-d');

    $this->db->select('DISTINCT(date),doctors.online_fee', false);
    $this->db->from('doctor_slots');
    $this->db->where('doctor_slots.main_data_id', $main_data_id);
    $this->db->where('doctor_slots.doctor_id', $doctor_id);
    $this->db->where('doctor_slots.date >=', $today);
    $this->db->where('doctor_slots.status', 1);
    $this->db->where('doctor_slots.delete_status', 1);
    $this->db->join('doctors','doctors.id=doctor_slots.doctor_id','left');
    $this->db->order_by('date', 'ASC');
    
    $query = $this->db->get();
    $result = $query->result_array();

    $dates = [];
    foreach ($result as $row) {
        $dates[] = [
            'date'         => $row['date'],
            'format_date'  => date('D d M Y', strtotime($row['date'])),
            'convert_date' => date('d-m-Y', strtotime($row['date'])),
            'offline_fee'  => $row['online_fee']
        ];
    }

    return $dates;
}
/*doctor_booking*/

/*hospital_diagnostic_booking*/
public function get_hospital_diagnostic_tests_subtests($test_id) {
    // Step 1: Get package IDs
    $this->db->select("id");
    $this->db->from("hospital_diagnostic_packages");
    $this->db->where("id", $test_id);
    $this->db->where("status", 1);
    $this->db->where("delete_status", 1);
    $this->db->order_by("id", "desc");
    //$this->db->limit($limit, $offset);
    $package_query = $this->db->get();
    $package_ids = array_column($package_query->result_array(), 'id');

    if (empty($package_ids)) {
        return []; // No packages found
    }

    // Step 2: Get all related tests and sub-tests
    $this->db->select("
        hospital_diagnostic_packages.id AS package_id,
        hospital_diagnostic_packages.name,
        hospital_diagnostic_packages.image,
        hospital_diagnostic_packages.one_person,
        hospital_diagnostic_packages.one_person_discount,
        hospital_diagnostic_packages.report_in,
        hospital_diagnostic_packages.fasting,
        hospital_diagnostic_tests.id AS test_id,
        hospital_diagnostic_tests.name AS test_name,
        hospital_diagnostic_sub_tests.id AS sub_test_id,
        hospital_diagnostic_sub_tests.name AS sub_test_name
    ");
    $this->db->from('hospital_diagnostic_packages');
    $this->db->join('hospital_diagnostic_tests', 'hospital_diagnostic_tests.package_id = hospital_diagnostic_packages.id AND hospital_diagnostic_tests.main_data_id = hospital_diagnostic_packages.main_data_id AND hospital_diagnostic_tests.status = 1 AND hospital_diagnostic_tests.delete_status = 1', 'left');
    $this->db->join('hospital_diagnostic_sub_tests', 'hospital_diagnostic_sub_tests.test_id = hospital_diagnostic_tests.id AND hospital_diagnostic_sub_tests.package_id = hospital_diagnostic_tests.package_id AND hospital_diagnostic_sub_tests.main_data_id = hospital_diagnostic_tests.main_data_id AND hospital_diagnostic_sub_tests.status = 1 AND hospital_diagnostic_sub_tests.delete_status = 1', 'left');
    $this->db->where_in('hospital_diagnostic_packages.id', $package_ids);
    $this->db->where('hospital_diagnostic_packages.status', 1);
    $this->db->where('hospital_diagnostic_packages.delete_status', 1);
    $this->db->order_by('hospital_diagnostic_packages.id', 'desc');

    $query = $this->db->get();
    $result = $query->result_array();

    // Step 3: Process data
    $final_data = [];

    foreach ($result as $row) {
        $package_id = $row['package_id'];
        $test_id = $row['test_id'];
        $sub_test_id = $row['sub_test_id'];

        if (!isset($final_data[$package_id])) {
            $final_data[$package_id] = [
                'id' => intval($package_id),
                'name' => $row['name'],
                'image' => $row['image'],
                'one_person' => intval($row['one_person']),
                'one_person_discount' => intval($row['one_person_discount']),
                'report_in' => $row['report_in'],
                'fasting' => $row['fasting'],
                'tests' => []
            ];
        }

        if ($test_id && !isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id] = [
                'id' => intval($test_id),
                'name' => $row['test_name'],
                'sub_tests' => []
            ];
        }

        if ($sub_test_id && isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id]['sub_tests'][] = [
                'id' => intval($sub_test_id),
                'name' => $row['sub_test_name']
            ];
        }
    }

    // Convert associative test arrays to indexed
    foreach ($final_data as &$package) {
        $package['tests'] = array_values($package['tests']);
    }

    return array_values($final_data);
}
public function get_hospital_diagnostic_dates($main_data_id) {
    $today = date('Y-m-d');

    $this->db->select('DISTINCT(date)', false);
    $this->db->from('hospital_diagnostic_slots');
    $this->db->where('hospital_diagnostic_slots.main_data_id', $main_data_id);
    $this->db->where('hospital_diagnostic_slots.date >=', $today);
    $this->db->where('hospital_diagnostic_slots.status', 1);
    $this->db->where('hospital_diagnostic_slots.delete_status', 1);
    //$this->db->join('main_data','main_data.id=hospital_diagnostic_slots.main_data_id','left');
    $this->db->order_by('date', 'ASC');
    
    $query = $this->db->get();
    $result = $query->result_array();

    $dates = [];
    foreach ($result as $row) {
        $dates[] = [
            'date'          => $row['date'],
            'format_date'   => date('D d M Y', strtotime($row['date'])),
            'convert_date'  => date('d-m-Y', strtotime($row['date'])),
            'flat_discount' => 0
        ];
    }

    return $dates;
}
public function get_hospital_diagnostic_slots($main_data_id, $date) {
    $today = date('Y-m-d');
    $current_time_24hr = date('H:i');

    $this->db->select('id, time, session, booking_status, date');
    $this->db->from('hospital_diagnostic_slots');
    $this->db->where('main_data_id', $main_data_id);
    $this->db->where('date', $date);
    $this->db->where('status', 1);
    $this->db->where('delete_status', 1);

    // Filter only future slots if date is today
    if ($date == $today) {
        $this->db->where("STR_TO_DATE(time, '%h:%i %p') >=", $current_time_24hr);
    }

    $this->db->order_by("STR_TO_DATE(time, '%h:%i %p')", "ASC", false);

    $query = $this->db->get();
    $raw_slots = $query->result_array();

    $slots = ['morning' => [], 'afternoon' => [], 'evening' => []];
    $added_times = []; // To avoid duplicates

    foreach ($raw_slots as $row) {
        $time_24hr = date('H:i', strtotime($row['time']));
        if (in_array($row['time'], $added_times)) continue; // prevent duplicates
        $added_times[] = $row['time'];

        $row['id'] = (int)$row['id'];
        $row['format_date'] = date('d M Y', strtotime($row['date']));

        if ($time_24hr >= 0 && $time_24hr < 12) {
            $slots['morning'][] = $row;
        } elseif ($time_24hr >= 12 && $time_24hr < 17) {
            $slots['afternoon'][] = $row;
        } else {
            $slots['evening'][] = $row;
        }
    }

    return $slots;
}
public function get_single_hospital_diagnostic_tests($test_id){
    // Step 1: Get package IDs
    $this->db->select("id");
    $this->db->from("hospital_diagnostic_packages");
    $this->db->where("id", $test_id);
    /*$this->db->where("status", 1);
    $this->db->where("delete_status", 1);*/
    $this->db->order_by("id", "desc");
    //$this->db->limit($limit, $offset);
    $package_query = $this->db->get();
    $package_ids = array_column($package_query->result_array(), 'id');

    if (empty($package_ids)) {
        return []; // No packages found
    }

    // Step 2: Get all related tests and sub-tests
    $this->db->select("
        hospital_diagnostic_packages.id AS package_id,
        hospital_diagnostic_packages.name,
        hospital_diagnostic_packages.image,
        hospital_diagnostic_packages.one_person,
        hospital_diagnostic_packages.one_person_discount,
        hospital_diagnostic_packages.report_in,
        hospital_diagnostic_packages.fasting,
        hospital_diagnostic_tests.id AS test_id,
        hospital_diagnostic_tests.name AS test_name,
        hospital_diagnostic_sub_tests.id AS sub_test_id,
        hospital_diagnostic_sub_tests.name AS sub_test_name,
        main_data.location,
        main_data.lat,
        main_data.lon
    ");
    $this->db->from('hospital_diagnostic_packages');
    $this->db->join('hospital_diagnostic_tests', 'hospital_diagnostic_tests.package_id = hospital_diagnostic_packages.id AND hospital_diagnostic_tests.main_data_id = hospital_diagnostic_packages.main_data_id AND hospital_diagnostic_tests.status = 1 AND hospital_diagnostic_tests.delete_status = 1', 'left');
    $this->db->join('hospital_diagnostic_sub_tests', 'hospital_diagnostic_sub_tests.test_id = hospital_diagnostic_tests.id AND hospital_diagnostic_sub_tests.package_id = hospital_diagnostic_tests.package_id AND hospital_diagnostic_sub_tests.main_data_id = hospital_diagnostic_tests.main_data_id AND hospital_diagnostic_sub_tests.status = 1 AND hospital_diagnostic_sub_tests.delete_status = 1', 'left');
    $this->db->join('main_data','main_data.id=hospital_diagnostic_packages.main_data_id','left');
    $this->db->where_in('hospital_diagnostic_packages.id', $package_ids);
    $this->db->where('hospital_diagnostic_packages.id', $test_id);
    $this->db->where('hospital_diagnostic_packages.status', 1);
    $this->db->where('hospital_diagnostic_packages.delete_status', 1);
    $this->db->order_by('hospital_diagnostic_packages.id', 'desc');

    $query = $this->db->get();
    $result = $query->result_array();

    // Step 3: Process data
    $final_data = [];

    foreach ($result as $row) {
        $package_id = $row['package_id'];
        $test_id = $row['test_id'];
        $sub_test_id = $row['sub_test_id'];

        if (!isset($final_data[$package_id])) {
            $final_data[$package_id] = [
                'id' => intval($package_id),
                'name' => $row['name'],
                'image' => $row['image'],
                'one_person' => intval($row['one_person']),
                'one_person_discount' => intval($row['one_person_discount']),
                'report_in' => $row['report_in'],
                'fasting' => $row['fasting'],
                'location' => $row['location'],
                'lat' => $row['lat'],
                'lon' => $row['lon'],
                'tests' => []
            ];
        }

        if ($test_id && !isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id] = [
                'id' => intval($test_id),
                'name' => $row['test_name'],
                'sub_tests' => []
            ];
        }

        if ($sub_test_id && isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id]['sub_tests'][] = [
                'id' => intval($sub_test_id),
                'name' => $row['sub_test_name']
            ];
        }
    }

    // Convert associative test arrays to indexed
    foreach ($final_data as &$package) {
        $package['tests'] = array_values($package['tests']);
    }

    return array_values($final_data);
}
public function save_hospital_diagnostic_booking_snapshot($booking_id, $diagnostic_data) {
    foreach ($diagnostic_data as $package) {
        // 1. Insert into booking_diagnostic_packages
        $package_data = [
            'booking_id' => $booking_id,
            'name' => $package['name'],
            'image' => $package['image'],
            'one_person' => $package['one_person'],
            'one_person_discount' => $package['one_person_discount'],
            'report_in' => $package['report_in'],
            'fasting' => $package['fasting'],
            'location' => $package['location'],
            'created_on'    => date('Y-m-d H:i:s')
        ];
        $this->db->insert('hospital_diagnostic_booking_packages', $package_data);
        $booking_package_id = $this->db->insert_id();

        foreach ($package['tests'] as $test) {
            // 2. Insert into booking_diagnostic_tests
            $test_data = [
                'booking_id' => $booking_id,
                'booking_package_id' => $booking_package_id,
                'name' => $test['name'],
                'created_on'    => date('Y-m-d H:i:s')
            ];
            $this->db->insert('hospital_diagnostic_booking_tests', $test_data);
            $booking_test_id = $this->db->insert_id();

            foreach ($test['sub_tests'] as $sub_test) {
                // 3. Insert into booking_diagnostic_subtests
                $subtest_data = [
                    'booking_id' => $booking_id,
                    'booking_test_id' => $booking_test_id,
                    'name' => $sub_test['name'],
                    'created_on'    => date('Y-m-d H:i:s')
                ];
                $this->db->insert('hospital_diagnostic_booking_subtests', $subtest_data);
            }
        }
    }
}
/*hospital_diagnostic_booking*/

/*diagnostic_booking*/
public function get_diagnostic_tests_subtests($test_id) {
    // Step 1: Get package IDs
    $this->db->select("id");
    $this->db->from("diagnostic_packages");
    $this->db->where("id", $test_id);
    $this->db->where("status", 1);
    $this->db->where("delete_status", 1);
    $this->db->order_by("id", "desc");
    //$this->db->limit($limit, $offset);
    $package_query = $this->db->get();
    $package_ids = array_column($package_query->result_array(), 'id');

    if (empty($package_ids)) {
        return []; // No packages found
    }

    // Step 2: Get all related tests and sub-tests
    $this->db->select("
        diagnostic_packages.id AS package_id,
        diagnostic_packages.name,
        diagnostic_packages.image,
        diagnostic_packages.one_person,
        diagnostic_packages.one_person_discount,
        diagnostic_packages.report_in,
        diagnostic_packages.fasting,
        diagnostic_tests.id AS test_id,
        diagnostic_tests.name AS test_name,
        diagnostic_sub_tests.id AS sub_test_id,
        diagnostic_sub_tests.name AS sub_test_name
    ");
    $this->db->from('diagnostic_packages');
    $this->db->join('diagnostic_tests', 'diagnostic_tests.package_id = diagnostic_packages.id AND diagnostic_tests.main_data_id = diagnostic_packages.main_data_id AND diagnostic_tests.status = 1 AND diagnostic_tests.delete_status = 1', 'left');
    $this->db->join('diagnostic_sub_tests', 'diagnostic_sub_tests.test_id = diagnostic_tests.id AND diagnostic_sub_tests.package_id = diagnostic_tests.package_id AND diagnostic_sub_tests.main_data_id = diagnostic_tests.main_data_id AND diagnostic_sub_tests.status = 1 AND diagnostic_sub_tests.delete_status = 1', 'left');
    $this->db->where_in('diagnostic_packages.id', $package_ids);
    $this->db->where('diagnostic_packages.status', 1);
    $this->db->where('diagnostic_packages.delete_status', 1);
    $this->db->order_by('diagnostic_packages.id', 'desc');

    $query = $this->db->get();
    $result = $query->result_array();

    // Step 3: Process data
    $final_data = [];

    foreach ($result as $row) {
        $package_id = $row['package_id'];
        $test_id = $row['test_id'];
        $sub_test_id = $row['sub_test_id'];

        if (!isset($final_data[$package_id])) {
            $final_data[$package_id] = [
                'id' => intval($package_id),
                'name' => $row['name'],
                'image' => $row['image'],
                'one_person' => intval($row['one_person']),
                'one_person_discount' => intval($row['one_person_discount']),
                'report_in' => $row['report_in'],
                'fasting' => $row['fasting'],
                'tests' => []
            ];
        }

        if ($test_id && !isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id] = [
                'id' => intval($test_id),
                'name' => $row['test_name'],
                'sub_tests' => []
            ];
        }

        if ($sub_test_id && isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id]['sub_tests'][] = [
                'id' => intval($sub_test_id),
                'name' => $row['sub_test_name']
            ];
        }
    }

    // Convert associative test arrays to indexed
    foreach ($final_data as &$package) {
        $package['tests'] = array_values($package['tests']);
    }

    return array_values($final_data);
}
public function get_diagnostic_dates($main_data_id) {
    $today = date('Y-m-d');

    $this->db->select('DISTINCT(date),diagnostics.diagnostic_flat_discount', false);
    $this->db->from('diagnostic_slots');
    $this->db->where('diagnostic_slots.main_data_id', $main_data_id);
    $this->db->where('diagnostic_slots.date >=', $today);
    $this->db->where('diagnostic_slots.status', 1);
    $this->db->where('diagnostic_slots.delete_status', 1);
    $this->db->join('diagnostics','diagnostics.id=diagnostic_slots.main_data_id','left');
    $this->db->order_by('date', 'ASC');
    
    $query = $this->db->get();
    $result = $query->result_array();

    $dates = [];
    foreach ($result as $row) {
        $dates[] = [
            'date'          => $row['date'],
            'format_date'   => date('D d M Y', strtotime($row['date'])),
            'convert_date'  => date('d-m-Y', strtotime($row['date'])),
            'flat_discount' => $row['diagnostic_flat_discount']
        ];
    }

    return $dates;
}
public function get_diagnostic_slots($main_data_id, $date) {
    $today = date('Y-m-d');
    $current_time_24hr = date('H:i');

    $this->db->select('id, time, session, booking_status, date');
    $this->db->from('diagnostic_slots');
    $this->db->where('main_data_id', $main_data_id);
    $this->db->where('date', $date);
    $this->db->where('status', 1);
    $this->db->where('delete_status', 1);

    // Filter only future slots if date is today
    if ($date == $today) {
        $this->db->where("STR_TO_DATE(time, '%h:%i %p') >=", $current_time_24hr);
    }

    $this->db->order_by("STR_TO_DATE(time, '%h:%i %p')", "ASC", false);

    $query = $this->db->get();
    $raw_slots = $query->result_array();

    $slots = ['morning' => [], 'afternoon' => [], 'evening' => []];
    $added_times = []; // To avoid duplicates

    foreach ($raw_slots as $row) {
        $time_24hr = date('H:i', strtotime($row['time']));
        if (in_array($row['time'], $added_times)) continue; // prevent duplicates
        $added_times[] = $row['time'];

        $row['id'] = (int)$row['id'];
        $row['format_date'] = date('d M Y', strtotime($row['date']));

        if ($time_24hr >= 0 && $time_24hr < 12) {
            $slots['morning'][] = $row;
        } elseif ($time_24hr >= 12 && $time_24hr < 17) {
            $slots['afternoon'][] = $row;
        } else {
            $slots['evening'][] = $row;
        }
    }

    return $slots;
}
public function get_single_diagnostic_tests($test_id) {
    // Step 1: Get package IDs
    $this->db->select("id");
    $this->db->from("diagnostic_packages");
    $this->db->where("id", $test_id);
    /*$this->db->where("status", 1);
    $this->db->where("delete_status", 1);*/
    $this->db->order_by("id", "desc");
    //$this->db->limit($limit, $offset);
    $package_query = $this->db->get();
    $package_ids = array_column($package_query->result_array(), 'id');

    if (empty($package_ids)) {
        return []; // No packages found
    }

    // Step 2: Get all related tests and sub-tests
    $this->db->select("
        diagnostic_packages.id AS package_id,
        diagnostic_packages.name,
        diagnostic_packages.image,
        diagnostic_packages.one_person,
        diagnostic_packages.one_person_discount,
        diagnostic_packages.report_in,
        diagnostic_packages.fasting,
        diagnostic_tests.id AS test_id,
        diagnostic_tests.name AS test_name,
        diagnostic_sub_tests.id AS sub_test_id,
        diagnostic_sub_tests.name AS sub_test_name,
        diagnostics.location,
        diagnostics.lat,
        diagnostics.lon
    ");
    $this->db->from('diagnostic_packages');
    $this->db->join('diagnostic_tests', 'diagnostic_tests.package_id = diagnostic_packages.id AND diagnostic_tests.main_data_id = diagnostic_packages.main_data_id AND diagnostic_tests.status = 1 AND diagnostic_tests.delete_status = 1', 'left');
    $this->db->join('diagnostic_sub_tests', 'diagnostic_sub_tests.test_id = diagnostic_tests.id AND diagnostic_sub_tests.package_id = diagnostic_tests.package_id AND diagnostic_sub_tests.main_data_id = diagnostic_tests.main_data_id AND diagnostic_sub_tests.status = 1 AND diagnostic_sub_tests.delete_status = 1', 'left');
    $this->db->join('diagnostics','diagnostics.id=diagnostic_packages.main_data_id','left');
    $this->db->where_in('diagnostic_packages.id', $package_ids);
    $this->db->where('diagnostic_packages.id', $test_id);
    $this->db->where('diagnostic_packages.status', 1);
    $this->db->where('diagnostic_packages.delete_status', 1);
    $this->db->order_by('diagnostic_packages.id', 'desc');

    $query = $this->db->get();
    $result = $query->result_array();

    // Step 3: Process data
    $final_data = [];

    foreach ($result as $row) {
        $package_id = $row['package_id'];
        $test_id = $row['test_id'];
        $sub_test_id = $row['sub_test_id'];

        if (!isset($final_data[$package_id])) {
            $final_data[$package_id] = [
                'id' => intval($package_id),
                'name' => $row['name'],
                'image' => $row['image'],
                'one_person' => intval($row['one_person']),
                'one_person_discount' => intval($row['one_person_discount']),
                'report_in' => $row['report_in'],
                'fasting' => $row['fasting'],
                'location' => $row['location'],
                'lat'       => $row['lat'],
                'lon'       => $row['lon'],
                'tests' => []
            ];
        }

        if ($test_id && !isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id] = [
                'id' => intval($test_id),
                'name' => $row['test_name'],
                'sub_tests' => []
            ];
        }

        if ($sub_test_id && isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id]['sub_tests'][] = [
                'id' => intval($sub_test_id),
                'name' => $row['sub_test_name']
            ];
        }
    }

    // Convert associative test arrays to indexed
    foreach ($final_data as &$package) {
        $package['tests'] = array_values($package['tests']);
    }

    return array_values($final_data);
}
public function save_diagnostic_booking_snapshot($booking_id, $diagnostic_data) {
    foreach ($diagnostic_data as $package) {
        // 1. Insert into booking_diagnostic_packages
        $package_data = [
            'booking_id' => $booking_id,
            'name' => $package['name'],
            'image' => $package['image'],
            'one_person' => $package['one_person'],
            'one_person_discount' => $package['one_person_discount'],
            'report_in' => $package['report_in'],
            'fasting' => $package['fasting'],
            'location' => $package['location'],
            'created_on'    => date('Y-m-d H:i:s')
        ];
        $this->db->insert('diagnostic_booking_packages', $package_data);
        $booking_package_id = $this->db->insert_id();

        foreach ($package['tests'] as $test) {
            // 2. Insert into booking_diagnostic_tests
            $test_data = [
                'booking_id' => $booking_id,
                'booking_package_id' => $booking_package_id,
                'name' => $test['name'],
                'created_on'    => date('Y-m-d H:i:s')
            ];
            $this->db->insert('diagnostic_booking_tests', $test_data);
            $booking_test_id = $this->db->insert_id();

            foreach ($test['sub_tests'] as $sub_test) {
                // 3. Insert into booking_diagnostic_subtests
                $subtest_data = [
                    'booking_id' => $booking_id,
                    'booking_test_id' => $booking_test_id,
                    'name' => $sub_test['name'],
                    'created_on'    => date('Y-m-d H:i:s')
                ];
                $this->db->insert('diagnostic_booking_subtests', $subtest_data);
            }
        }
    }
}
/*diagnostic_booking*/

/*lab_test_booking*/
public function get_lab_tests_subtests($test_id) {
    // Step 1: Get package IDs
    $this->db->select("id");
    $this->db->from("lab_packages");
    $this->db->where("id", $test_id);
    $this->db->where("status", 1);
    $this->db->where("delete_status", 1);
    $this->db->order_by("id", "desc");
    //$this->db->limit($limit, $offset);
    $package_query = $this->db->get();
    $package_ids = array_column($package_query->result_array(), 'id');

    if (empty($package_ids)) {
        return []; // No packages found
    }

    // Step 2: Get all related tests and sub-tests
    $this->db->select("
        lab_packages.id AS package_id,
        lab_packages.name,
        lab_packages.image,
        lab_packages.one_person,
        lab_packages.one_person_discount,
        lab_packages.report_in,
        lab_packages.fasting,
        lab_package_tests.id AS test_id,
        lab_package_tests.name AS test_name,
        lab_sub_tests.id AS sub_test_id,
        lab_sub_tests.name AS sub_test_name
    ");
    $this->db->from('lab_packages');
    $this->db->join('lab_package_tests', 'lab_package_tests.package_id = lab_packages.id AND lab_package_tests.main_data_id = lab_packages.main_data_id AND lab_package_tests.status = 1 AND lab_package_tests.delete_status = 1', 'left');
    $this->db->join('lab_sub_tests', 'lab_sub_tests.test_id = lab_package_tests.id AND lab_sub_tests.package_id = lab_package_tests.package_id AND lab_sub_tests.main_data_id = lab_package_tests.main_data_id AND lab_sub_tests.status = 1 AND lab_sub_tests.delete_status = 1', 'left');
    $this->db->where_in('lab_packages.id', $package_ids);
    $this->db->where('lab_packages.status', 1);
    $this->db->where('lab_packages.delete_status', 1);
    $this->db->order_by('lab_packages.id', 'desc');

    $query = $this->db->get();
    $result = $query->result_array();

    // Step 3: Process data
    $final_data = [];

    foreach ($result as $row) {
        $package_id = $row['package_id'];
        $test_id = $row['test_id'];
        $sub_test_id = $row['sub_test_id'];

        if (!isset($final_data[$package_id])) {
            $final_data[$package_id] = [
                'id' => intval($package_id),
                'name' => $row['name'],
                'image' => $row['image'],
                'one_person' => intval($row['one_person']),
                'one_person_discount' => intval($row['one_person_discount']),
                'report_in' => $row['report_in'],
                'fasting' => $row['fasting'],
                'tests' => []
            ];
        }

        if ($test_id && !isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id] = [
                'id' => intval($test_id),
                'name' => $row['test_name'],
                'sub_tests' => []
            ];
        }

        if ($sub_test_id && isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id]['sub_tests'][] = [
                'id' => intval($sub_test_id),
                'name' => $row['sub_test_name']
            ];
        }
    }

    // Convert associative test arrays to indexed
    foreach ($final_data as &$package) {
        $package['tests'] = array_values($package['tests']);
    }

    return array_values($final_data);
}
public function get_lab_test_dates($main_data_id) {
    $today = date('Y-m-d');

    $this->db->select('DISTINCT(date),lab_tests.lab_test_flat_discount', false);
    $this->db->from('lab_test_slots');
    $this->db->where('lab_test_slots.main_data_id', $main_data_id);
    $this->db->where('lab_test_slots.date >=', $today);
    $this->db->where('lab_test_slots.status', 1);
    $this->db->where('lab_test_slots.delete_status', 1);
    $this->db->join('lab_tests','lab_tests.id=lab_test_slots.main_data_id','left');
    $this->db->order_by('date', 'ASC');
    
    $query = $this->db->get();
    $result = $query->result_array();

    $dates = [];
    foreach ($result as $row) {
        $dates[] = [
            'date'          => $row['date'],
            'format_date'   => date('D d M Y', strtotime($row['date'])),
            'convert_date'  => date('d-m-Y', strtotime($row['date'])),
            'flat_discount' => $row['lab_test_flat_discount']
        ];
    }

    return $dates;
}
public function get_lab_test_slots($main_data_id, $date) {
    $today = date('Y-m-d');
    $current_time_24hr = date('H:i');

    $this->db->select('id, time, session, booking_status, date');
    $this->db->from('lab_test_slots');
    $this->db->where('main_data_id', $main_data_id);
    $this->db->where('date', $date);
    $this->db->where('status', 1);
    $this->db->where('delete_status', 1);

    // Filter only future slots if date is today
    if ($date == $today) {
        $this->db->where("STR_TO_DATE(time, '%h:%i %p') >=", $current_time_24hr);
    }

    $this->db->order_by("STR_TO_DATE(time, '%h:%i %p')", "ASC", false);

    $query = $this->db->get();
    $raw_slots = $query->result_array();

    $slots = ['morning' => [], 'afternoon' => [], 'evening' => []];
    $added_times = []; // To avoid duplicates

    foreach ($raw_slots as $row) {
        $time_24hr = date('H:i', strtotime($row['time']));
        if (in_array($row['time'], $added_times)) continue; // prevent duplicates
        $added_times[] = $row['time'];

        $row['id'] = (int)$row['id'];
        $row['format_date'] = date('d M Y', strtotime($row['date']));

        if ($time_24hr >= 0 && $time_24hr < 12) {
            $slots['morning'][] = $row;
        } elseif ($time_24hr >= 12 && $time_24hr < 17) {
            $slots['afternoon'][] = $row;
        } else {
            $slots['evening'][] = $row;
        }
    }

    return $slots;
}
public function get_single_lab_test($test_id) {
    // Step 1: Get package IDs
    $this->db->select("id");
    $this->db->from("lab_packages");
    $this->db->where("id", $test_id);
    /*$this->db->where("status", 1);
    $this->db->where("delete_status", 1);*/
    $this->db->order_by("id", "desc");
    //$this->db->limit($limit, $offset);
    $package_query = $this->db->get();
    $package_ids = array_column($package_query->result_array(), 'id');

    if (empty($package_ids)) {
        return []; // No packages found
    }

    // Step 2: Get all related tests and sub-tests
    $this->db->select("
        lab_packages.id AS package_id,
        lab_packages.name,
        lab_packages.image,
        lab_packages.one_person,
        lab_packages.one_person_discount,
        lab_packages.report_in,
        lab_packages.fasting,
        lab_package_tests.id AS test_id,
        lab_package_tests.name AS test_name,
        lab_sub_tests.id AS sub_test_id,
        lab_sub_tests.name AS sub_test_name,
        lab_tests.location
    ");
    $this->db->from('lab_packages');
    $this->db->join('lab_package_tests', 'lab_package_tests.package_id = lab_packages.id AND lab_package_tests.main_data_id = lab_packages.main_data_id AND lab_package_tests.status = 1 AND lab_package_tests.delete_status = 1', 'left');
    $this->db->join('lab_sub_tests', 'lab_sub_tests.test_id = lab_package_tests.id AND lab_sub_tests.package_id = lab_package_tests.package_id AND lab_sub_tests.main_data_id = lab_package_tests.main_data_id AND lab_sub_tests.status = 1 AND lab_sub_tests.delete_status = 1', 'left');
    $this->db->join('lab_tests','lab_tests.id=lab_packages.main_data_id','left');
    $this->db->where_in('lab_packages.id', $package_ids);
    $this->db->where('lab_packages.id', $test_id);
    $this->db->where('lab_packages.status', 1);
    $this->db->where('lab_packages.delete_status', 1);
    $this->db->order_by('lab_packages.id', 'desc');

    $query = $this->db->get();
    $result = $query->result_array();

    // Step 3: Process data
    $final_data = [];

    foreach ($result as $row) {
        $package_id = $row['package_id'];
        $test_id = $row['test_id'];
        $sub_test_id = $row['sub_test_id'];

        if (!isset($final_data[$package_id])) {
            $final_data[$package_id] = [
                'id' => intval($package_id),
                'name' => $row['name'],
                'image' => $row['image'],
                'one_person' => intval($row['one_person']),
                'one_person_discount' => intval($row['one_person_discount']),
                'report_in' => $row['report_in'],
                'fasting' => $row['fasting'],
                'location' => $row['location'],
                'tests' => []
            ];
        }

        if ($test_id && !isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id] = [
                'id' => intval($test_id),
                'name' => $row['test_name'],
                'sub_tests' => []
            ];
        }

        if ($sub_test_id && isset($final_data[$package_id]['tests'][$test_id])) {
            $final_data[$package_id]['tests'][$test_id]['sub_tests'][] = [
                'id' => intval($sub_test_id),
                'name' => $row['sub_test_name']
            ];
        }
    }

    // Convert associative test arrays to indexed
    foreach ($final_data as &$package) {
        $package['tests'] = array_values($package['tests']);
    }

    return array_values($final_data);
}
public function save_lab_test_booking_snapshot($booking_id, $lab_test_data) {
    foreach ($lab_test_data as $package) {
        // 1. Insert into booking_diagnostic_packages
        $package_data = [
            'booking_id' => $booking_id,
            'name' => $package['name'],
            'image' => $package['image'],
            'one_person' => $package['one_person'],
            'one_person_discount' => $package['one_person_discount'],
            'report_in' => $package['report_in'],
            'fasting' => $package['fasting'],
            'location' => $package['location'],
            'created_on'    => date('Y-m-d H:i:s')
        ];
        $this->db->insert('lab_test_booking_packages', $package_data);
        $booking_package_id = $this->db->insert_id();

        foreach ($package['tests'] as $test) {
            // 2. Insert into booking_diagnostic_tests
            $test_data = [
                'booking_id' => $booking_id,
                'booking_package_id' => $booking_package_id,
                'name' => $test['name'],
                'created_on'    => date('Y-m-d H:i:s')
            ];
            $this->db->insert('lab_test_booking_tests', $test_data);
            $booking_test_id = $this->db->insert_id();

            foreach ($test['sub_tests'] as $sub_test) {
                // 3. Insert into booking_diagnostic_subtests
                $subtest_data = [
                    'booking_id' => $booking_id,
                    'booking_test_id' => $booking_test_id,
                    'name' => $sub_test['name'],
                    'created_on'    => date('Y-m-d H:i:s')
                ];
                $this->db->insert('lab_test_booking_subtests', $subtest_data);
            }
        }
    }
}
/*lab_test_booking*/

/*online_doctor_booking*/
public function get_online_doctor_dates($doctor_id){
    $today = date('Y-m-d');

    $this->db->select('DISTINCT(date),online_doctors.fee', false);
    $this->db->from('online_doctor_slots');
    //$this->db->where('speciality_id', $speciality_id);
    $this->db->where('online_doctor_slots.doctor_id', $doctor_id);
    $this->db->where('online_doctor_slots.date >=', $today);
    $this->db->where('online_doctor_slots.status', 1);
    $this->db->where('online_doctor_slots.delete_status', 1);
    $this->db->join('online_doctors','online_doctors.id=online_doctor_slots.doctor_id','left');
    $this->db->order_by('date', 'ASC');
    
    $query = $this->db->get();
    $result = $query->result_array();

    // Format the dates
    $dates = array_map(function($row) {
        return [
            'date' => $row['date'],
            'format_date' => date('D d M', strtotime($row['date'])),
            'convert_date' => date('d-m-Y', strtotime($row['date'])),
            'offline_fee'  => $row['fee']
        ];
    }, $result);

    return $dates;
}
public function get_online_doctor_slots($doctor_id, $date) {
    $today = date('Y-m-d');
    $current_time_24hr = date('H:i');

    $this->db->select('id, time, session, booking_status, date');
    $this->db->from('online_doctor_slots');
    $this->db->where('doctor_id', $doctor_id);
    //$this->db->where('speciality_id', $speciality_id);
    $this->db->where('doctor_id', $doctor_id);
    $this->db->where('date', $date);
    $this->db->where('status', 1);
    $this->db->where('delete_status', 1);

    // Filter only future slots if date is today
    if ($date == $today) {
        $this->db->where("STR_TO_DATE(time, '%h:%i %p') >=", $current_time_24hr);
    }

    $this->db->order_by("STR_TO_DATE(time, '%h:%i %p')", "ASC", false);

    $query = $this->db->get();
    $raw_slots = $query->result_array();

    $slots = ['morning' => [], 'afternoon' => [], 'evening' => []];
    $added_times = []; // To avoid duplicates

    foreach ($raw_slots as $row) {
        $time_24hr = date('H:i', strtotime($row['time']));
        if (in_array($row['time'], $added_times)) continue; // prevent duplicates
        $added_times[] = $row['time'];

        $row['id'] = (int)$row['id'];
        $row['format_date'] = date('d M Y', strtotime($row['date']));

        if ($time_24hr >= 0 && $time_24hr < 12) {
            $slots['morning'][] = $row;
        } elseif ($time_24hr >= 12 && $time_24hr < 17) {
            $slots['afternoon'][] = $row;
        } else {
            $slots['evening'][] = $row;
        }
    }

    return $slots;
}
/*online_doctor_booking*/
/*booking_for_an_user*/

}
?>