<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

if (!function_exists('success')) {

    function success($message)
    {
        $ci = &get_instance();
        $ci->session->set_userdata('success', $message);
        return true;
    }
}


if (!function_exists('error')) {

    function error($message)
    {
        $ci = &get_instance();
        $ci->session->set_userdata('error', $message);
        return true;
    }
}

if (!function_exists('calculate_age')) {
    function calculate_age($dob) {
        if (!$dob) {
            return '';
        }
        
        $birth = new DateTime($dob);
        $today = new DateTime();
        
        $diff = $birth->diff($today);
        
        $age = '';
        if ($diff->y > 0) {
            $age .= $diff->y . ' yrs ';
        }
        if ($diff->m > 0) {
            $age .= $diff->m . ' month ';
        }
        if ($diff->d > 0) {
            $age .= $diff->d . ' days';
        }
        
        return trim($age);
    }
} 

if (!function_exists('warning')) {

    function warning($message)
    {
        $ci = &get_instance();
        $ci->session->set_userdata('warning', $message);
        return true;
    }
}

if (!function_exists('info')) {

    function info($message)
    {
        $ci = &get_instance();
        $ci->session->set_userdata('info', $message);
        return true;
    }
}

if (!function_exists('logged_in_user_id')) {

    function logged_in_user_id()
    {
        $logged_in_id = 0;
        $ci = &get_instance();
        if ($ci->session->userdata('user_id') && $ci->session->userdata('role_id')) :
            $logged_in_id = $ci->session->userdata('user_id');
        endif;
        return $logged_in_id;
    }
}

if (!function_exists('logged_in_role_id')) {

    function logged_in_role_id()
    {
        $logged_in_role_id = 0;
        $ci = &get_instance();
        if ($ci->session->userdata('role_id')) :
            $logged_in_role_id = $ci->session->userdata('role_id');
        endif;
        return $logged_in_role_id;
    }
}

if (!function_exists('get_http')) {

    function get_http($url)
    {
        if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
            // If not exist then add http 
            $url = "http://" . $url;
        }
        return $url;
    }
}

if (!function_exists('get_slug')) {

    function get_slug($slug)
    {
        if (!$slug) {
            return;
        }

        $char = array("!", "â€™", "'", ":", ",", "_", "`", "~", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "=", "{", "}", "[", "]", "/", ";", '"', '<', '>', '?', "'\'");
        $slug = str_replace($char, "", $slug);
        $str = strtolower(str_replace(' ', "-", $slug));
        return $str;
    }
}

if (!function_exists('get_status')) {

    function get_status($status)
    {
        $ci = &get_instance();
        if ($status == 1) {
            return $ci->lang->line('active');
        } elseif ($status == 2) {
            return $ci->lang->line('in_active');
        } elseif ($status == 3) {
            return $ci->lang->line('trash');
        }
    }
}

if (!function_exists('verify_email_format')) {

    function verify_email_format($email)
    {
        $email = trim($email);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return '';
        } else {
            return $email;
        }
    }
}

if (!function_exists('get_user_by_role')) {

    function get_user_by_role($role_id, $user_id)
    {

        $ci = &get_instance();

        if ($role_id == SUPER_ADMIN) {
            $ci->db->select('E.*, D.name as department, DE.name as designation, U.username, U.temp_password as password, U.role_id');
            $ci->db->from('employees AS E');
            $ci->db->join('departments AS D', 'D.id = E.department_id', 'left');
            $ci->db->join('designations AS DE', 'DE.id = E.designation_id', 'left');
            $ci->db->join('users AS U', 'U.id = E.user_id', 'left');
            $ci->db->join('roles AS R', 'R.id = U.role_id', 'left');
            $ci->db->where('E.user_id', $user_id);
            return $ci->db->get()->row();
        } elseif ($role_id == PATIENT) {
            $ci->db->select('P.*, U.username, U.temp_password as password, U.role_id');
            $ci->db->from('patients AS P');
            $ci->db->join('users AS U', 'U.id = P.user_id', 'left');
            $ci->db->join('roles AS R', 'R.id = U.role_id', 'left');
            $ci->db->where('P.user_id', $user_id);
            return $ci->db->get()->row();
        } else {
            $ci->db->select('E.*, D.name as department, DE.name as designation, U.username, U.temp_password as password, U.role_id, U.device_id');
            $ci->db->from('employees AS E');
            $ci->db->join('departments AS D', 'D.id = E.department_id', 'left');
            $ci->db->join('designations AS DE', 'DE.id = E.designation_id', 'left');
            $ci->db->join('users AS U', 'U.id = E.user_id', 'left');
            $ci->db->join('roles AS R', 'R.id = U.role_id', 'left');
            $ci->db->where('E.user_id', $user_id);
            return $ci->db->get()->row();
        }
        $ci->db->last_query();
    }
}

if (!function_exists('get_user_by_id')) {

    function get_user_by_id($user_id)
    {

        $ci = &get_instance();

        $ci->db->select('U.id, U.role_id');
        $ci->db->from('users AS U');
        $ci->db->where('U.id', $user_id);
        $user = $ci->db->get()->row();

        if ($user->role_id == SUPER_ADMIN) {
            $ci->db->select('E.*, U.username, U.temp_password as password, U.role_id, U.device_id');
            $ci->db->from('employees AS E');
            $ci->db->join('users AS U', 'U.id = E.user_id', 'left');
            $ci->db->join('roles AS R', 'R.id = U.role_id', 'left');
            $ci->db->where('E.user_id', $user_id);
            return $ci->db->get()->row();
        } elseif ($user->role_id == PATIENT) {
            $ci->db->select('P.*, U.username, U.temp_password as password, U.role_id');
            $ci->db->from('patients AS P');
            $ci->db->join('users AS U', 'U.id = P.user_id', 'left');
            $ci->db->join('roles AS R', 'R.id = U.role_id', 'left');
            $ci->db->where('P.user_id', $user_id);
            return $ci->db->get()->row();
        } else {
            $ci->db->select('E.*, U.username, U.temp_password as password, U.role_id, U.device_id');
            $ci->db->from('employees AS E');
            $ci->db->join('users AS U', 'U.id = E.user_id', 'left');
            $ci->db->join('roles AS R', 'R.id = U.role_id', 'left');
            $ci->db->where('E.user_id', $user_id);
            return $ci->db->get()->row();
        }
    }
}


if (!function_exists('get_template_tags')) {

    function get_template_tags($role_id, $type = null)
    {
        $tags = array();
        $tags[] = '[name]';
        $tags[] = '[phone]';

        if ($role_id == PATIENT && $type === 'appointment') {
            $tags[] = '[doctor]';
            $tags[] = '[reference]';
            $tags[] = '[appointment_no]';
            $tags[] = '[serial_no]';
            $tags[] = '[date]';
            $tags[] = '[gender]';
            $tags[] = '[address]';
            $tags[] = '[note]';
            $tags[] = '[appointment_status]';
            $tags[] = '[source]';
            $tags[] = '[created_by]';
        } elseif ($role_id == PATIENT && $type === 'ipd_admission') {
            $tags[] = '[gender]';
            $tags[] = '[address]';
            $tags[] = '[doctor]';
            $tags[] = '[reference]';
            $tags[] = '[ipd_no]';
            $tags[] = '[registration_no]';
            $tags[] = '[admission_date]';
            $tags[] = '[discharged_date]';
            $tags[] = '[bed]';
            $tags[] = '[remark]';
            $tags[] = '[created_by]';
        } elseif ($role_id == PATIENT && $type === 'ipd_discharged') {
            $tags[] = '[gender]';
            $tags[] = '[address]';
            $tags[] = '[doctor]';
            $tags[] = '[reference]';
            $tags[] = '[ipd_no]';
            $tags[] = '[registration_no]';
            $tags[] = '[admission_date]';
            $tags[] = '[discharged_date]';
            $tags[] = '[bed]';
            $tags[] = '[remark]';
            $tags[] = '[created_by]';
        } elseif ($role_id == PATIENT && $type === 'ipd_payment') {
            $tags[] = '[gender]';
            $tags[] = '[address]';
            $tags[] = '[invoice_no]';
            $tags[] = '[payment_date]';
            $tags[] = '[amount]';
            $tags[] = '[note]';
            $tags[] = '[payment_status]';
            $tags[] = '[created_by]';
        } elseif ($role_id == PATIENT && $type === 'billing_sms') {
            $tags[] = '[gender]';
            $tags[] = '[address]';
            $tags[] = '[doctor]';
            $tags[] = '[reference]';
            $tags[] = '[invoice_no]';
            $tags[] = '[bill_date]';
            $tags[] = '[total_bill]';
            $tags[] = '[discount]';
            $tags[] = '[net_payable]';
            $tags[] = '[advanced]';
            $tags[] = '[due_amount]';
            $tags[] = '[paid_status]';
            $tags[] = '[created_by]';
        } elseif ($role_id == PATIENT && $type === 'billing_payment_sms') {
            $tags[] = '[gender]';
            $tags[] = '[address]';
            $tags[] = '[doctor]';
            $tags[] = '[reference]';
            $tags[] = '[invoice_no]';
            $tags[] = '[bill_date]';
            $tags[] = '[payment_date]';
            $tags[] = '[total_bill]';
            $tags[] = '[discount]';
            $tags[] = '[net_payable]';
            $tags[] = '[advanced]';
            $tags[] = '[due_amount]';
            $tags[] = '[paid_status]';
            $tags[] = '[amount]';
            $tags[] = '[second_less]';
            $tags[] = '[created_by]';
        } elseif ($role_id == PATIENT && $type === 'investigation_payment_sms') {
            $tags[] = '[gender]';
            $tags[] = '[address]';
            $tags[] = '[doctor]';
            $tags[] = '[reference]';
            $tags[] = '[invoice_no]';
            $tags[] = '[bill_date]';
            $tags[] = '[payment_date]';
            $tags[] = '[total_bill]';
            $tags[] = '[discount]';
            $tags[] = '[net_payable]';
            $tags[] = '[advanced]';
            $tags[] = '[due_amount]';
            $tags[] = '[paid_status]';
            $tags[] = '[commission_amount]';
            $tags[] = '[payable_amount]';
            $tags[] = '[due_amount]';
            $tags[] = '[payment_date]';
            $tags[] = '[delivery_date]';
            $tags[] = '[created_by]';
        } elseif ($role_id == PATIENT) {
            $tags[] = '[patient_unique_id]';
            $tags[] = '[email]';
            $tags[] = '[address]';
            $tags[] = '[gender]';
        } elseif ($role_id == SUPER_ADMIN) {
            $tags[] = '[designation]';
            $tags[] = '[gender]';
            $tags[] = '[blood_group]';
            $tags[] = '[religion]';
            $tags[] = '[dob]';
        } elseif ($role_id == DOCTOR) {
            $tags[] = '[department]';
            $tags[] = '[designation]';
            $tags[] = '[specialist]';
            $tags[] = '[email]';
            $tags[] = '[gender]';
            $tags[] = '[blood_group]';
            $tags[] = '[religion]';
            $tags[] = '[dob]';
            $tags[] = '[device_id]';
        } else {
            $tags[] = '[email]';
            $tags[] = '[gender]';
            $tags[] = '[department]';
            $tags[] = '[designation]';
            $tags[] = '[blood_group]';
            $tags[] = '[religion]';
            $tags[] = '[dob]';
            $tags[] = '[device_id]';
        }

        return $tags;
    }
}


