<?php

if (!function_exists('printing_options')) {

    function printing_options() {
        $CI = & get_instance();
        return array(
            '6' => $CI->lang->line('gkpos_kitchen_print_setting6'),
            '1' => $CI->lang->line('gkpos_kitchen_print_setting1'),
            '2' => $CI->lang->line('gkpos_kitchen_print_setting2'),
            '3' => $CI->lang->line('gkpos_kitchen_print_setting3'),
            '4' => $CI->lang->line('gkpos_kitchen_print_setting4'),
            '5' => $CI->lang->line('gkpos_kitchen_print_setting5'),
            '7' => $CI->lang->line('gkpos_kitchen_print_setting7'),
        );
    }

}
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('calculate_discount')) {

    function calculate_discount($order_id, $total, $foodTotal, $nonFoodTotal, $data) {
        $CI = & get_instance();
        $discount = 0;
        $discount_string = '';
        if (!isset($data['func'])) {
            $data['func'] = 1;
        }
        $food = isset($data['food']) && $data['food'] == 'yes' ? true : false;
        $nonfood = isset($data['nonfood']) && $data['nonfood'] == 'yes' ? true : false;
        $both = ($food && $nonfood) ? true : false;
        if (!isset($data['food']) && !isset($data['nonfood']) && $both == false) {
            $both = true;
        }
        $status = '';
        if (true == $both) {
            if (isset($data['func']) && $data['func'] == 1) {
                $discount = $total * $data['number'] / 100;
                $discount_string = "(" . $data['number'] . "%)";
            } else {
                $discount = $data['number'];
            }
            $status = 'both';
        }
        if (true == $food && false == $both) {
            if (isset($data['func']) && $data['func'] == 1) {
                $discount = $foodTotal * $data['number'] / 100;
                $discount_string = "(" . $data['number'] . "%)";
            } else {
                $discount = $data['number'];
            }
            $status = 'food';
        }
        if (true == $nonfood && false == $both) {
            if (isset($data['func']) && $data['func'] == 1) {
                $discount = $nonFoodTotal * $data['number'] / 100;
                $discount_string = "(" . $data['number'] . "%)";
            } else {
                $discount = $data['number'];
            }
            $status = 'nonfood';
        }

        $CI->Orders_Model->set_discount_amount($order_id, $discount);
        return array('discount' => $discount, 'dsicount_string' => $discount_string, 'where' => array('food' => $food, 'nonfood' => $nonfood, 'both' => $both));
    }

}

if (!function_exists('calculate_service_charge')) {

    function calculate_service_charge($order_id, $total, $data) {
        $service_charge = 0;
        if ($total > 0 && isset($data['func']) && $data['func'] == 1) {
            $service_charge = $total * $data['number'] / 100;
        } else {
            $service_charge = isset($data['number']) && $data['number'] > 0 ? $data['number'] : $service_charge;
        }
        $CI = & get_instance();
        $CI->Orders_Model->set_servicecharge_amount($order_id, $service_charge);
        return $service_charge;
    }

}

if (!function_exists('calculate_vat')) {

    function calculate_vat($order_id, $total, $vat_data) {
        $vat = 0;
        if ($vat_data['func'] == 1) {
            $vat = $total * $vat_data['number'] / 100;
        }
        $CI = & get_instance();
        $CI->Orders_Model->set_vat_amount($order_id, $vat);
        return $vat;
    }

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

    function gkpos_dateformat($php_format) {
        $SYMBOLS_MATCHING = array(
            // Day
            'd' => 'dd',
            'D' => 'd',
            'j' => 'd',
            'l' => 'dd',
            'N' => '',
            'S' => '',
            'w' => '',
            'z' => '',
            // Week
            'W' => '',
            // Month
            'F' => 'MM',
            'm' => 'mm',
            'M' => 'M',
            'n' => 'm',
            't' => '',
            // Year
            'L' => '',
            'o' => '',
            'Y' => 'yyyy',
            'y' => 'yy',
            // Time
            'a' => 'p',
            'A' => 'P',
            'B' => '',
            'g' => 'H',
            'G' => 'h',
            'h' => 'HH',
            'H' => 'hh',
            'i' => 'ii',
            's' => 'ss',
            'u' => ''
        );

        $bootstrap_format = "";
        $escaping = false;
        for ($i = 0; $i < strlen($php_format); $i++) {
            $char = $php_format[$i];
            if ($char === '\\') { // PHP date format escaping character
                $i++;
                if ($escaping)
                    $bootstrap_format .= $php_format[$i];
                else
                    $bootstrap_format .= '\'' . $php_format[$i];
                $escaping = true;
            }
            else {
                if ($escaping) {
                    $bootstrap_format .= "'";
                    $escaping = false;
                }
                if (isset($SYMBOLS_MATCHING[$char]))
                    $bootstrap_format .= $SYMBOLS_MATCHING[$char];
                else
                    $bootstrap_format .= $char;
            }
        }

        return $bootstrap_format;
    }

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

    function gkpos_chopstring($incoming_string, $x = 200) {
        $string = strip_tags(stripslashes($incoming_string)); // convert to plaintext
        return substr($string, 0, strpos(wordwrap($string, $x), "\n"));
    }

}


if (!function_exists('postcodeFormat')) {

    function postcodeFormat($postcode) {
        //trim and remove spaces
        $cleanPostcodeParam = preg_replace("/[^A-Za-z0-9]/", '', $postcode);
        //make uppercase
        $cleanPostcode = strtoupper($cleanPostcodeParam);
        //if 5 charcters, insert space after the 2nd character
        if (strlen($cleanPostcode) == 5) {
            $postcode = substr($cleanPostcode, 0, 2) . " " . substr($cleanPostcode, 2, 3);
        }
        //if 6 charcters, insert space after the 3rd character
        elseif (strlen($cleanPostcode) == 6) {
            $postcode = substr($cleanPostcode, 0, 3) . " " . substr($cleanPostcode, 3, 3);
        }
        //if 7 charcters, insert space after the 4th character
        elseif (strlen($cleanPostcode) == 7) {
            $postcode = substr($cleanPostcode, 0, 4) . " " . substr($cleanPostcode, 4, 3);
        }
        return $postcode;
    }

}

