<?php

if (!function_exists('debugPrint')) {

    function debugPrint($object, $title = "", $isMarkup = false) {
        echo '<font color="red">Debug <<< START';
        if (!empty($title)) {
            echo "$title: ";
        }
        if ($isMarkup == false) {
            echo "<pre>";
            print_r($object);
            echo "</pre>";
        } else {
            echo htmlspecialchars($object);
        }
        echo 'END >>></font>';
    }

}
if (!function_exists('get_record_list')) {

    function get_record_list($table, $condition = null, $columns = '*', $order = null) {
        $CI = & get_instance();
        $CI->db->select($columns);
        if ($order)
            $CI->db->order_by($order);
        if ($condition)
            $CI->db->where($condition);
        return $CI->db->get($table)->result();
    }

}
if (!function_exists('get_single_record')) {

    function get_single_record($table, $condition = null, $columns = '*', $order = null) {
        $CI = & get_instance();
        $CI->db->select($columns);
        if ($order)
            $CI->db->order_by($order);
        if ($condition)
            $CI->db->where($condition);
        return $CI->db->get($table)->row();
    }

}
if (!function_exists('count_rows')) {

    function count_rows($table, $condition = null) {
        $CI = & get_instance();
        if ($condition) {
            $CI->db->where($condition);
        }
        $CI->db->from($table);
        return $CI->db->count_all_results();
    }

}
if (!function_exists('get_title')) {

    function get_title($table, $condition) {
        $record = get_single_record($table, $condition);
        return !empty($record) ? $record->title : '';
    }

}