if (!function_exists('get_formatted_body')) {

    function get_formatted_body($body, $role_id, $user_id)
    {

        $tags = get_template_tags($role_id, null);
        $user = get_user_by_role($role_id, $user_id);
        $arr = array('[', ']');
        foreach ($tags as $tag) {
            $field = str_replace($arr, '', $tag);
            if ($field == 'created_at') {
                $body = str_replace($tag, date('M-d-Y', strtotime($user->created_at)), $body);
            } else {
                $body  = str_replace($tag, $user->{$field}, $body);
                $body  = str_replace('[password]', base64_decode($user->password), $body);
            }
        }
        return $body;
    }
}

if (!function_exists('get_blood_group')) {

    function get_blood_group()
    {
        $ci = &get_instance();
        return array(
            'a_positive' => $ci->lang->line('a_positive'),
            'a_negative' => $ci->lang->line('a_negative'),
            'b_positive' => $ci->lang->line('b_positive'),
            'b_negative' => $ci->lang->line('b_negative'),
            'o_positive' => $ci->lang->line('o_positive'),
            'o_negative' => $ci->lang->line('o_negative'),
            'ab_positive' => $ci->lang->line('ab_positive'),
            'ab_negative' => $ci->lang->line('ab_negative'),
        );
    }
}
if (!function_exists('get_religion')) {

    function get_religion()
    {
        $ci = &get_instance();
        return array(
            'islam' => $ci->lang->line('islam'),
            'hindu' => $ci->lang->line('hindu'),
            'buddha' => $ci->lang->line('buddha'),
            'christian' => $ci->lang->line('christian'),
            'other' => $ci->lang->line('other'),
        );
    }
}

if (!function_exists('get_visitor_profession')) {

    function get_visitor_profession()
    {
        $ci = &get_instance();
        return array(
            'ডাক্তার' => 'ডাক্তার',
            'ধাত্রী' => 'ধাত্রী',
            'মেম্বর' => 'মেম্বর',
            'চেয়ারম্যান' => 'চেয়ারম্যান',
            'ইমাম' => 'ইমাম',
            'মুয়াজ্জিন' => 'মুয়াজ্জিন',
            'শিক্ষক' => 'শিক্ষক',
            'কৃষক' => 'কৃষক',
            'মৎস্যজীবী' => 'মৎস্যজীবী',
            'সরকারী চাকুরিজীবী' => 'সরকারী চাকুরিজীবী',
            'কোম্পানি চাকুরিজীবী' => 'কোম্পানি চাকুরিজীবী',
            'ব্লাড ফাউন্ডেশন' => 'ব্লাড ফাউন্ডেশন',
            'সাস্থ্য কর্মী' => 'সাস্থ্য কর্মী',
            'ব্যাবসায়ী' => 'ব্যাবসায়ী',
            'গৃহিনী' => 'গৃহিনী',
            'শিক্ষার্থী' => 'শিক্ষার্থী',
            'অন্যান্য' => 'অন্যান্য',
        );
    }
}

if (!function_exists('get_visitor_emergency_treatment')) {

    function get_visitor_emergency_treatment()
    {
        $ci = &get_instance();
        return array(
            'মেডিসিন' => 'মেডিসিন',
            'মেডিসিন & কার্ডিওলজি বিশেষজ্ঞ' => 'মেডিসিন & কার্ডিওলজি বিশেষজ্ঞ',
            'নিউরো মেডিসিন' => 'নিউরো মেডিসিন',
            'অর্থোপেডিক সার্জারি' => 'অর্থোপেডিক সার্জারি',
            'গাইনী' => 'গাইনী',
            'বক্ষব্যাধি' => 'বক্ষব্যাধি',
            'চর্ম যৌন এলার্জি' => 'চর্ম যৌন এলার্জি',
            'শিশু মেডিসিন' => 'শিশু মেডিসিন',
            'চক্ষু ও ফ্যাকো সার্জারি' => 'চক্ষু ও ফ্যাকো সার্জারি',
            'নাক কান গলা' => 'নাক কান গলা',
            'কিডনি ও ইউরোলজি' => 'কিডনি ও ইউরোলজি',
            'জেনারেল সার্জারি ও ল্যাপারোস্কোপিক সার্জারি' => 'জেনারেল সার্জারি ও ল্যাপারোস্কোপিক সার্জারি',
            'ডায়াবেটিস থাইরয়েড ও হরমোন' => 'ডায়াবেটিস থাইরয়েড ও হরমোন',
            'নেফ্রোলজি ও কিডনি' => 'নেফ্রোলজি ও কিডনি',
            'সনোলজিস্ট ও আল্ট্রাসাউন্ড' => 'সনোলজিস্ট ও আল্ট্রাসাউন্ড',
        );
    }
}

if (!function_exists('get_visitor_health_package')) {

    function get_visitor_health_package()
    {
        $ci = &get_instance();
        return array(
            'হার্টের চেকাআপ' => 'হার্টের চেকাআপ',
            'ডায়াবেটিস চেকাআপ' => 'ডায়াবেটিস চেকাআপ',
            'কিডনি চেকআপ' => 'কিডনি চেকআপ',
            'প্রেগন্যান্সি চেকআপ' => 'প্রেগন্যান্সি চেকআপ',
            'লিভার চেকআপ' => 'লিভার চেকআপ',
            'থাইরয়েড চেকআপ' => 'থাইরয়েড চেকআপ',
            'বিদেশগামীদের স্বাস্থ্য চেকআপ' => 'বিদেশগামীদের স্বাস্থ্য চেকআপ',
            'ক্যান্সার চেকআপ(মহিলা)' => 'ক্যান্সার চেকআপ(মহিলা)',
            'ক্যান্সার চেকআপ(পুরুষ)' => 'ক্যান্সার চেকআপ(পুরুষ)',
            'মহিলাদের স্বাস্থ্য চেকআপ' => 'মহিলাদের স্বাস্থ্য চেকআপ',
            'শিশুদের স্বাস্থ্য চেকআপ' => 'শিশুদের স্বাস্থ্য চেকআপ',
            'মাদকাসক্তদের স্বাস্থ্য চেকআপ' => 'মাদকাসক্তদের স্বাস্থ্য চেকআপ',
        );
    }
}

if (!function_exists('get_visitor_operation')) {

    function get_visitor_operation()
    {
        $ci = &get_instance();
        return array(
            'নরমাল ডেলিভারি' => 'নরমাল ডেলিভারি',
            'সিজারিয়ান অপারেশন' => 'সিজারিয়ান অপারেশন',
            'এ্যাপেন্ডিসাইড' => 'এ্যাপেন্ডিসাইড',
            'জরায়ু অপারেশন' => 'জরায়ু অপারেশন',
            'হার্নিয়া অপারেশন' => 'হার্নিয়া অপারেশন',
            'হাইড্রোসিন অপারেশন' => 'হাইড্রোসিন অপারেশন',
            'পিত্তথলির পাথার' => 'পিত্তথলির পাথার',
            'নাক-কান-গাল অপারেশন' => 'নাক-কান-গাল অপারেশন',
            'হাড়ের অপারেশন' => 'হাড়ের অপারেশন',
            'চোখের অপারেশন' => 'চোখের অপারেশন',
            'পাইলস ফিষ্টুলা অপারেশন' => 'পাইলস ফিষ্টুলা অপারেশন',
            'টিউমার অপারেশন' => 'টিউমার অপারেশন',
            'অন্যান্য অপারেশন' => 'অন্যান্য অপারেশন',
        );
    }
}

if (!function_exists('get_visitor_test')) {

    function get_visitor_test()
    {
        $ci = &get_instance();
        return array(
            'প্যাথলজি' => 'প্যাথলজি',
            'আল্ট্রাসনো' => 'আল্ট্রাসনো',
            'এক্স-রে' => 'এক্স-রে',
            'ইসিজি' => 'ইসিজি',
            'ইকো' => 'ইকো',
        );
    }
}

if (!function_exists('get_marital_status')) {

    function get_marital_status()
    {
        $ci = &get_instance();
        return array(
            'single' => $ci->lang->line('single'),
            'married' => $ci->lang->line('married'),
            'widowed' => $ci->lang->line('widowed'),
            'separated' => $ci->lang->line('separated'),
            'divorced' => $ci->lang->line('divorced'),
            'other' => $ci->lang->line('other'),
        );
    }
}

if (!function_exists('get_visitor_reasons')) {

    function get_visitor_reasons()
    {
        $ci = &get_instance();
        return array(
            'vendor' => $ci->lang->line('vendor'),
            'guardian' => $ci->lang->line('guardian'),
            'relative' => $ci->lang->line('relative'),
            'friend' => $ci->lang->line('friend'),
            'family' => $ci->lang->line('family'),
            'interview' => $ci->lang->line('interview'),
            'meeting' => $ci->lang->line('meeting'),
            'other' => $ci->lang->line('other'),
        );
    }
}


if (!function_exists('get_week_days')) {

    function get_week_days()
    {
        $ci = &get_instance();
        return array(
            'saturday' => $ci->lang->line('saturday'),
            'sunday' => $ci->lang->line('sunday'),
            'monday' => $ci->lang->line('monday'),
            'tuesday' => $ci->lang->line('tuesday'),
            'wednesday' => $ci->lang->line('wednesday'),
            'thursday' => $ci->lang->line('thursday'),
            'friday' => $ci->lang->line('friday'),
        );
    }
}

if (!function_exists('get_months')) {

    function get_months()
    {
        $ci = &get_instance();
        return array(
            'january' => $ci->lang->line('january'),
            'february' => $ci->lang->line('february'),
            'march' => $ci->lang->line('march'),
            'april' => $ci->lang->line('april'),
            'may' => $ci->lang->line('may'),
            'june' => $ci->lang->line('june'),
            'july' => $ci->lang->line('july'),
            'august' => $ci->lang->line('august'),
            'september' => $ci->lang->line('september'),
            'october' => $ci->lang->line('october'),
            'november' => $ci->lang->line('november'),
            'december' => $ci->lang->line('december'),
        );
    }
}

if (!function_exists('en2bn')) {

    function en2bn($number)
    {
        $search_array = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
        $replace_array = array("১", "২", "৩", "৪", "৫", "৬", "৭", "৮", "৯", "০");
        $bn_number = str_replace($search_array, $replace_array, $number);

        return $bn_number;
    }
}

if (!function_exists('bn2en')) {

    function bn2en($number)
    {
        $search_array = array("১", "২", "৩", "৪", "", "৬", "৭", "৮", "৯", "");
        $replace_array = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
        $en_number = str_replace($search_array, $replace_array, $number);

        return $en_number;
    }
}

