<?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('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[] = '[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);
        $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_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_patient_category')) {

    function get_patient_category()
    {
        $ci = &get_instance();
        return array(
            'silver' => 'Silver',
            'gold' => 'Gold',
            'diamond' => 'Diamond',
            '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('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('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",
            'Etc/GMT-13' => "Etc/GMT-13",
            'Etc/GMT-14' => "Etc/GMT-14",
        );

        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',
            'serum' => 'Semen',
            'urine' => 'Urine',
            'usg' => 'USG',
            'xray' => 'X-Ray',
            'ecg' => 'ECG',
            'echo' => 'ECHO',
            'stool' => 'Stool',
            'skin' => 'Skin',
            'tissue' => 'Tissue',
            'sputum' => 'Sputum',
        );
    }
}

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_ipd_medicine')) {

    function get_ipd_medicine()
    {
        $ci = &get_instance();
        return array(
            'patient' => $ci->lang->line('patient'),
            'hospital' => $ci->lang->line('hospital')
        );
    }
}

if (!function_exists('get_ipd_oxygen')) {

    function get_ipd_oxygen()
    {
        $ci = &get_instance();
        return array(
            'patient' => $ci->lang->line('patient'),
            'hospital' => $ci->lang->line('hospital')
        );
    }
}

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'),
        );
    }
}

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_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,
                '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://www.mimsms.com.bd/smsAPI?balance&apikey=' . $sms_setting->mimsms_api_key . '&apitoken=j2IC1669898677';
            $check = @file_get_contents($api);
            return 0;
            // if ($check) {
            //     return $check;
            // }
        }
    }
}

if (!function_exists('get_ipd_advanced_amount')) {

    function get_ipd_advanced_amount($ipd_id, $patient_id)
    {

        $ci = &get_instance();

        $ci->db->select_sum('amount');
        $ci->db->from('ipd_advance_payments');
        $ci->db->where('ipd_id', $ipd_id);
        $ci->db->where('patient_id', $patient_id);
        $ci->db->where('payment_status', 'complete');
        $amount = $ci->db->get()->row()->amount;
        return $amount;
    }
}