if (!function_exists('objectToArray')) {

    function objectToArray($d) {
        if (is_object($d)) {
            $d = get_object_vars($d);
        }
        if (is_array($d)) {
            return array_map(__FUNCTION__, $d);
        } else {
            return $d;
        }
    }

}
if (!function_exists('checkfile')) {

    function checkfile($path = '', $file = '') {
        $filename = $path . $file;
        if (file_exists($filename)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

}
if (!function_exists('timezone_list')) {

    function timezone_list() {
        $zones_array = array();
        $timestamp = time();
        foreach (timezone_identifiers_list() as $key => $zone) {
            date_default_timezone_set($zone);
            $zones_array[$key]['zone'] = $zone;
            $zones_array[$key]['diff_from_GMT'] = 'UTC/GMT ' . date('P', $timestamp);
        }
        return $zones_array;
    }

}
if (!function_exists('to_currency')) {

    function to_currency($number, $escape = FALSE) {
        $CI = & get_instance();
        if ($CI->config->item('locale_currencysymbol')) {
            $currency_symbol = $CI->config->item('locale_currencyicon') ? $CI->config->item('locale_currencyicon') : $CI->config->item('locale_currencyicon');
            $thousands_separator = $CI->config->item('locale_thouandseparator') ? $CI->config->item('locale_thouandseparator') : '';
            $decimal_point = $CI->config->item('locale_decimalpoint') ? $CI->config->item('locale_decimalpoint') : '.';
            $decimals = $CI->config->item('locale_currencydecimal') ? $CI->config->item('locale_currencydecimal') : 0;
            if ($number >= 0) {
                if (trim($CI->config->item('locale_currencyside')) === 'left') {
                    return $currency_symbol . '' . number_format($number, $decimals, $decimal_point, $thousands_separator);
                } else {
                    return number_format($number, $decimals, $decimal_point, $thousands_separator) . ' ' . $currency_symbol;
                }
            } else {
                if (trim($CI->config->item('locale_currencyside')) === 'left') {
                    return $currency_symbol . '' . '-' . number_format(abs($number), $decimals, $decimal_point, $thousands_separator);
                } else {
                    return '-' . number_format(abs($number), $decimals, $decimal_point, $thousands_separator) . ' ' . $currency_symbol;
                }
            }
        }
    }

}
if (!function_exists('to_currency_no_money')) {

    function to_currency_no_money($number) {
        if (empty($number)) {
            return $number;
        }
        $CI = & get_instance();
        $decimals = $CI->config->item('locale_currencydecimal') ? $CI->config->item('locale_currencydecimal') : 0;
        return number_format($number, $decimals, '.', '');
    }

}
if (!function_exists('totals_decimals')) {

    function totals_decimals() {
        $CI = & get_instance();
        $decimals = $CI->config->item('locale_currencydecimal') ? $CI->config->item('locale_currencydecimal') : 0;
        return $decimals;
    }

}
if (!function_exists('to_tax_decimals')) {

    function to_tax_decimals($number) {
        if (empty($number)) {
            return $number;
        }

        $CI = & get_instance();
        $decimal_point = $CI->config->item('locale_decimalpoint') ? $CI->config->item('locale_decimalpoint') : '.';
        $decimals = $CI->config->item('locale_taxdecimal') ? $CI->config->item('locale_taxdecimal') : 0;
        return number_format($number, $decimals, $decimal_point, '');
    }

}
if (!function_exists('to_quantity_decimals')) {

    function to_quantity_decimals($number) {
        $CI = & get_instance();
        $decimal_point = $CI->config->item('locale_decimalpoint') ? $CI->config->item('locale_decimalpoint') : '.';
        $decimals = $CI->config->item('locale_quantitydecimal') ? $CI->config->item('locale_quantitydecimal') : 0;
        return number_format($number, $decimals, $decimal_point, '');
    }

}
if (!function_exists('quantity_decimals')) {

    function quantity_decimals() {
        $CI = & get_instance();
        return $CI->config->item('locale_quantitydecimal') ? $CI->config->item('locale_quantitydecimal') : 0;
    }

}
if (!function_exists('currencies')) {

    function currencies() {
        return array(
            'BDT' => 'Bangladeshi Taka',
            'GBP' => 'United Kingdom Pound',
            'USD' => 'United States Dollar',
        );
    }

}
if (!function_exists('getItemPrice')) {

    function getItemPrice($item) {
        if ($item->out_price > 0) {
            return to_currency($item->out_price);
        } else {
            return to_currency($item->base_price);
        }
    }

}


if (!function_exists('getDrivingDistance')) {

    function getDrivingDistance($orgins, $destination, $apiKey) {
        $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" . urlencode($orgins) . "&destinations=" . urlencode($destination) . "&mode=driving&language=en-EN&sensor=false&key=" . $apiKey . "";
        $data = @file_get_contents($url);
        $result = json_decode($data, true);
        if (isset($result ['rows'][0]['elements'][0]['distance'])) {
            $distance = array(
                "meters" => $result["rows"][0]["elements"][0]["distance"]["value"],
                "kilometers" => $result["rows"][0]["elements"][0]["distance"]["value"] / 1000,
                "yards" => $result["rows"][0]["elements"][0]["distance"]["value"] * 1.0936133,
                "miles" => $result["rows"][0]["elements"][0]["distance"]["value"] * 0.000621371,
                "status" => $result['status']
            );
            return ($distance);
        } else {
            $distance = array(
                "meters" => 0,
                "kilometers" => 0,
                "yards" => 0,
                "miles" => 0,
                "status" => $result['status']
            );
            return $distance;
        }
    }

}
if (!function_exists('postcodeFormat')) {

    function postcodeFormat($postcode) {
        $cleanPostcodeParam = preg_replace("/[^A-Za-z0-9]/", '', $postcode);
        $cleanPostcode = strtoupper($cleanPostcodeParam);
        if (strlen($cleanPostcode) == 5) {
            $postcode = substr($cleanPostcode, 0, 2) . " " . substr($cleanPostcode, 2, 3);
        } elseif (strlen($cleanPostcode) == 6) {
            $postcode = substr($cleanPostcode, 0, 3) . " " . substr($cleanPostcode, 3, 3);
        } elseif (strlen($cleanPostcode) == 7) {
            $postcode = substr($cleanPostcode, 0, 4) . " " . substr($cleanPostcode, 4, 3);
        }
        return $postcode;
    }

}
if (!function_exists('getExpenseColumnSum')) {

    function getExpenseColumnSum($id, $field) {
        $CI = & get_instance();
        $CI->db->select_sum($field);
        $CI->db->where('ledger', $id);
        return $CI->db->get('expense')->row();
    }

}
if (!function_exists('getIncomeColumnSum')) {

    function getIncomeColumnSum($id, $field) {
        $CI = & get_instance();
        $CI->db->select_sum($field);
        $CI->db->where('ledger', $id);
        return $CI->db->get('income')->row();
    }

}
if (!function_exists('isDevice')) {

    function isDevice($device) {
        $ua = $_SERVER["HTTP_USER_AGENT"];
        switch ($device) {
            case 'Android':
                return strpos($ua, 'Android') ? true : false;
            case 'BlackBerry':
                return strpos($ua, 'BlackBerry') ? true : false;
            case 'iPhone':
                return strpos($ua, 'iPhone') ? true : false;
            case 'iPad':
                return strpos($ua, 'iPad') ? true : false;
            case 'Palm':
                return strpos($ua, 'Palm') ? true : false;
            case 'Electron':
                return strpos($ua, 'Electron') ? true : false;
            default :
                return false;
        }
    }

}
if (!function_exists('convertToBanglaNumber')) {

    function convertToBanglaNumber($englishNumber) {
        $englishNumber = (string) $englishNumber;
        $banglaNumber = '';
        $indexLimit = strlen($englishNumber);
        for ($i = 0; $i < $indexLimit; $i++) {
            switch ($englishNumber[$i]) {
                case "0":
                    $banglaNumber .= '&#2534;';
                    break;
                case "1":
                    $banglaNumber .= '&#2535;';
                    break;
                case "2":
                    $banglaNumber .= '&#2536;';
                    break;
                case "3":
                    $banglaNumber .= '&#2537;';
                    break;
                case "4":
                    $banglaNumber .= '&#2538;';
                    break;
                case "5":
                    $banglaNumber .= '&#2539;';
                    break;
                case "6":
                    $banglaNumber .= '&#2540;';
                    break;
                case "7":
                    $banglaNumber .= '&#2541;';
                    break;
                case "8":
                    $banglaNumber .= '&#2542;';
                    break;
                case "9":
                    $banglaNumber .= '&#2543;';
                    break;
                default:
                    $banglaNumber .= $englishNumber[$i];
                    break;
            }
        }
        return $banglaNumber;
    }

}
if (!function_exists('convertToBanglaNumber')) {

    function getBanglaDigit($input) {
        $bn_digits = array('০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯');
        $output = str_replace(range(0, 9), $bn_digits, $input);
        return $output;
    }

}
if (!function_exists('serviceTime')) {

    function serviceTime($branch = 1) {
        $CI = & get_instance();
        $serviceSchedule = get_record_list('servicetimehead', array('branch' => $branch));
        $serviceTime = array();
        if (!empty($serviceSchedule)) {
            foreach ($serviceSchedule as $aSchedule) {
                $allRecords = get_record_list('servicetime', array('branch' => $branch, 'schedule' => $aSchedule->id));
                if (!empty($allRecords)) {
                    foreach ($allRecords as $aRecord) {
                        $serviceTime[$aSchedule->title][$aRecord->day] = $aRecord;
                    }
                }
            }
        }
        return $serviceTime;
    }

}
if (!function_exists('isRestaurantOpenNow')) {

    function isRestaurantOpenNow() {
        $resultArray = array();
        $nowTime = strtotime(date('h:i a'));
        $serviceTime = serviceTime();
        if (!empty($serviceTime)) {
            foreach ($serviceTime as $time) {
                if ($time[date('D')]->opened == '3') {
                    $startTime = strtotime(date('h:i a', strtotime($time[date('D')]->start)));
                    $endTime = strtotime(date('h:i a', strtotime($time[date('D')]->end)));
                    if ($nowTime >= $startTime && $nowTime <= $endTime) {
                        array_push($resultArray, 'yes');
                    } else {
                        array_push($resultArray, 'no');
                    }
                } else {
                    array_push($resultArray, 'no');
                }
            }
        }
        return in_array('yes', $resultArray) ? true : false;
    }

}

if (!function_exists('isTodayOpened')) {

    function isTodayOpened() {
        $resultArray = array();
        $serviceTime = serviceTime();
        foreach ($serviceTime as $time) {
            if ($time[date('D')]->opened == '3') {
                array_push($resultArray, 'yes');
            } else {
                array_push($resultArray, 'no');
            }
        }
        return in_array('yes', $resultArray) ? true : false;
    }

}

if (!function_exists('getDiscountPlan')) {

    function getDiscountPlan() {
        $list = get_record_list('discountplan', array('status' => '3', 'start_date<=' => date('Y-m-d'), 'end_date>=' => date('Y-m-d')));
        return $list;
    }

}
if (!function_exists('getDiscountPromo')) {

    function getDiscountPromo() {
        $list = get_record_list('discountpromo', array('status' => '3', 'start_date<=' => date('Y-m-d'), 'end_date>=' => date('Y-m-d')));
        return $list;
    }

}
if (!function_exists('getDiscountMulti')) {

    function getDiscountMulti() {
        $list = get_record_list('discountmulti', array('status' => '3', 'start_date<=' => date('Y-m-d'), 'end_date>=' => date('Y-m-d')));
        return $list;
    }

}
if (!function_exists('getFeaturedItems')) {

    function getFeaturedItems() {
        $data['menus'] = get_record_list('menu', array('status' => '3', 'featured' => 'yes', 'image<>' => ''));
        if (!empty($data['menus'])) {
            foreach ($data['menus'] as $item) {
                $data['selections'][$item->id] = get_record_list('menuselection', array('menu' => $item->id, 'status' => '3', 'featured' => 'yes', 'image<>' => ''));
            }
        }
        return $data;
    }

}
if (!function_exists('getFeaturedCategegory')) {

    function getFeaturedCategegory() {
        return get_record_list('menucategory', array('status' => '3', 'featured' => 'yes', 'image<>' => ''));
    }

}
if (!function_exists('getBreakfastItems')) {

    function getBreakfastItems() {
        $data['menus'] = get_record_list('menu', array('status' => '3', 'breakfast' => 'yes'));
        if (!empty($data['menus'])) {
            foreach ($data['menus'] as $item) {
                $data['selections'][$item->id] = get_record_list('menuselection', array('menu' => $item->id, 'status' => '3', 'breakfast' => 'yes'));
            }
        }
        return $data;
    }

}
if (!function_exists('getLunchItems')) {

    function getLunchItems() {
        $data['menus'] = get_record_list('menu', array('status' => '3', 'launch' => 'yes'));
        if (!empty($data['menus'])) {
            foreach ($data['menus'] as $item) {
                $data['selections'][$item->id] = get_record_list('menuselection', array('menu' => $item->id, 'status' => '3', 'launch' => 'yes'));
            }
        }
        return $data;
    }

}
if (!function_exists('getDinnerItems')) {

    function getDinnerItems() {
        $data['menus'] = get_record_list('menu', array('status' => '3', 'dinner' => 'yes'));
        if (!empty($data['menus'])) {
            foreach ($data['menus'] as $item) {
                $data['selections'][$item->id] = get_record_list('menuselection', array('menu' => $item->id, 'status' => '3', 'dinner' => 'yes'));
            }
        }
        return $data;
    }

}
if (!function_exists('getRestaurantInfo')) {

    function getRestaurantInfo($branch = 1) {
        return get_single_record('branch', array('id' => $branch));
    }

}
if (!function_exists('getDomain')) {

    function getDomain() {
        $CI = & get_instance();
        return preg_replace("/^[\w]{2,6}:\/\/([\w\d\.\-]+).*$/", "$1", $CI->config->slash_item('base_url'));
    }

}
if (!function_exists('getDeliveryInformation')) {

    function getDeliveryInformation($branch = 1) {
        $data['apiSetting'] = get_single_record('apisetting', array('branch' => $branch));
        $data['deliveryArea'] = get_record_list('deliveryplan', array('status' => '3', 'branch' => $branch));
        return $data;
    }

}
if (!function_exists('getExtranalLinks')) {

    function getExtranalLinks($branch = 1) {
        $links = get_record_list('extranallinks', array('branch' => $branch));
        $managedLink = array();
        if (!empty($links)) {
            foreach ($links as $link) {
                $managedLink[$link->slug] = $link;
            }
        }
        return $managedLink;
    }

}
if (!function_exists('getFreeDishOffer')) {

    function getFreeDishOffer($branch = 1) {
        $freeDish = get_record_list('discountitem', array('branch' => $branch, 'status' => 3));
        if (!empty($freeDish)) {
            foreach ($freeDish as $key => $dish) {
                $freeDish[$key]->type = unserialize($dish->type);
                $freeDish[$key]->item = unserialize($dish->item);
            }
        }
        return $freeDish;
    }

}

if (!function_exists('CallAPI')) {

    function CallAPI($method, $url, $data = false) {
        $curl = curl_init();
        switch ($method) {
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);
                if ($data) {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                }
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_PUT, 1);
                break;
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

}

if (!function_exists('format_associativity')) {
    function format_associativity($data)
    {
        $items = array();
        foreach ($data as $key => $value) {
            $items[] = $key;
        }
        return elements($items, $data);
    }
}

/* sms sending required part */
if (!function_exists('sendSMS')) {
    function sendSMS($content)
    {
        $ch = curl_init('https://api.smsbroadcast.co.uk/api-adv.php');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}
if (!function_exists('sms')) {
    function sms($destination, $text, $ref)
    {
        $name=explode(" ",trim(config_item('general_name')));
        $content = 'username=' . rawurlencode('gksoft') . '&password=' . rawurlencode('Ihave3kids') . '&to=' . rawurlencode($destination) . '&from=' . rawurlencode(substr($name[0],0,11)) . '&message=' . rawurlencode($text) . '&ref=' . rawurlencode($ref);
        $smsbroadcast_response = sendSMS($content);
        $response_lines = explode("\n", $smsbroadcast_response);
        $data_line =  $response_lines[0];
        $message_data = explode(':', $data_line);
        return $message_data[0] === "OK";
    }
}
/* sms sending required part end */
/* Email sending required part */
function send_api_email($data)
{
    $CI = &get_instance();
    $CI->load->library('email');
    $config['mailtype'] = 'html';
    $config['send_multipart'] = FALSE;
    $config['wordwrap'] = TRUE;
    $CI->email->initialize($config);
    $CI->email->from($data['from'], $data['from_title']);
    $CI->email->to($data['to']);
    $CI->email->subject($data['subject']);
    $CI->email->message($data['message']);
    $CI->email->reply_to($data['from'], $data['from_title']);
    return $_SERVER['SERVER_NAME'] != 'localhost' ? $CI->email->send() : true;
}
/* sms sending required part end */