if (!function_exists('en2bnWeek')) {

    function en2bnWeek($week)
    {
        $search_array = array("saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday");
        $replace_array = array("ন", "রবিবার", "মার", "মঙ্লবার", "বুধা", "বৃহস্পিা", "শু্বর");
        $bn_week = str_replace($search_array, $replace_array, $week);
        return $bn_week;
    }
}

if (!function_exists('get_pattern')) {

    function get_pattern()
    {
        $ci = &get_instance();
        return array(
            'default' => array(
                'name' => 'Default',
                'color' => '#000',
                'bgColor' => '#fff',
            ),
            '5-dots' => array(
                'name' => '5 Dots',
                'color' => '#fff',
                'bgColor' => '#000',
            ),
            'criss-cross' => array(
                'name' => 'Criss Cross',
                'color' => '#000',
                'bgColor' => '#eee',
            ),
            'dot-grid' => array(
                'name' => 'Dot Grid',
                'color' => '#000',
                'bgColor' => '#fff',
            ),
            'circle-grid' => array(
                'name' => 'Circle Grid',
                'color' => '#fff',
                'bgColor' => '#414751',
            ),
            'grid-white' => array(
                'name' => 'Grid White',
                'color' => '#000',
                'bgColor' => '#fff',
            ),
            'email-pattern' => array(
                'name' => 'Email Pattern',
                'color' => '#000',
                'bgColor' => '#fff',
            ),
            'light-grey-terrazzo' => array(
                'name' => 'Light Grey',
                'color' => '#000',
                'bgColor' => '#eee',
            ),
            'morocco-blue' => array(
                'name' => 'Borocco Blue',
                'color' => '#fff',
                'bgColor' => '#4BAFC6',
            ),
        );
    }
}

if (!function_exists('get_genders')) {

    function get_genders()
    {
        $ci = &get_instance();
        return array(
            'male' => $ci->lang->line('male'),
            'female' => $ci->lang->line('female'),
            'other' => $ci->lang->line('other'),
        );
    }
}

if (!function_exists('yes_no')) {

    function yes_no()
    {
        $ci = &get_instance();
        return array(
            'yes' => $ci->lang->line('yes'),
            'no' => $ci->lang->line('no'),
        );
    }
}

if (!function_exists('get_payment_methods')) {

    function get_payment_methods()
    {
        $ci = &get_instance();

        $methods = array(
            'cash'   => $ci->lang->line('cash'),
            'cheque' => $ci->lang->line('cheque')
        );

        // if ($ci->session->userdata('role_id') != SUPER_ADMIN) {
        //     $school_id = $ci->session->userdata('school_id');
        // }

        // $ci->db->select('PS.*');
        // $ci->db->from('payment_settings AS PS');
        // if ($school_id) {
        //     $ci->db->where('PS.school_id', $school_id);
        // }
        // $data = $ci->db->get()->row();
        // if (!empty($data)) {
        //     if ($data->paypal_status) {
        //         $methods['paypal'] = $ci->lang->line('paypal');
        //     }
        //     if ($data->stripe_status) {
        //         $methods['stripe'] = $ci->lang->line('stripe');
        //     }
        //     if ($data->payumoney_status) {
        //         $methods['payumoney'] = $ci->lang->line('payumoney');
        //     }
        //     if ($data->ccavenue_status) {
        //         $methods['ccavenue'] = $ci->lang->line('ccavenue');
        //     }
        //     if ($data->paytm_status) {
        //         $methods['paytm'] = $ci->lang->line('paytm');
        //     }
        // }
        return $methods;
    }
}

if (!function_exists('get_paid_types')) {

    function get_paid_status($status)
    {
        $ci = &get_instance();
        $data = array(
            'paid' => $ci->lang->line('paid'),
            'unpaid' => $ci->lang->line('unpaid'),
            'partial' => $ci->lang->line('partial'),
        );
        return $data[$status];
    }
}

if (!function_exists('get_relation_types')) {

    function get_relation_types()
    {
        $ci = &get_instance();
        return array(
            'father' => $ci->lang->line('father'),
            'mother' => $ci->lang->line('mother'),
            'sister' => $ci->lang->line('sister'),
            'brother' => $ci->lang->line('brother'),
            'uncle' => $ci->lang->line('uncle'),
            'maternal_uncle' => $ci->lang->line('maternal_uncle'),
            'other_relative' => $ci->lang->line('other_relative'),
        );
    }
}

if (!function_exists('get_group_by_type')) {

    function get_group_by_type()
    {
        $ci = &get_instance();
        return array(
            'daily' => $ci->lang->line('daily'),
            'monthly' => $ci->lang->line('monthly'),
            'yearly' => $ci->lang->line('yearly')
        );
    }
}


if (!function_exists('get_nice_time')) {

    function get_nice_time($date)
    {

        $ci = &get_instance();
        if (empty($date)) {
            return "2 months ago"; //"No date provided";
        }

        $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
        $lengths = array("60", "60", "24", "7", "4.35", "12", "10");

        $now = time();
        $unix_date = strtotime($date);

        // check validity of date
        if (empty($unix_date)) {
            return "2 months ago"; // "Bad date";
        }

        // is it future date or past date
        if ($now > $unix_date) {
            $difference = $now - $unix_date;
            $tense = "ago";
        } else {
            $difference = $unix_date - $now;
            $tense = "from now";
        }

        for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) {
            $difference /= $lengths[$j];
        }

        $difference = round($difference);

        if ($difference != 1) {
            $periods[$j] .= "s";
        }

        return "$difference $periods[$j] {$tense}";
    }
}


if (!function_exists('get_lang')) {

    function get_lang()
    {
        $ci = &get_instance();
        $ci->lang->line('dashboard');
    }
}

if (!function_exists('get_default_lang_list')) {

    function get_default_lang_list($lang)
    {
        $lang_lists = array();
        $lang_lists['english'] = 'english';
        $lang_lists['bengali'] = 'bengali';
        $lang_lists['spanish'] = 'spanish';
        $lang_lists['arabic'] = 'arabic';
        $lang_lists['hindi'] = 'hindi';
        $lang_lists['urdu'] = 'urdu';
        $lang_lists['chinese'] = 'chinese';
        $lang_lists['japanese'] = 'japanese';
        $lang_lists['portuguese'] = 'portuguese';
        $lang_lists['russian'] = 'russian';
        $lang_lists['french'] = 'french';
        $lang_lists['korean'] = 'korean';
        $lang_lists['german'] = 'german';
        $lang_lists['italian'] = 'italian';
        $lang_lists['thai'] = 'thai';
        $lang_lists['hungarian'] = 'hungarian';
        $lang_lists['dutch'] = 'dutch';
        $lang_lists['latin'] = 'latin';
        $lang_lists['indonesian'] = 'indonesian';
        $lang_lists['turkish'] = 'turkish';
        $lang_lists['greek'] = 'greek';
        $lang_lists['persian'] = 'persian';
        $lang_lists['malay'] = 'malay';
        $lang_lists['telugu'] = 'telugu';
        $lang_lists['tamil'] = 'tamil';
        $lang_lists['gujarati'] = 'gujarati';
        $lang_lists['polish'] = 'polish';
        $lang_lists['ukrainian'] = 'ukrainian';
        $lang_lists['panjabi'] = 'panjabi';
        $lang_lists['romanian'] = 'romanian';
        $lang_lists['burmese'] = 'burmese';
        $lang_lists['yoruba'] = 'yoruba';
        $lang_lists['hausa'] = 'hausa';

        if (isset($lang_lists[$lang]) && !empty($lang_lists[$lang])) {
            return true;
        } else {
            return FALSE;
        }
    }
}