if (!function_exists('formatPhoneNumber')) {

    function formatPhoneNumber($IncomingPhoneNumber) {
        $phoneNumber = preg_replace('/[^0-9]/', '', $IncomingPhoneNumber);
        if (strlen($phoneNumber) > 10) {
            $countryCode = substr($phoneNumber, 0, strlen($phoneNumber) - 10);
            $areaCode = substr($phoneNumber, -10, 3);
            $nextThree = substr($phoneNumber, -7, 3);
            $lastFour = substr($phoneNumber, -4, 4);
            $phoneNumber = '+' . $countryCode . ' (' . $areaCode . ') ' . $nextThree . '-' . $lastFour;
        } else if (strlen($phoneNumber) == 10) {
            $areaCode = substr($phoneNumber, 0, 3);
            $nextThree = substr($phoneNumber, 3, 3);
            $lastFour = substr($phoneNumber, 6, 4);
            $phoneNumber = '(' . $areaCode . ') ' . $nextThree . '-' . $lastFour;
        } else if (strlen($phoneNumber) == 7) {
            $nextThree = substr($phoneNumber, 0, 3);
            $lastFour = substr($phoneNumber, 3, 4);
            $phoneNumber = $nextThree . '-' . $lastFour;
        }
        return $phoneNumber;
    }

}

if (!function_exists('get_order_type')) {

    function get_order_type($id) {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM gkpos_order
               WHERE id = $id              
               ";
        return $ci->db->query($sql)->row()->order_type;
    }

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

    function get_user_name($id) {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM gkpos_user
               WHERE id = $id              
               ";
        $row = $ci->db->query($sql)->row();
        $name = '';
        if (!empty($row)) {
            $user = '';
            if ($row->first_name != '') {
                $user .= $row->first_name;
            }
            if ($row->first_name != '') {
                $user .= ' ' . $row->last_name;
            }
            $name = ($user == null || $user == '') ? $row->username : $user;
        } else {
            $name = 'undefined';
        }
        return $name;
    }

}



if (!function_exists('checkfile')) {

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

}

if (!function_exists('get_gkcategory_name')) {

    function get_gkcategory_name($id) {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM gkpos_category
               WHERE id = $id              
               ";

        $obj = $ci->db->query($sql)->row();
        if ($obj && $obj->title) {
            return $obj->title;
        }
    }

}

if (!function_exists('get_topping_category_name')) {

    function get_topping_category_name($id) {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM toppings_category
               WHERE id = $id              
               ";
        return $ci->db->query($sql)->row();
    }

}

if (!function_exists('get_menu_info_by_id')) {

    function get_menu_info_by_id($id) {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM gkpos_menu
               WHERE id = $id              
               ";
        return $ci->db->query($sql)->row();
    }

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

    function get_selection_info_by_id($id) {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM gkpos_selection
               WHERE id = $id              
               ";
        return $ci->db->query($sql)->row();
    }

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

    function get_topping_info_by_id($id) {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM toppings
               WHERE id = $id              
               ";
        return $ci->db->query($sql)->row();
    }

}

if (!function_exists('get_driver_info')) {

    function get_driver_info($id) {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM gkpos_driver
               WHERE id = $id              
               ";
        return $ci->db->query($sql)->row();
    }

}


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('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_delivery_distance')) {

        function get_delivery_distance($orgins, $destination) {
            $CI = & get_instance();
            $key = trim($CI->config->item('google_map_api_key')) != null ? $CI->config->item('google_map_api_key') : GOOGLE_API_KEY;
            $url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=" . urlencode($orgins) . "&destinations=" . urlencode($destination) . "&mode=driving&language=en&key=" . $key;
            $drivingdetails = json_decode(file_get_contents($url));
            if (isset($drivingdetails->rows[0]->elements[0]->distance)) {
                $distance_text = $drivingdetails->rows[0]->elements[0]->distance->text;
                return (double) str_replace('mi', '', $distance_text);
            } else {
                return 0;
            }
        }

    }
}

function detectDevice() {
    $ua = $_SERVER["HTTP_USER_AGENT"];
    $android = strpos($ua, 'Android') ? true : false;
    $blackberry = strpos($ua, 'BlackBerry') ? true : false;
    $iphone = strpos($ua, 'iPhone') ? true : false;
    $iphone = strpos($ua, 'iPad') ? true : false;
    $palm = strpos($ua, 'Palm') ? true : false;
    if ($android || $blackberry || $iphone || $palm) {
        return true;
    }
}

if (!function_exists('get_specials')) {

    function get_specials() {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM gkpos_special
               WHERE status = '1'             
               ";
        return $ci->db->query($sql)->result();
    }

}

if (!function_exists('get_template')) {

    function get_template() {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM template
                ";
        $result = $ci->db->query($sql)->result();
        $organizedResult = array();
        if (!empty($result)) {
            foreach ($result as $key => $obj) {
                $organizedResult[$obj->wrapper] = $obj;
            }
        }
        return $organizedResult;
    }

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

    function get_customer_name($phone) {
        $ci = & get_instance();
        $sql = " SELECT *
                   FROM gkpos_customer
               WHERE phone = $phone              
               ";
        return $ci->db->query($sql)->row()->name;
    }

}