if (!function_exists('get_timezones')) {

    function get_timezones()
    {
        $timezones = array(
            'Pacific/Midway' => "(GMT-11:00) Midway Island",
            'US/Samoa' => "(GMT-11:00) Samoa",
            'US/Hawaii' => "(GMT-10:00) Hawaii",
            'US/Alaska' => "(GMT-09:00) Alaska",
            'US/Pacific' => "(GMT-08:00) Pacific Time (US &amp; Canada)",
            'America/Tijuana' => "(GMT-08:00) Tijuana",
            'US/Arizona' => "(GMT-07:00) Arizona",
            'US/Mountain' => "(GMT-07:00) Mountain Time (US &amp; Canada)",
            'America/Chihuahua' => "(GMT-07:00) Chihuahua",
            'America/Mazatlan' => "(GMT-07:00) Mazatlan",
            'America/Mexico_City' => "(GMT-06:00) Mexico City",
            'America/Monterrey' => "(GMT-06:00) Monterrey",
            'Canada/Saskatchewan' => "(GMT-06:00) Saskatchewan",
            'US/Central' => "(GMT-06:00) Central Time (US &amp; Canada)",
            'US/Eastern' => "(GMT-05:00) Eastern Time (US &amp; Canada)",
            'US/East-Indiana' => "(GMT-05:00) Indiana (East)",
            'America/Bogota' => "(GMT-05:00) Bogota",
            'America/Lima' => "(GMT-05:00) Lima",
            'America/Caracas' => "(GMT-04:30) Caracas",
            'Canada/Atlantic' => "(GMT-04:00) Atlantic Time (Canada)",
            'America/La_Paz' => "(GMT-04:00) La Paz",
            'America/Santiago' => "(GMT-04:00) Santiago",
            'Canada/Newfoundland' => "(GMT-03:30) Newfoundland",
            'America/Buenos_Aires' => "(GMT-03:00) Buenos Aires",
            'Greenland' => "(GMT-03:00) Greenland",
            'Atlantic/Stanley' => "(GMT-02:00) Stanley",
            'Atlantic/Azores' => "(GMT-01:00) Azores",
            'Atlantic/Cape_Verde' => "(GMT-01:00) Cape Verde Is.",
            'Africa/Casablanca' => "(GMT) Casablanca",
            'Europe/Dublin' => "(GMT) Dublin",
            'Europe/Lisbon' => "(GMT) Lisbon",
            'Europe/London' => "(GMT) London",
            'Africa/Monrovia' => "(GMT) Monrovia",
            'Europe/Amsterdam' => "(GMT+01:00) Amsterdam",
            'Europe/Belgrade' => "(GMT+01:00) Belgrade",
            'Europe/Berlin' => "(GMT+01:00) Berlin",
            'Europe/Bratislava' => "(GMT+01:00) Bratislava",
            'Europe/Brussels' => "(GMT+01:00) Brussels",
            'Europe/Budapest' => "(GMT+01:00) Budapest",
            'Europe/Copenhagen' => "(GMT+01:00) Copenhagen",
            'Europe/Ljubljana' => "(GMT+01:00) Ljubljana",
            'Europe/Madrid' => "(GMT+01:00) Madrid",
            'Europe/Paris' => "(GMT+01:00) Paris",
            'Europe/Prague' => "(GMT+01:00) Prague",
            'Europe/Rome' => "(GMT+01:00) Rome",
            'Europe/Sarajevo' => "(GMT+01:00) Sarajevo",
            'Europe/Skopje' => "(GMT+01:00) Skopje",
            'Europe/Stockholm' => "(GMT+01:00) Stockholm",
            'Europe/Vienna' => "(GMT+01:00) Vienna",
            'Europe/Warsaw' => "(GMT+01:00) Warsaw",
            'Europe/Zagreb' => "(GMT+01:00) Zagreb",
            'Europe/Athens' => "(GMT+02:00) Athens",
            'Europe/Bucharest' => "(GMT+02:00) Bucharest",
            'Africa/Cairo' => "(GMT+02:00) Cairo",
            'Africa/Harare' => "(GMT+02:00) Harare",
            'Europe/Helsinki' => "(GMT+02:00) Helsinki",
            'Europe/Istanbul' => "(GMT+02:00) Istanbul",
            'Asia/Jerusalem' => "(GMT+02:00) Jerusalem",
            'Europe/Kiev' => "(GMT+02:00) Kyiv",
            'Europe/Minsk' => "(GMT+02:00) Minsk",
            'Europe/Riga' => "(GMT+02:00) Riga",
            'Europe/Sofia' => "(GMT+02:00) Sofia",
            'Europe/Tallinn' => "(GMT+02:00) Tallinn",
            'Europe/Vilnius' => "(GMT+02:00) Vilnius",
            'Asia/Baghdad' => "(GMT+03:00) Baghdad",
            'Asia/Kuwait' => "(GMT+03:00) Kuwait",
            'Africa/Nairobi' => "(GMT+03:00) Nairobi",
            'Asia/Riyadh' => "(GMT+03:00) Riyadh",
            'Asia/Tehran' => "(GMT+03:30) Tehran",
            'Europe/Moscow' => "(GMT+04:00) Moscow",
            'Asia/Baku' => "(GMT+04:00) Baku",
            'Europe/Volgograd' => "(GMT+04:00) Volgograd",
            'Asia/Muscat' => "(GMT+04:00) Muscat",
            'Asia/Tbilisi' => "(GMT+04:00) Tbilisi",
            'Asia/Yerevan' => "(GMT+04:00) Yerevan",
            'Asia/Kabul' => "(GMT+04:30) Kabul",
            'Asia/Karachi' => "(GMT+05:00) Karachi",
            'Asia/Tashkent' => "(GMT+05:00) Tashkent",
            'Asia/Kolkata' => "(GMT+05:30) Kolkata",
            'Asia/Kathmandu' => "(GMT+05:45) Kathmandu",
            'Asia/Yekaterinburg' => "(GMT+06:00) Ekaterinburg",
            'Asia/Almaty' => "(GMT+06:00) Almaty",
            'Asia/Dhaka' => "(GMT+06:00) Dhaka",
            'Asia/Novosibirsk' => "(GMT+07:00) Novosibirsk",
            'Asia/Bangkok' => "(GMT+07:00) Bangkok",
            'Asia/Jakarta' => "(GMT+07:00) Jakarta",
            'Asia/Krasnoyarsk' => "(GMT+08:00) Krasnoyarsk",
            'Asia/Chongqing' => "(GMT+08:00) Chongqing",
            'Asia/Hong_Kong' => "(GMT+08:00) Hong Kong",
            'Asia/Kuala_Lumpur' => "(GMT+08:00) Kuala Lumpur",
            'Australia/Perth' => "(GMT+08:00) Perth",
            'Asia/Singapore' => "(GMT+08:00) Singapore",
            'Asia/Taipei' => "(GMT+08:00) Taipei",
            'Asia/Ulaanbaatar' => "(GMT+08:00) Ulaan Bataar",
            'Asia/Urumqi' => "(GMT+08:00) Urumqi",
            'Asia/Irkutsk' => "(GMT+09:00) Irkutsk",
            'Asia/Seoul' => "(GMT+09:00) Seoul",
            'Asia/Tokyo' => "(GMT+09:00) Tokyo",
            'Australia/Adelaide' => "(GMT+09:30) Adelaide",
            'Australia/Darwin' => "(GMT+09:30) Darwin",
            'Asia/Yakutsk' => "(GMT+10:00) Yakutsk",
            'Australia/Brisbane' => "(GMT+10:00) Brisbane",
            'Australia/Canberra' => "(GMT+10:00) Canberra",
            'Pacific/Guam' => "(GMT+10:00) Guam",
            'Australia/Hobart' => "(GMT+10:00) Hobart",
            'Australia/Melbourne' => "(GMT+10:00) Melbourne",
            'Pacific/Port_Moresby' => "(GMT+10:00) Port Moresby",
            'Australia/Sydney' => "(GMT+10:00) Sydney",
            'Asia/Vladivostok' => "(GMT+11:00) Vladivostok",
            'Asia/Magadan' => "(GMT+12:00) Magadan",
            'Pacific/Auckland' => "(GMT+12:00) Auckland",
            'Pacific/Fiji' => "(GMT+12:00) Fiji",
        );

        return $timezones;
    }
}


if (!function_exists('get_date_format')) {

    function get_date_format()
    {

        $date = array();
        $date['Y-m-d'] = '2019-01-15';
        $date['d-m-Y'] = '15-01-2019';
        $date['d/m/Y'] = '15/01/2019';
        $date['m/d/Y'] = '03/15/2019';
        $date['m.d.Y'] = '03.15.2019';
        $date['j, n, Y'] = '14, 7, 2019';
        $date['F j, Y'] = 'July 15, 2019';
        $date['M j, Y'] = 'Jul 13, 2019';
        $date['j M, Y'] = '13 Jul, 2019';
        $date['d F, Y'] = '13 July, 2019';

        return $date;
    }
}

if (!function_exists('get_time_format')) {

    function get_time_format()
    {

        $date = array();
        $date['h:i:sa'] = '03:18:03am';
        $date['h:i:sA'] = '03:18:22AM';
        $date['H:i:sa'] = '13:18:03am';
        $date['H:i:sA'] = '13:18:03AM';
        $date['h:i'] = '03:18';
        $date['H:i'] = '13:18';
        $date['h:ia'] = '03:18am';
        $date['H:iA'] = '13:18AM';

        return $date;
    }
}

if (!function_exists('get_mail_protocol')) {
    function get_mail_protocol()
    {

        $protocol = array();
        $protocol['mail'] = 'mail';
        $protocol['sendmail'] = 'sendmail';
        $protocol['smtp'] = 'smtp';

        return $protocol;
    }
}

if (!function_exists('get_smtp_crypto')) {
    function get_smtp_crypto()
    {

        $smtp_crypto = array();
        $smtp_crypto['tls'] = 'tls';
        $smtp_crypto['ssl'] = 'ssl';

        return $smtp_crypto;
    }
}

if (!function_exists('get_mail_type')) {
    function get_mail_type()
    {

        $mail_type = array();
        $mail_type['text'] = 'text';
        $mail_type['html'] = 'html';

        return $mail_type;
    }
}

if (!function_exists('get_char_set')) {
    function get_char_set()
    {

        $char_set = array();
        $char_set['utf-8'] = 'utf-8';
        $char_set['iso-8859-1'] = 'iso-8859-1';

        return $char_set;
    }
}

if (!function_exists('get_email_priority')) {
    function get_email_priority()
    {

        $priority = array();
        $priority['1'] = 'highest';
        $priority['3'] = 'normal';
        $priority['5'] = 'lowest';

        return $priority;
    }
}


if (!function_exists('get_operation_by_module')) {

    function get_operation_by_module($module_id)
    {
        $ci = &get_instance();
        $ci->db->select('O.*');
        $ci->db->from('operations AS O');
        $ci->db->where('O.module_id', $module_id);
        return $ci->db->get()->result();
    }
}

if (!function_exists('get_permission_by_operation')) {

    function get_permission_by_operation($role_id, $operation_id)
    {
        $ci = &get_instance();
        $ci->db->select('P.*');
        $ci->db->from('privileges AS P');
        $ci->db->where('P.role_id', $role_id);
        $ci->db->where('P.operation_id', $operation_id);
        return $ci->db->get()->row();
    }
}

if (!function_exists('check_permission')) {

    function check_permission($action)
    {

        $ci = &get_instance();
        $role_id = $ci->session->userdata('role_id');
        $operation_slug = $ci->router->fetch_class();
        $module_slug = $ci->router->fetch_module();

        if ($module_slug == '') {
            $module_slug = $operation_slug;
        }

        $module_slug = 'my_' . $module_slug;

        $data = $ci->config->item($operation_slug, $module_slug);

        $result = $data[$role_id];
        if (!empty($result)) {
            $array = explode('|', $result);
            if (!$array[$action]) {
                error($ci->lang->line('permission_denied'));
                redirect('dashboard');
            }
        } else {
            error($ci->lang->line('permission_denied'));
            redirect('dashboard');
        }

        return TRUE;
    }
}

if (!function_exists('has_permission')) {

    function has_permission($action, $module_slug = NULL, $operation_slug = NULL)
    {

        $ci = &get_instance();
        $role_id = $ci->session->userdata('role_id');

        if ($module_slug == '') {
            $module_slug = $operation_slug;
        }

        $module_slug = 'my_' . $module_slug;

        $data = $ci->config->item($operation_slug, $module_slug);

        $result = @$data[$role_id];

        if (!empty($result)) {
            $array = explode('|', $result);
            return $array[$action];
        } else {
            return FALSE;
        }
    }
}

if (!function_exists('create_log')) {

    function create_log($activity = NULL)
    {

        $ci = &get_instance();
        $data = array();

        $data['user_id'] = logged_in_user_id();
        $data['role_id'] = logged_in_role_id();
        $user = get_user_by_id($data['user_id']);

        $data['name'] = isset($user->name) && !empty($user->name) ? $user->name : null;
        $data['phone'] = isset($user->phone) && !empty($user->phone) ? $user->phone : null;
        $data['email'] = isset($user->email) && !empty($user->email) ? $user->email : null;
        $data['ip_address'] = $_SERVER['REMOTE_ADDR'];
        $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
        $data['activity'] = $activity;
        $data['status'] = 1;
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['created_by'] = logged_in_user_id();
        $ci->db->insert('activity_logs', $data);
    }
}

if (!function_exists('get_pagination')) {
    function get_pagination($per_page)
    {
        $config['per_page'] = $per_page;
        $config['enable_query_strings'] = TRUE;
        $config['use_page_numbers'] = TRUE;
        $config['query_string_segment'] = 'page';
        $config['page_query_string'] = TRUE;
        $config['num_links'] = 5;
        $config['full_tag_open'] = '<nav class="pagination-wrap"><ul class="pagination">';
        $config['full_tag_close'] = '</ul></nav>';
        $config['attributes'] = ['class' => 'page-link'];
        $config['first_link'] = false;
        $config['last_link'] = false;
        $config['first_tag_open'] = '<li class="page-item">';
        $config['first_tag_close'] = '</li>';
        $config['prev_link'] = '&laquo';
        $config['prev_tag_open'] = '<li class="page-item">';
        $config['prev_tag_close'] = '</li>';
        $config['next_link'] = '&raquo';
        $config['next_tag_open'] = '<li class="page-item">';
        $config['next_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li class="page-item">';
        $config['last_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="page-item active"><a href="#" class="page-link">';
        $config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
        $config['num_tag_open'] = '<li class="page-item">';
        $config['num_tag_close'] = '</li>';
        return $config;
    }
}

if (!function_exists('get_ajax_pagination')) {
    function get_ajax_pagination()
    {
        $config['use_page_numbers'] = TRUE;
        $config['num_links'] = 5;
        $config['full_tag_open'] = '<nav class="pagination-wrap"><ul class="pagination">';
        $config['full_tag_close'] = '</ul></nav>';
        $config['attributes'] = ['class' => 'page-link'];
        $config['first_link'] = false;
        $config['last_link'] = false;
        $config['first_tag_open'] = '<li class="page-item">';
        $config['first_tag_close'] = '</li>';
        $config['prev_link'] = '&laquo';
        $config['prev_tag_open'] = '<li class="page-item">';
        $config['prev_tag_close'] = '</li>';
        $config['next_link'] = '&raquo';
        $config['next_tag_open'] = '<li class="page-item">';
        $config['next_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li class="page-item">';
        $config['last_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="page-item active"><a href="#" class="page-link">';
        $config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
        $config['num_tag_open'] = '<li class="page-item">';
        $config['num_tag_close'] = '</li>';
        return $config;
    }
}


// Hospital Start

if (!function_exists('get_charge_type')) {

    function get_charge_type()
    {
        $ci = &get_instance();
        return array(
            'procedures' => $ci->lang->line('procedures'),
            'investigations' => $ci->lang->line('investigations'),
            'operation_theatre' => $ci->lang->line('operation_theatre'),
            'other' => $ci->lang->line('other'),
        );
    }
}

if (!function_exists('get_appointment_source')) {

    function get_appointment_source()
    {
        $ci = &get_instance();
        return array(
            '0' => $ci->lang->line('offline'),
            '1' => $ci->lang->line('online'),
        );
    }
}

if (!function_exists('get_appointment_status')) {

    function get_appointment_status()
    {
        $ci = &get_instance();
        return array(
            '1' => $ci->lang->line('approved'),
            '0' => $ci->lang->line('pending'),
            '2' => $ci->lang->line('cancel'),
        );
    }
}


if (!function_exists('get_custom_serial_number')) {
    function get_custom_serial_number($table, $doctor_id = null, $date = null)
    {
        $max_id = '';
        $ci = &get_instance();
        $ci->db->select_max('serial_no');
        $ci->db->where('doctor_id', $doctor_id);
        $ci->db->where('date', $date);
        $max_id = $ci->db->get($table)->row()->serial_no;

        if (isset($max_id) && $max_id > 0) {
            $max_id = $max_id + 1;
        } else {
            $max_id = 1;
        }

        if (!$max_id) {
            $max_id = '000' . $max_id;
        } elseif ($max_id > 0 && $max_id < 10) {
            $max_id = '00' . $max_id;
        } elseif ($max_id >= 10 && $max_id < 100) {
            $max_id = '0' . $max_id;
        } else {
            $max_id = $max_id;
        }
        return $max_id;
    }
}

if (!function_exists('get_custom_appointment_number')) {
    function get_custom_appointment_number($serial_no = null)
    {
        return 'APN' . date('Y') . date('m') . $serial_no;
    }
}

if (!function_exists('get_custom_invoice')) {

    function get_custom_invoice($table, $string = null, $year = null, $month = null)
    {
        $ci = &get_instance();
        $ci->db->select_max('id');
        $max_id = $ci->db->get($table)->row()->id;


        if (isset($max_id) && $max_id > 0) {
            $max_id = $max_id + 1;
        } else {
            $max_id = 1;
        }

        if (!$max_id) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id > 0 && $max_id < 10) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id >= 10 && $max_id < 100) {
            $max_id = '000' . $max_id;
        } elseif ($max_id >= 100 && $max_id < 1000) {
            $max_id = '00' . $max_id;
        } elseif ($max_id >= 1000 && $max_id < 10000) {
            $max_id = '0' . $max_id;
        } else {
            $max_id = $max_id;
        }

        return ($string . $year . $month . $max_id);
    }
}

if (!function_exists('get_custom_id')) {

    function get_custom_id($table, $string = null, $year = null, $month = null)
    {
        $ci = &get_instance();
        $ci->db->select_max('id');
        $max_id = $ci->db->get($table)->row()->id;


        if (isset($max_id) && $max_id > 0) {
            $max_id = $max_id + 1;
        } else {
            $max_id = 1;
        }

        if (!$max_id) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id > 0 && $max_id < 10) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id >= 10 && $max_id < 100) {
            $max_id = '000' . $max_id;
        } elseif ($max_id >= 100 && $max_id < 1000) {
            $max_id = '00' . $max_id;
        } elseif ($max_id >= 1000 && $max_id < 10000) {
            $max_id = '0' . $max_id;
        } else {
            $max_id = $max_id;
        }

        return ($string . $year . $month . $max_id);
    }
}

if (!function_exists('get_datewise_custom_invoice_id')) {

    function get_datewise_custom_invoice_id($table, $string = null, $year = null, $month = null, $date = null)
    {
        $ci = &get_instance();
        $ci->db->select('id');
        $ci->db->where("DATE(created_at)", date('Y-m-d'));
        $max_id = $ci->db->get($table)->num_rows();

        if (isset($max_id) && $max_id > 0) {
            $max_id = $max_id + 1;
        } else {
            $max_id = 1;
        }

        if (!$max_id) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id > 0 && $max_id < 10) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id >= 10 && $max_id < 100) {
            $max_id = '000' . $max_id;
        } elseif ($max_id >= 100 && $max_id < 1000) {
            $max_id = '00' . $max_id;
        } elseif ($max_id >= 1000 && $max_id < 10000) {
            $max_id = '0' . $max_id;
        } else {
            $max_id = $max_id;
        }

        return ($string . $year . $month . $date . $max_id);
    }
}


if (!function_exists('get_datewise_payment_custom_invoice_id')) {

    function get_datewise_payment_custom_invoice_id($table, $type, $date, $string = null, $year = null, $month = null, $day = null)
    {
        $ci = &get_instance();
        $ci->db->select('id');
        if ($type) {
            $ci->db->where("invoice_type", $type);
        }
        if ($date) {
            $ci->db->where("DATE(date)", $date);
        }
        $max_id = $ci->db->get($table)->num_rows();

        if (isset($max_id) && $max_id > 0) {
            $max_id = $max_id + 1;
        } else {
            $max_id = 1;
        }

        if (!$max_id) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id > 0 && $max_id < 10) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id >= 10 && $max_id < 100) {
            $max_id = '000' . $max_id;
        } elseif ($max_id >= 100 && $max_id < 1000) {
            $max_id = '00' . $max_id;
        } else {
            $max_id = $max_id;
        }

        return ($string . $year . $month . $day . $max_id);
    }
}


if (!function_exists('get_investagation_custom_code')) {

    function get_investagation_custom_code($table, $string = null)
    {
        $ci = &get_instance();
        $ci->db->select_max('id');
        $max_id = $ci->db->get($table)->row()->id;


        if (isset($max_id) && $max_id > 0) {
            $max_id = $max_id + 1;
        } else {
            $max_id = 1;
        }

        if (!$max_id) {
            $max_id = '00' . $max_id;
        } elseif ($max_id > 0 && $max_id < 10) {
            $max_id = '000' . $max_id;
        } elseif ($max_id >= 10 && $max_id < 100) {
            $max_id = '00' . $max_id;
        } elseif ($max_id >= 100 && $max_id < 1000) {
            $max_id = '' . $max_id;
        } else {
            $max_id = $max_id;
        }

        return ($string . $max_id);
    }
}

if (!function_exists('get_specimen')) {

    function get_specimen()
    {
        return array(
            'blood' => 'Blood',
            'semen' => 'Semen',
            'urine' => 'Urine',
            'usg' => 'USG',
            'xray' => 'X-Ray',
            'ecg' => 'ECG',
            'echo' => 'ECHO',
            'stool' => 'Stool',
            'skin' => 'Skin',
            'nasopharyngeale-swab' => 'Nasopharyngeale Swab',

        );
    }
}

if (!function_exists('get_room_list')) {
    function get_room_list($id)
    {
        $ci = &get_instance();
        $ci->db->select('DT.*');
        $ci->db->from('diagnostic_tests AS DT');
        $ci->db->where('DT.id', $id);
        $ci->db->group_by('DT.room_no');
        $ci->db->order_by('DT.room_no', 'ASC');
        return $ci->db->get()->row();
    }
}

if (!function_exists('get_menu_location')) {
    function get_menu_location()
    {
        $ci = &get_instance();
        return array(
            'main_menu' => $ci->lang->line('main') . ' ' . $ci->lang->line('menu'),
            'footer_menu_1' => $ci->lang->line('footer_menu_1'),
            'footer_menu_2' => $ci->lang->line('footer_menu_2')
        );
    }
}


if (!function_exists('get_invoice_status')) {

    function get_invoice_status()
    {
        $ci = &get_instance();
        return array(
            'complete' => $ci->lang->line('complete'),
            'rejected' => $ci->lang->line('rejected'),
            'canceled' => $ci->lang->line('cancel'),
            'pending' => $ci->lang->line('pending'),
        );
    }
}

if (!function_exists('get_ipd_disease')) {

    function get_ipd_disease()
    {
        $ci = &get_instance();
        return array(
            'medicine' => $ci->lang->line('medicine'),
            'surgery' => $ci->lang->line('surgery'),
            'orthopedic' => $ci->lang->line('orthopedic'),
            'gynaecology' => $ci->lang->line('gynaecology'),
            'urology' => $ci->lang->line('urology'),
            'ent' => $ci->lang->line('ent'),
        );
    }
}

if (!function_exists('get_custom_permission_type')) {

    function get_custom_permission_type()
    {
        $ci = &get_instance();
        return array(
            'created_by' => $ci->lang->line('created_by'),
            'modified_by' => $ci->lang->line('modified_by'),
            'discount' => $ci->lang->line('discount'),
            'modified_discharged' => $ci->lang->line('modified_discharged'),
            'second_less' => $ci->lang->line('second_less'),
            'appointment_edit' => $ci->lang->line('appointment') . ' ' . $ci->lang->line('edit'),
            'payment_collection' => $ci->lang->line('payment') . ' ' . $ci->lang->line('collection'),
            'add_marketing' => $ci->lang->line('marketing') . ' ' . $ci->lang->line('bill'),
          	
        );
    }
}

if (!function_exists('custom_permission')) {

    function custom_permission($action)
    {

        $ci = &get_instance();
        $role_id = $ci->session->userdata('role_id');
        $user_id = $ci->session->userdata('user_id');

        $ci->db->select('P.*');
        $ci->db->from('permissions AS P');
        $ci->db->where('P.role_id', $role_id);
        $ci->db->where('P.user_id', $user_id);
        $ci->db->where('P.permission_type', $action);
        $ci->db->where('P.permissions_status', 1);
        return $ci->db->get()->row();
    }
}

if (!function_exists('isMobile')) {
    function isMobile()
    {
        return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
    }
}

if (!function_exists('get_age')) {
    function get_age($dob)
    {
        $birth_date     = new DateTime($dob);
        $current_date   = new DateTime();
        $diff           = $birth_date->diff($current_date);
        return $diff->y . "Y " . $diff->m . "M " . $diff->d . "D";
    }
}

if (!function_exists('get_badge_color')) {

    function get_badge_color($role)
    {
        if ($role == ADMIN) {
            return 'primary';
        } elseif ($role == DOCTOR) {
            return 'success';
        } elseif ($role == PATIENT) {
            return 'info';
        } elseif ($role == ACCOUNTANT) {
            return 'warning';
        } elseif ($role == PATHOLOGIST) {
            return 'sky';
        } elseif ($role == RADIOLOGIST) {
            return 'teal';
        } elseif ($role == NURSE) {
            return 'lime';
        } elseif ($role == RECEPTIONIST) {
            return 'yellow';
        } elseif ($role == STAFF) {
            return 'brown';
        } elseif ($role == VD) {
            return 'gold';
        } elseif ($role == MARKETING) {
            return 'smoke';
        } elseif ($role == PHARMACIST) {
            return 'grey';
        } else {
            return 'danger';
        }
    }
}



if (!function_exists('get_video_detail')) {
    function get_video_detail($video_url)
    {
        $host = explode('.', str_replace('www.', '', strtolower(parse_url($video_url, PHP_URL_HOST))));
        $host = isset($host[0]) ? $host[0] : $host;
        $youtube_api_key = 'AIzaSyCZMlDInK0-ucWpahE9848-EntPRIQCtwE';
        if ('youtube' || 'youtu') {
            $video_id = get_youtube_video_id($video_url);
            $hash = json_decode(file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=" . $video_id . "&key=" . $youtube_api_key . ""));
            $duration = new DateInterval($hash->items[0]->contentDetails->duration);
            return array(
                'provider' => 'YouTube',
                'video_id' => $video_id,
                'title' => $hash->items[0]->snippet->title,
                'thumbnail' => 'https://i.ytimg.com/vi/' . $hash->items[0]->id . '/hqdefault.jpg',
                'video' => "http://www.youtube.com/watch?v=" . $hash->items[0]->id,
                'embed_video' => "http://www.youtube.com/embed/" . $hash->items[0]->id,
                'duration' => $duration->format('%H:%I:%S'),
            );
        }
    }
}

function get_youtube_video_id($embed_url)
{
    preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $embed_url, $match);
    $video_id = $match[1];
    return $video_id;
}


if (!function_exists('get_employee_type')) {

    function get_employee_type()
    {
        $ci = &get_instance();
        return array(
            // 'admin' => $ci->lang->line('admin'),
            // 'accountant' => $ci->lang->line('accountant'),
            'staff' => $ci->lang->line('staff'),
            // 'marketing' => $ci->lang->line('marketing'),
            // 'surgeon' => $ci->lang->line('surgeon'),
            // 'doctor' => $ci->lang->line('doctor'),
            // 'anesthetist' => $ci->lang->line('anesthetist'),
            // 'assistant' => $ci->lang->line('assistant'),
            // 'vd' => $ci->lang->line('vd'),
            // 'nurse' => $ci->lang->line('nurse'),
            'other' => $ci->lang->line('other')
        );
    }
}

if (!function_exists('get_commission_type')) {

    function get_commission_type()
    {
        $ci = &get_instance();
        return array(
            'mbbs' => $ci->lang->line('mbbs'),
            'vd' => $ci->lang->line('vd'),
            'emp' => $ci->lang->line('emp'),
            'corporate' => $ci->lang->line('corporate')
        );
    }
}


if (!function_exists('get_attendance_status')) {
    function get_attendance_status()
    {
        return array(
            'p' => 'Present',
            'a' => 'Absent',
            'h' => 'Holiday',
            'l' => 'Leave',
            'w' => 'Weekend',
            'o' => 'Out of Office',
            'ph' => 'Present Holiday',
            'pl' => 'Present Leave',
            'po' => 'Present Out of Office',
            'pw' => 'Present Weekend',
        );
    }
}

if (!function_exists('get_attendance_badge')) {
    function get_attendance_badge($attendance_status)
    {
        if ($attendance_status == 'a') {
            return '<span class="badge badge-danger">Absent</span>';
        } elseif ($attendance_status == 'h') {
            return '<span class="badge badge-warning">Holiday</span>';
        } elseif ($attendance_status == 'l') {
            return '<span class="badge badge-info">Leave</span>';
        } elseif ($attendance_status == 'o') {
            return '<span class="badge badge-sky">Out of Office</span>';
        } elseif ($attendance_status == 'p') {
            return '<span class="badge badge-success">Present</span>';
        } elseif ($attendance_status == 'w') {
            return '<span class="badge badge-yellow">Weekend</span>';
        } elseif ($attendance_status == 'ph') {
            return '<span class="badge badge-teal">Present Holiday</span>';
        } elseif ($attendance_status == 'pl') {
            return '<span class="badge badge-lime">Present Leave</span>';
        } elseif ($attendance_status == 'po') {
            return '<span class="badge badge-smoke">Present Out of Office</span>';
        } else {
            return '<span class="badge badge-brown">Present Weekend</span>';
        }
    }
}

if (!function_exists('get_schedule_slot')) {

    function get_schedule_slot()
    {
        $ci = &get_instance();
        return array(
            'morning' => $ci->lang->line('morning'),
            'noon' => $ci->lang->line('noon'),
            'afternoon' => $ci->lang->line('afternoon'),
            'evening' => $ci->lang->line('evening')
        );
    }
}

if (!function_exists('en2bnSlot')) {

    function en2bnSlot($number)
    {
        $search_array = array("morning", "noon", "afternoon", "evening");
        $replace_array = array("কা", "ুপু", "কা", "সন্া");
        $bn_number = str_replace($search_array, $replace_array, $number);

        return $bn_number;
    }
}

if (!function_exists('get_sms_formatted_body')) {

    function get_sms_formatted_body($body, $role_id, $type, $data)
    {

        $ci = &get_instance();

        if ($type === 'appointment') {
            $tags = get_template_tags($role_id, 'appointment');
            $appointment = $ci->db->get_where('appointments', array('id' => $data))->row();

            if ($appointment->doctor_id && $appointment->doctor_id > 0) {
                $doctor = $ci->db->get_where('employees', array('user_id' => $appointment->doctor_id))->row();
            }

            if ($appointment->reference_id && $appointment->reference_id > 0) {
                $reference = $ci->db->get_where('employees', array('user_id' => $appointment->reference_id))->row();
            }

            if ($appointment->created_by && $appointment->created_by > 0) {
                $created_by = $ci->db->get_where('employees', array('user_id' => $appointment->created_by))->row();
            }

            $appointment_data = [
                'doctor' => $appointment->doctor_id && $appointment->doctor_id > 0 ? $doctor->name : '',
                'reference' => $appointment->reference_id && $appointment->reference_id > 0 ? $reference->name : '',
                'name' => $appointment->name,
                'phone' => $appointment->phone,
                'appointment_no' => $appointment->appointment_no,
                'serial_no' => $appointment->serial_no,
                'date' => $appointment->date,
                'gender' => $appointment->gender,
                'address' => $appointment->address,
                'note' => $appointment->note,
                'appointment_status' => $appointment->appointment_status,
                'source' => $appointment->source,
                'created_by' => $appointment->created_by && $appointment->created_by > 0 ? $created_by->name : '',
            ];
        }

        // IPD Patient Admission

        elseif ($type === 'ipd_admission') {
            $tags = get_template_tags($role_id, 'ipd_admission');
            $ipd_patient = $ci->db->get_where('ipd_patients', array('id' => $data))->row();

            if ($ipd_patient->patient_id) {
                $patient = $ci->db->get_where('patients', array('user_id' => $ipd_patient->patient_id))->row();
            }

            if ($ipd_patient->doctor_id && $ipd_patient->doctor_id > 0) {
                $doctor = $ci->db->get_where('employees', array('user_id' => $ipd_patient->doctor_id))->row();
            }

            if ($ipd_patient->reference_id && $ipd_patient->reference_id > 0) {
                $reference = $ci->db->get_where('employees', array('user_id' => $ipd_patient->reference_id))->row();
            }

            if ($ipd_patient->bed_id && $ipd_patient->bed_id > 0) {
                $bed = $ci->db->get_where('beds', array('id' => $ipd_patient->bed_id))->row();
            }

            if ($ipd_patient->created_by && $ipd_patient->created_by > 0) {
                $created_by = $ci->db->get_where('employees', array('user_id' => $ipd_patient->created_by))->row();
            }

            $ipd_patient_data = [
                'name' => $patient->name,
                'phone' => $patient->phone,
                'gender' => $patient->gender,
                'address' => $patient->address,
                'doctor' => $ipd_patient->doctor_id && $ipd_patient->doctor_id > 0 ? $doctor->name : '',
                'reference' => $ipd_patient->reference_id && $ipd_patient->reference_id > 0 ? $reference->name : '',
                'ipd_no' => $ipd_patient->ipd_no,
                'registration_no' => $ipd_patient->registration_no,
                'admission_date' => $ipd_patient->admission_date,
                'discharged_date' => $ipd_patient->discharged_date,
                'remark' => $ipd_patient->remark,
                'bed' => $bed->name,
                'created_by' => $ipd_patient->created_by && $ipd_patient->created_by > 0 ? $created_by->name : '',
            ];
        }

        // IPD Discharged Patient

        elseif ($type === 'ipd_discharged') {
            $tags = get_template_tags($role_id, 'ipd_discharged');
            $ipd_patient = $ci->db->get_where('ipd_patients', array('id' => $data))->row();

            if ($ipd_patient->patient_id) {
                $patient = $ci->db->get_where('patients', array('user_id' => $ipd_patient->patient_id))->row();
            }

            if ($ipd_patient->doctor_id && $ipd_patient->doctor_id > 0) {
                $doctor = $ci->db->get_where('employees', array('user_id' => $ipd_patient->doctor_id))->row();
            }

            if ($ipd_patient->reference_id && $ipd_patient->reference_id > 0) {
                $reference = $ci->db->get_where('employees', array('user_id' => $ipd_patient->reference_id))->row();
            }

            if ($ipd_patient->bed_id && $ipd_patient->bed_id > 0) {
                $bed = $ci->db->get_where('beds', array('id' => $ipd_patient->bed_id))->row();
            }

            if ($ipd_patient->created_by && $ipd_patient->created_by > 0) {
                $created_by = $ci->db->get_where('employees', array('user_id' => $ipd_patient->created_by))->row();
            }

            $ipd_patient_data = [
                'name' => $patient->name,
                'phone' => $patient->phone,
                'gender' => $patient->gender,
                'address' => $patient->address,
                'doctor' => $ipd_patient->doctor_id && $ipd_patient->doctor_id > 0 ? $doctor->name : '',
                'reference' => $ipd_patient->reference_id && $ipd_patient->reference_id > 0 ? $reference->name : '',
                'ipd_no' => $ipd_patient->ipd_no,
                'registration_no' => $ipd_patient->registration_no,
                'admission_date' => $ipd_patient->admission_date,
                'discharged_date' => $ipd_patient->discharged_date,
                'remark' => $ipd_patient->remark,
                'bed' => $bed->name,
                'created_by' => $ipd_patient->created_by && $ipd_patient->created_by > 0 ? $created_by->name : '',
            ];
        }

        // IPD Advance Payment

        elseif ($type === 'ipd_payment') {
            $tags = get_template_tags($role_id, 'ipd_payment');
            $ipd_payment = $ci->db->get_where('ipd_advance_payments', array('id' => $data))->row();

            if ($ipd_payment->patient_id) {
                $patient = $ci->db->get_where('patients', array('user_id' => $ipd_payment->patient_id))->row();
            }

            if ($ipd_payment->created_by && $ipd_payment->created_by > 0) {
                $created_by = $ci->db->get_where('employees', array('user_id' => $ipd_payment->created_by))->row();
            }

            $ipd_payment_data = [
                'name' => $patient->name,
                'phone' => $patient->phone,
                'gender' => $patient->gender,
                'address' => $patient->address,
                'invoice_no' => $ipd_payment->custom_invoice_id,
                'payment_date' => $ipd_payment->payment_date,
                'amount' => $ipd_payment->amount,
                'note' => $ipd_payment->note,
                'payment_status' => $ipd_payment->payment_status,
                'created_by' => $ipd_payment->created_by && $ipd_payment->created_by > 0 ? $created_by->name : '',
            ];
        }

        // Billing Message

        elseif ($type === 'billing_sms') {
            $tags = get_template_tags($role_id, 'billing_sms');
            $invoice = $ci->db->get_where('invoices', array('id' => $data))->row();

            if ($invoice->patient_id) {
                $patient = $ci->db->get_where('patients', array('user_id' => $invoice->patient_id))->row();
            }

            if ($invoice->ref_dr_id && $invoice->ref_dr_id > 0) {
                $doctor = $ci->db->get_where('employees', array('user_id' => $invoice->ref_dr_id))->row();
            }

            if ($invoice->commission_user_id && $invoice->commission_user_id > 0) {
                $reference = $ci->db->get_where('employees', array('user_id' => $invoice->commission_user_id))->row();
            }

            if ($invoice->created_by && $invoice->created_by > 0) {
                $created_by = $ci->db->get_where('employees', array('user_id' => $invoice->created_by))->row();
            }

            $billing_data = [
                'name' => $patient->name,
                'phone' => $patient->phone,
                'gender' => $patient->gender,
                'address' => $patient->address,
                'doctor' => $invoice->ref_dr_id ? $doctor->name : 'Self',
                'reference' => $invoice->commission_user_id ? $reference->name : '',
                'invoice_no' => $invoice->custom_invoice_id,
                'bill_date' => $invoice->bill_date,
                'total_bill' => $invoice->total_bill,
                'discount' => $invoice->discount,
                'net_payable' => $invoice->net_payable,
                'advanced' => $invoice->advanced,
                'due_amount' => $invoice->due_amount,
                'paid_status' => $invoice->paid_status,
                'created_by' => $invoice->created_by && $invoice->created_by > 0 ? $created_by->name : '',
            ];
        }

        // Billing Second Payment Message

        elseif ($type === 'billing_payment_sms') {
            $tags = get_template_tags($role_id, 'billing_payment_sms');
            $invoice_payment = $ci->db->get_where('invoice_payments', array('id' => $data))->row();
            $invoice = $ci->db->get_where('invoices', array('id' => $invoice_payment->invoice_id))->row();

            if ($invoice->patient_id) {
                $patient = $ci->db->get_where('patients', array('user_id' => $invoice->patient_id))->row();
            }

            if ($invoice->ref_dr_id && $invoice->ref_dr_id > 0) {
                $doctor = $ci->db->get_where('employees', array('user_id' => $invoice->ref_dr_id))->row();
            }

            if ($invoice->commission_user_id && $invoice->commission_user_id > 0) {
                $reference = $ci->db->get_where('employees', array('user_id' => $invoice->commission_user_id))->row();
            }

            if ($invoice_payment->created_by && $invoice_payment->created_by > 0) {
                $created_by = $ci->db->get_where('employees', array('user_id' => $invoice_payment->created_by))->row();
            }

            $billing_payment_data = [
                'name' => $patient->name,
                'phone' => $patient->phone,
                'gender' => $patient->gender,
                'address' => $patient->address,
                'doctor' => $invoice->ref_dr_id ? $doctor->name : 'Self',
                'reference' => $invoice->commission_user_id ? $reference->name : '',
                'invoice_no' => $invoice->custom_invoice_id,
                'bill_date' => $invoice->bill_date,
                'total_bill' => $invoice->total_bill,
                'discount' => $invoice->discount,
                'net_payable' => $invoice->net_payable,
                'advanced' => $invoice->advanced,
                'due_amount' => $invoice->due_amount,
                'paid_status' => $invoice->paid_status,
                'amount' => $invoice_payment->amount,
                'second_less' => $invoice_payment->second_less,
                'payment_date' => $invoice_payment->payment_date,
                'created_by' => $invoice_payment->created_by && $invoice_payment->created_by > 0 ? $created_by->name : '',
            ];
        }

        // Investigation Commission Payment Message

        elseif ($type === 'investigation_payment_sms') {
            $tags = get_template_tags($role_id, 'investigation_payment_sms');
            $payment = $ci->db->get_where('payments', array('id' => $data))->row();
            $invoice = $ci->db->get_where('invoices', array('id' => $payment->invoice_id))->row();

            if ($invoice->patient_id) {
                $patient = $ci->db->get_where('patients', array('user_id' => $invoice->patient_id))->row();
            }

            if ($invoice->ref_dr_id && $invoice->ref_dr_id > 0) {
                $doctor = $ci->db->get_where('employees', array('user_id' => $invoice->ref_dr_id))->row();
            }

            if ($invoice->commission_user_id && $invoice->commission_user_id > 0) {
                $reference = $ci->db->get_where('employees', array('user_id' => $invoice->commission_user_id))->row();
            }

            if ($payment->created_by && $payment->created_by > 0) {
                $created_by = $ci->db->get_where('employees', array('user_id' => $payment->created_by))->row();
            }

            $investigation_payment_data = [
                'name' => $patient->name,
                'phone' => $patient->phone,
                'gender' => $patient->gender,
                'address' => $patient->address,
                'doctor' => $invoice->ref_dr_id ? $doctor->name : 'Self',
                'reference' => $invoice->commission_user_id ? $reference->name : '',
                'invoice_no' => $invoice->custom_invoice_id,
                'bill_date' => $invoice->bill_date,
                'total_bill' => $invoice->total_bill,
                'discount' => $invoice->discount,
                'net_payable' => $invoice->net_payable,
                'advanced' => $invoice->advanced,
                'due_amount' => $invoice->due_amount,
                'paid_status' => $invoice->paid_status,
                'commission_amount' => $payment->commission_amount,
                'payable_amount' => $payment->payable_amount,
                'due_amount' => $payment->due_amount,
                'payment_date' => $payment->date,
                'delivery_date' => $payment->delivery_date,
                'created_by' => $payment->created_by && $payment->created_by > 0 ? $created_by->name : '',
            ];
        } else {
            return false;
        }

        $arr = array('[', ']');
        foreach ($tags as $tag) {
            $field = str_replace($arr, '', $tag);

            if ($type === 'appointment') {
                $body  = str_replace($tag, $appointment_data[$field], $body);
            } elseif ($type === 'ipd_admission') {
                $body  = str_replace($tag, $ipd_patient_data[$field], $body);
            } elseif ($type === 'ipd_discharged') {
                $body  = str_replace($tag, $ipd_patient_data[$field], $body);
            } elseif ($type === 'ipd_payment') {
                $body  = str_replace($tag, $ipd_payment_data[$field], $body);
            } elseif ($type === 'billing_sms') {
                $body  = str_replace($tag, $billing_data[$field], $body);
            } elseif ($type === 'billing_payment_sms') {
                $body  = str_replace($tag, $billing_payment_data[$field], $body);
            } elseif ($type === 'investigation_payment_sms') {
                $body  = str_replace($tag, $investigation_payment_data[$field], $body);
            } else {
                return false;
            }
        }
        return $body;
    }
}

if (!function_exists('send_sms')) {

    function send_sms($type, $data)
    {
        $ci = &get_instance();
        $ci->load->library('mimsms');

        if ($type === 'appointment') {
            $notification = $ci->db->get_where('notifications', array('status' => 1, 'type' => $type))->row();
            if (isset($notification->is_sms) && $notification->is_sms) {
                $appointment = $ci->db->get_where('appointments', array('id' => $data))->row();
                $body = $ci->db->get_where('sms_templates', array('type' => $notification->id))->row();
                if (isset($body) && $body->status) {
                    $message = get_sms_formatted_body($body->template, PATIENT, $type, $data);
                    create_sms_log($message, $appointment->phone, $type, $appointment);
                    return $ci->mimsms->sendMimSms($appointment->phone, $message);
                }
            }
        }

        // IPD Admission Patients Message

        elseif ($type === 'ipd_admission') {
            $notification = $ci->db->get_where('notifications', array('status' => 1, 'type' => $type))->row();
            if (isset($notification->is_sms) && $notification->is_sms) {
                $ipd_patient = $ci->db->get_where('ipd_patients', array('id' => $data))->row();
                if ($ipd_patient->patient_id) {
                    $patient = $ci->db->get_where('patients', array('user_id' => $ipd_patient->patient_id))->row();
                }
                $body = $ci->db->get_where('sms_templates', array('type' => $notification->id))->row();
                if (isset($body) && $body->status) {
                    $message = get_sms_formatted_body($body->template, PATIENT, $type, $data);
                    create_sms_log($message, $patient->phone, $type, $ipd_patient);
                    return $ci->mimsms->sendMimSms($patient->phone, $message);
                }
            }
        }

        // IPD Discharged Patients Message

        elseif ($type === 'ipd_discharged') {
            $notification = $ci->db->get_where('notifications', array('status' => 1, 'type' => $type))->row();
            if (isset($notification->is_sms) && $notification->is_sms) {
                $ipd_patient = $ci->db->get_where('ipd_patients', array('id' => $data))->row();
                if ($ipd_patient->patient_id) {
                    $patient = $ci->db->get_where('patients', array('user_id' => $ipd_patient->patient_id))->row();
                }
                $body = $ci->db->get_where('sms_templates', array('type' => $notification->id))->row();
                if (isset($body) && $body->status) {
                    $message = get_sms_formatted_body($body->template, PATIENT, $type, $data);
                    create_sms_log($message, $patient->phone, $type, $ipd_patient);
                    return $ci->mimsms->sendMimSms($patient->phone, $message);
                }
            }
        }

        // IPD Patient Payment Message

        elseif ($type === 'ipd_payment') {
            $notification = $ci->db->get_where('notifications', array('status' => 1, 'type' => $type))->row();
            if (isset($notification->is_sms) && $notification->is_sms) {
                $ipd_payment = $ci->db->get_where('ipd_advance_payments', array('id' => $data))->row();
                if ($ipd_payment->patient_id) {
                    $patient = $ci->db->get_where('patients', array('user_id' => $ipd_payment->patient_id))->row();
                }
                $body = $ci->db->get_where('sms_templates', array('type' => $notification->id))->row();
                if (isset($body) && $body->status) {
                    $message = get_sms_formatted_body($body->template, PATIENT, $type, $data);
                    create_sms_log($message, $patient->phone, $type, $ipd_payment);
                    return $ci->mimsms->sendMimSms($patient->phone, $message);
                }
            }
        }

        // Billing Message

        elseif ($type === 'billing_sms') {
            $notification = $ci->db->get_where('notifications', array('status' => 1, 'type' => $type))->row();
            if (isset($notification->is_sms) && $notification->is_sms) {
                $invoice = $ci->db->get_where('invoices', array('id' => $data))->row();
                if ($invoice->patient_id) {
                    $patient = $ci->db->get_where('patients', array('user_id' => $invoice->patient_id))->row();
                }
                $body = $ci->db->get_where('sms_templates', array('type' => $notification->id))->row();
                if (isset($body) && $body->status) {
                    $message = get_sms_formatted_body($body->template, PATIENT, $type, $data);
                    create_sms_log($message, $patient->phone, $type, $invoice);
                    return $ci->mimsms->sendMimSms($patient->phone, $message);
                }
            }
        }

        // Billing Payment Message

        elseif ($type === 'billing_payment_sms') {
            $notification = $ci->db->get_where('notifications', array('status' => 1, 'type' => $type))->row();
            if (isset($notification->is_sms) && $notification->is_sms) {
                $invoice_payment = $ci->db->get_where('invoice_payments', array('id' => $data))->row();
                $invoice = $ci->db->get_where('invoices', array('id' => $invoice_payment->invoice_id))->row();
                if ($invoice->patient_id) {
                    $patient = $ci->db->get_where('patients', array('user_id' => $invoice->patient_id))->row();
                }
                $body = $ci->db->get_where('sms_templates', array('type' => $notification->id))->row();
                if (isset($body) && $body->status) {
                    $message = get_sms_formatted_body($body->template, PATIENT, $type, $data);
                    create_sms_log($message, $patient->phone, $type, $invoice_payment);
                    return $ci->mimsms->sendMimSms($patient->phone, $message);
                }
            }
        }

        // Investigation Commission Payment Message

        elseif ($type === 'investigation_payment_sms') {
            $notification = $ci->db->get_where('notifications', array('status' => 1, 'type' => $type))->row();
            if (isset($notification->is_sms) && $notification->is_sms) {
                $payment = $ci->db->get_where('payments', array('id' => $data))->row();
                if ($payment->commission_user_id) {
                    $commission = $ci->db->get_where('employees', array('user_id' => $payment->commission_user_id))->row();
                }
                $body = $ci->db->get_where('sms_templates', array('type' => $notification->id))->row();
                if (isset($body) && $body->status) {
                    $message = get_sms_formatted_body($body->template, PATIENT, $type, $data);
                    create_sms_log($message, $commission->phone, $type, $payment);
                    return $ci->mimsms->sendMimSms($commission->phone, $message);
                }
            }
        } else {
            return false;
        }
    }
}

if (!function_exists('create_sms_log')) {

    function create_sms_log($message = null, $phone = null, $type = null, $userData = null)
    {

        $ci = &get_instance();
        $data = array();
        $sms_setting = $ci->db->get_where('sms_settings', array('status' => 1))->row();

        if ($type == 'appointment') {
            $role_id = PATIENT;
            $user_id = $userData->patient_id ?? null;
            $data_id = $userData->id;
        }

        if ($type == 'ipd_admission') {
            $role_id = PATIENT;
            $user_id = $userData->patient_id ?? null;
            $data_id = $userData->id;
        }

        if ($type == 'ipd_discharged') {
            $role_id = PATIENT;
            $user_id = $userData->patient_id ?? null;
            $data_id = $userData->id;
        }

        if ($type == 'ipd_payment') {
            $role_id = PATIENT;
            $user_id = $userData->patient_id ?? null;
            $data_id = $userData->id;
        }

        if ($type == 'billing_sms') {
            $role_id = PATIENT;
            $user_id = $userData->patient_id ?? null;
            $data_id = $userData->id;
        }

        if ($type == 'billing_payment_sms') {
            $role_id = PATIENT;
            $user_id = $userData->patient_id ?? null;
            $data_id = $userData->id;
        }

        if ($type == 'investigation_payment_sms') {
            $role_id = PATIENT;
            $user_id = $userData->patient_id ?? null;
            $data_id = $userData->id;
        }

        if ($type == 'general') {
            $role_id = $userData['role_id'];
            $user_id = $userData['user_id'] ?? null;
            $data_id = null;
        }

        if ($type == 'patient') {
            $role_id = $userData['role_id'];
            $user_id = $userData['user_id'] ?? null;
            $data_id = null;
        }

        if ($type == 'opd_patient') {
            $role_id = $userData['role_id'];
            $user_id = $userData['user_id'] ?? null;
            $data_id = null;
        }

        if ($type == 'ipd_patient') {
            $role_id = $userData['role_id'];
            $user_id = $userData['user_id'] ?? null;
            $data_id = null;
        }

        if ($type == 'doctor') {
            $role_id = $userData['role_id'];
            $user_id = $userData['user_id'] ?? null;
            $data_id = null;
        }

        if ($type == 'vd') {
            $role_id = $userData['role_id'];
            $user_id = $userData['user_id'] ?? null;
            $data_id = null;
        }

        if ($type == 'employee') {
            $role_id = $userData['role_id'];
            $user_id = $userData['user_id'] ?? null;
            $data_id = null;
        }

        $data['role_id'] = $role_id;
        $data['user_id'] =  $user_id;
        $data['data_id'] = $data_id;
        $data['sender_id'] = $sms_setting->mimsms_sender_id;
        $data['charged'] = $sms_setting->price;
        $data['sms_type'] = $type;
        $data['operator'] = get_operator($phone);
        $data['label'] =  1; // 1 = transactional; 0 = promotional
        $data['sms_text'] = $message;
        $data['status'] = 1;
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['created_by'] = logged_in_user_id();
        $ci->db->insert('text_message_logs', $data);
    }
}

if (!function_exists('get_operator')) {

    function get_operator($number = null)
    {
        if (strstr($number, '017') || strstr($number, '013')) {
            $operator = 'GP';
        } elseif (strstr($number, '019') || strstr($number, '014')) {
            $operator = 'Banglalink';
        } elseif (strstr($number, '018')) {
            $operator = 'Robi';
        } elseif (strstr($number, '016')) {
            $operator = 'Airtel';
        } else {
            $operator = 'Teletalk';
        }
        return $operator;
    }
}

if (!function_exists('get_sms_type')) {

    function get_sms_type()
    {
        $ci = &get_instance();
        return array(
            'general' => $ci->lang->line('general'),
            'patient' => $ci->lang->line('patient'),
            'opd_patient' => $ci->lang->line('opd_patient'),
            'ipd_patient' => $ci->lang->line('ipd_patient'),
            'doctor' => $ci->lang->line('doctor'),
            'vd' => $ci->lang->line('vd'),
            'employee' => $ci->lang->line('employee'),
            'appointment' => $ci->lang->line('appointment'),
            'ipd_admission' => $ci->lang->line('ipd') . ' ' . $ci->lang->line('admission'),
            'ipd_discharged' => $ci->lang->line('ipd') . ' ' . $ci->lang->line('discharged'),
            'ipd_payment' => $ci->lang->line('ipd') . ' ' . $ci->lang->line('payment'),
            'billing_sms' => $ci->lang->line('billing') . ' ' . $ci->lang->line('sms'),
            'billing_payment_sms' => $ci->lang->line('billing') . ' ' . $ci->lang->line('payment'),
            'investigation_payment_sms' => $ci->lang->line('investigation') . ' ' . $ci->lang->line('payment'),
            'reset_pass' => $ci->lang->line('reset') . ' ' . $ci->lang->line('password')
        );
    }
}

if (!function_exists('get_operator_type')) {

    function get_operator_type()
    {
        return array(
            'GP' => 'GP',
            'Banglalink' => 'Banglalink',
            'Robi' => 'Robi',
            'Airtel' => 'Airtel',
            'Teletalk' => 'Teletalk'
        );
    }
}

if (!function_exists('get_sms_balance')) {

    function get_sms_balance()
    {
        $ci = &get_instance();
        $sms_setting = $ci->db->get_where('sms_settings', array('status' => 1))->row();
        if (isset($sms_setting) && $sms_setting->mimsms_status) {
            $api =  'https://esms.mimsms.com/miscapi/' . $sms_setting->mimsms_api_key . '/getBalance/';
            return @file_get_contents($api);
        }
    }
}

if (!function_exists('appointment_history')) {

    function appointment_history($old_data = NULL, $new_data = NULL)
    {

        $ci = &get_instance();
        $data = array();
        $data['old_data'] = json_encode($old_data);
        $data['new_data'] = json_encode($new_data);
        $data['ip_address'] = $_SERVER['REMOTE_ADDR'];
        $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
        $data['status'] = 1;
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['created_by'] = logged_in_user_id();
        $ci->db->insert('appointment_histories', $data);
    }
}

if (!function_exists('get_doctor_name')) {

    function get_doctor_name($doctor_id = NULL)
    {

        $ci = &get_instance();
        $ci->db->select('E.name, E.phone');
        $ci->db->from('employees AS E');
        $ci->db->where('E.user_id', $doctor_id);
        return $ci->db->get()->row()->name;
    }
}
if (!function_exists('get_days_between')) {

    function get_days_between($dateOne = null, $dateTwo = null)
    {
        return date_diff(
            date_create($dateOne ?? date('Y-m-d')),
            date_create($dateTwo ?? date('Y-m-d'))
        )->format('%a');
    }
}

if (!function_exists('getEmployeesWithoutAttendance')) {

    function getEmployeesWithoutAttendance($user_id, $date)
    {
        $ci = &get_instance();
        $ci->db->select('A.user_id');
        $ci->db->from('attendances AS A');
        if ($user_id) {
            $ci->db->where('A.user_id', $user_id);
        }
        if ($date) {
            $ci->db->where("DATE(A.date)", $date);
        }
        return $ci->db->get()->row();
    }
}

if (!function_exists('get_professions')) {

    function get_professions()
    {
        $ci = &get_instance();
        return array(
            'farmer' => 'Farmer',
            'teacher' => 'Teacher',
            'doctor' => 'Doctor',
            'other' => 'Other'
        );
    }
}
