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

// ------------------------------------------------------------------------

if (!function_exists('sendEmail')) {
    function sendEmail($to, $fromAddress, $fromName, $subject, $message, $cc = '', $bcc = '', $html = true)
    {

        $email_config = array(
            'protocol'  => 'smtp',
            'smtp_host' => 'callup2.co',
            'smtp_port' => '26',
            'smtp_user' => 'info@callup2.co',
            'smtp_pass' => '4@%G(.wzMljw',
            'mailtype'  => 'html'
        );
        $CI = &get_instance();
        $CI->load->library('email');
        $CI->email->initialize($email_config);
        $CI->email->from($fromAddress, $fromName);
        $CI->email->to($to);
        $CI->email->cc($cc);
        $CI->email->bcc($bcc);
        $CI->email->subject($subject);
        $CI->email->message($message);
        if ($html) $CI->email->set_mailtype("html");
        if ($CI->email->send()) {
            return true;
        } else {
            //return $CI->email->print_debugger();
            return false;
        }
    }
}


if (!function_exists('sendEmailNiyud')) {
    function sendEmailNiyud($to, $fromAddress, $fromName, $subject, $message, $cc = '', $bcc = '', $html = true)
    {

        $email_config = array(
            'protocol'      => 'smtp',
            'smtp_host'     => 'smtp.gmail.com',
            'smtp_port'     => '587',
            'smtp_user'     => 'portwithu@gmail.com',
            'smtp_pass'     => 'nvmqazjdfhmsrjcy',
            'smtp_auth'     => true,
            'mailtype'      => 'html',
            'newline'       => "\r\n",
            'crlf'          => "\r\n",
            'smtp_crypto'   => "tls"
        );
        $CI = &get_instance();
        $CI->load->library('email');
        $CI->email->initialize($email_config);
        $CI->email->from($fromAddress, $fromName);
        $CI->email->to($to);
        $CI->email->cc($cc);
        $CI->email->bcc($bcc);
        $CI->email->subject($subject);
        $CI->email->message($message);
        if ($html) $CI->email->set_mailtype("html");
        $CI->email->send();
    }
}

if (!function_exists('objectToArray')) {
    function objectToArray($d)
    {
        if (is_object($d)) {
            // Gets the properties of the given object
            // with get_object_vars function
            $d = get_object_vars($d);
        }

        if (is_array($d)) {
            /*
			* Return array converted to object
			* Using __FUNCTION__ (Magic constant)
			* for recursive call
			*/
            return array_map(__FUNCTION__, $d);
        } else {
            // Return array
            return $d;
        }
    }
}

if (!function_exists('arrayToObject')) {
    function arrayToObject($d)
    {
        if (is_array($d)) {
            /*
			* Return array converted to object
			* Using __FUNCTION__ (Magic constant)
			* for recursive call
			*/
            return (object) array_map(__FUNCTION__, $d);
        } else {
            // Return object
            return $d;
        }
    }
}

if (!function_exists('checkEmailExists')) {
    function checkEmailExists($email, $table)
    {
        $CI = &get_instance();
        $CI->db->select('email');
        $CI->db->from($table);
        $CI->db->where('email', $email);
        $query = $CI->db->get();

        $result = $query->result();
        if (count($result) > 0) return $result;
        else return false;
    }
}

if (!function_exists('getAdminId')) {
    function getAdminId()
    {
        $CI = &get_instance();
        if (!empty($CI->session->userdata('userData')->adminId)) {
            return intval($CI->session->userdata('userData')->adminId);
        } else {
            return false;
        }
    }
}

if (!function_exists('getUserId')) {
    function getUserId()
    {
        $CI = &get_instance();
        if (!empty($CI->session->userdata('userData')->userId)) {
            return intval($CI->session->userdata('userData')->userId);
        } else {
            return false;
        }
    }
}

if (!function_exists('debug')) {
    function debug($var, $die = 1)
    {
        print '<pre>';
        print_r($var);
        print '</pre>';
        if ($die) {
            die('DEBUG DIE');
        }
    }
}

if (!function_exists('_debug')) {
    function _debug($var)
    {
        return '<pre>' . print_r($var, true) . '</pre>';
    }
}

if (!function_exists('ip_address_to_number')) {
    function ip_address_to_number($IPaddress)
    {
        if ($IPaddress == '') {
            return 0;
        } else {
            $ips = explode('.', $IPaddress);
            return ($ips[3] + $ips[2] * 256 + $ips[1] * 65536 + $ips[0] * 16777216);
        }
    }
}

if (!function_exists('get_comma_from_array')) {
    function get_comma_from_array($array)
    {
        if (!empty($array)) {
            $data = implode(",", $array);
            return $data;
        }
    }
}

if (!function_exists('get_array_from_comma')) {
    function get_array_from_comma($array)
    {
        if (!empty($array)) {
            $data = explode(",", $array);
            return $data;
        }
    }
}

if (!function_exists('formatDateTime')) {
    function formatDateTime($timeString)
    {
        return date('d/m/Y H:i', strtotime($timeString));
    }
}

if (!function_exists('formatPhone')) {
    function formatPhone($phone)
    {
        if (strlen($phone) == 10) {
            return sprintf("%s-%s-%s", substr($phone, 0, 3), substr($phone, 3, 3), substr($phone, 6));
        } elseif (strlen($phone) == 9) {
            return sprintf("%s-%s", substr($phone, 0, 2), substr($phone, 2));
        } else {
            return $phone;
        }
    }
}

if (!function_exists('defaultValue')) {
    function defaultValue($object, $default)
    {
        if ($object == '') return $default;
        else return $object;
    }
}

if (!function_exists('getValueByColumnAndId')) {
    function getValueByColumnAndId($table, $column, $idColumn, $id)
    {

        $CI = &get_instance();
        $CI->db->select($column);
        $CI->db->from($table);
        $CI->db->where($idColumn, $id);
        $query = $CI->db->get();

        return $query->row();
    }
}

if (!function_exists('alphaID')) {
    /*
     * @author  Kevin van Zonneveld &lt;kevin@vanzonneveld.net>
     * @author  Simon Franz
     * @author  Deadfish
     * @author  SK83RJOSH
     * @copyright 2008 Kevin van Zonneveld (http://kevin.vanzonneveld.net)
     * @license   http://www.opensource.org/licenses/bsd-license.php New BSD Licence
     * @version   SVN: Release: $Id: alphaID.inc.php 344 2009-06-10 17:43:59Z kevin $
     * @link    http://kevin.vanzonneveld.net/
     *
     * @param mixed   $in   String or long input to translate
     * @param boolean $to_num  Reverses translation when true
     * @param mixed   $pad_up  Number or boolean padds the result up to a specified length
     * @param string  $pass_key Supplying a password makes it harder to calculate the original ID
     *
     * @return mixed string or long
     */
    function alphaID($in, $to_num = false, $pad_up = false, $pass_key = null)
    {
        $out   =   '';
        $index = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $base  = strlen($index);

        if ($pass_key !== null) {
            // Although this function's purpose is to just make the
            // ID short - and not so much secure,
            // with this patch by Simon Franz (http://blog.snaky.org/)
            // you can optionally supply a password to make it harder
            // to calculate the corresponding numeric ID

            for ($n = 0; $n < strlen($index); $n++) {
                $i[] = substr($index, $n, 1);
            }

            $pass_hash = hash('sha256', $pass_key);
            $pass_hash = (strlen($pass_hash) < strlen($index) ? hash('sha512', $pass_key) : $pass_hash);

            for ($n = 0; $n < strlen($index); $n++) {
                $p[] =  substr($pass_hash, $n, 1);
            }

            array_multisort($p, SORT_DESC, $i);
            $index = implode($i);
        }

        if ($to_num) {
            // Digital number  <<--  alphabet letter code
            $len = strlen($in) - 1;

            for ($t = $len; $t >= 0; $t--) {
                $bcp = bcpow($base, $len - $t);
                $out = $out + strpos($index, substr($in, $t, 1)) * $bcp;
            }

            if (is_numeric($pad_up)) {
                $pad_up--;

                if ($pad_up > 0) {
                    $out -= pow($base, $pad_up);
                }
            }
        } else {
            // Digital number  -->>  alphabet letter code
            if (is_numeric($pad_up)) {
                $pad_up--;

                if ($pad_up > 0) {
                    $in += pow($base, $pad_up);
                }
            }

            for ($t = ($in != 0 ? floor(log($in, $base)) : 0); $t >= 0; $t--) {
                $bcp = bcpow($base, $t);
                $a   = floor($in / $bcp) % $base;
                $out = $out . substr($index, $a, 1);
                $in  = $in - ($a * $bcp);
            }
        }

        return $out;
    }
}

if (!function_exists('generateRandomString')) {
    function generateRandomString($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }
}

if (!function_exists('printCitiesOptions')) {
    function printCitiesOptions($selected = null)
    {
        $CI = &get_instance();
        $CI->db->select('*');
        $CI->db->from('cities');
        $query = $CI->db->get();

        $cities = arrayToObject($query->result());
        $out = '<option value="">עיר</option>';
        foreach ($cities as $c) {
            if ($selected != null && $selected == $c->cityName) $out .= '<option value="' . $c->cityName . '" selected="selected">' . $c->cityName . '</option>';
            else $out .= '<option value="' . $c->cityName . '">' . $c->cityName . '</option>';
        }
        return $out;
    }
}

if (!function_exists('reindex_by_key')) {
    function reindex_by_key($input, $key = 'id')
    {

        if (!is_array($input)) {
            return $input;
        }

        // FROM:  http://ellislab.com/forums/viewthread/193209/
        $result = array();
        foreach ($input as $i) {
            $result[$i->$key] = $i;
        }
        return $result;
    }
}

if (!function_exists('group_array')) {
    function group_array($arr, $fields)
    {

        if (empty($fields) || !is_array($fields)) {
            return $arr;
        }

        $newarr = array(); // so that we always return an array
        $field = array_shift($fields);

        foreach ($arr as $val) {
            $val = (array)$val;
            $newarr[$val[$field]][] = $val;
        }

        foreach (array_keys($newarr) as $key) {
            // Since we shifted one field off before, this groups by the remaining
            $newarr[$key] = group_array($newarr[$key], $fields);
        }

        return $newarr;
    }
}

if (!function_exists('group_array_count')) {
    function group_array_count($arr, $fields)
    {

        if (empty($fields) || !is_array($fields)) {
            return $arr;
        }

        $newarr = array(); // so that we always return an array
        $field = array_shift($fields);

        foreach ($arr as $val) {
            $val = (array)$val;
            $newarr[$val[$field]][] = $val;
        }

        foreach (array_keys($newarr) as $key) {
            // Since we shifted one field off before, this groups by the remaining
            $newarr[$key] = count(group_array($newarr[$key], $fields));
        }

        return $newarr;
    }
}

if (!function_exists('printSourceTypeSelect')) {
    function printSourceTypeSelect()
    {
        echo '<label class="select">
        	<select name="sourceType">
                <option value="0" selected="selected">מקור</option>
        		<option value="1">ספר טלפונים</option>
        		<option value="2">עמוד נחיתה</option>
        		<option value="3">קמפיין</option>
        		<option value="4">חבר</option>
        		<option value="5">טלפון</option>
                <option value="6">דף צור קשר</option>
                <option value="7">אחר</option>
        	</select> <i></i> </label>';
    }
}

if (!function_exists('getSourceTypeName')) {
    function getSourceTypeName($id)
    {
        switch ($id) {
            case 0:
                return 'לא הוזן';
                break;

            case 1:
                return 'ספר טלפונים';
                break;

            case 2:
                return 'עמוד נחיתה';
                break;

            case 3:
                return 'קמפיין';
                break;

            case 4:
                return 'חבר';
                break;

            case 5:
                return 'טלפון';
                break;

            case 6:
                return 'דף צור קשר';
                break;

            case 7:
                return 'אחר';
                break;

            default:
        }
    }
}

if (!function_exists('makeLinks')) {

    function makeLinks($str, $target = '_blank')
    {
        if ($target) {
            $target = ' target="' . $target . '"';
        } else {
            $target = '';
        }
        $str = urldecode($str);
        // find and replace link
        $str = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" ' . $target . '>קישור</a>', $str);
        // add "http://" if not set
        $str = preg_replace('/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '<a href="http://$1" ' . $target . '>', $str);
        return $str;
    }
}

if (!function_exists('remove_emoji')) {
    function remove_emoji($text)
    {
        return preg_replace('/([0-9|#][\x{20E3}])|[\x{00ae}|\x{00a9}|\x{203C}|\x{2047}|\x{2048}|\x{2049}|\x{3030}|\x{303D}|\x{2139}|\x{2122}|\x{3297}|\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F6FF}][\x{FE00}-\x{FEFF}]?/u', '', $text);
    }
}

if (!function_exists('ip_info')) {
    function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE)
    {
        $output = NULL;
        if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
            $ip = $_SERVER["REMOTE_ADDR"];
            if ($deep_detect) {
                if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
                    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
            }
        }
        $purpose    = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
        $support    = array("country", "countrycode", "state", "region", "city", "location", "address");
        $continents = array(
            "AF" => "Africa",
            "AN" => "Antarctica",
            "AS" => "Asia",
            "EU" => "Europe",
            "OC" => "Australia (Oceania)",
            "NA" => "North America",
            "SA" => "South America"
        );
        if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
            $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
            if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
                switch ($purpose) {
                    case "location":
                        $output = array(
                            "city"           => @$ipdat->geoplugin_city,
                            "state"          => @$ipdat->geoplugin_regionName,
                            "country"        => @$ipdat->geoplugin_countryName,
                            "country_code"   => @$ipdat->geoplugin_countryCode,
                            "continent"      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
                            "continent_code" => @$ipdat->geoplugin_continentCode
                        );
                        break;
                    case "address":
                        $address = array($ipdat->geoplugin_countryName);
                        if (@strlen($ipdat->geoplugin_regionName) >= 1)
                            $address[] = $ipdat->geoplugin_regionName;
                        if (@strlen($ipdat->geoplugin_city) >= 1)
                            $address[] = $ipdat->geoplugin_city;
                        $output = implode(", ", array_reverse($address));
                        break;
                    case "city":
                        $output = @$ipdat->geoplugin_city;
                        break;
                    case "state":
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case "region":
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case "country":
                        $output = @$ipdat->geoplugin_countryName;
                        break;
                    case "countrycode":
                        $output = @$ipdat->geoplugin_countryCode;
                        break;
                }
            }
        }
        return $output;
    }
}

if (!function_exists('time_ago')) {
    function time_ago($timestamp = 0, $now = 0)
    {

        // Set up an array of time intervals.
        $intervals = array(
            60 * 60 * 24 * 365 => 'שנים',
            60 * 60 * 24 * 30  => 'חודשים',
            60 * 60 * 24 * 7   => 'שבועות',
            60 * 60 * 24       => 'ימים',
            60 * 60            => 'שעות',
            60                 => 'דקות',
            1                  => 'שניות',
        );

        // Get the current time if a reference point has not been provided.
        if (0 === $now) {
            $now = time();
        }

        // Make sure the timestamp to check predates the current time reference point.
        if ($timestamp > $now) {
            throw new \Exception('Timestamp postdates the current time reference point');
        }

        // Calculate the time difference between the current time reference point and the timestamp we're comparing.
        $time_difference = (int) abs($now - $timestamp);

        // Check the time difference against each item in our $intervals array. When we find an applicable interval,
        // calculate the amount of intervals represented by the the time difference and return it in a human-friendly
        // format.
        foreach ($intervals as $interval => $label) {

            // If the current interval is larger than our time difference, move on to the next smaller interval.
            if ($time_difference < $interval) {
                continue;
            }

            // Our time difference is smaller than the interval. Find the number of times our time difference will fit into
            // the interval.
            $time_difference_in_units = round($time_difference / $interval);

            if ($time_difference_in_units <= 1) {
                $time_ago = sprintf(
                    'לפני 1 %s',
                    $label
                );
            } else {
                $time_ago = sprintf(
                    'לפני %s %s',
                    $time_difference_in_units,
                    $label
                );
            }

            return $time_ago;
        }
    }
}

if (!function_exists('xml2array')) {
    function xml2array($xml)
    {
        $arr = array();

        foreach ($xml->children() as $r) {
            $t = array();
            if (count($r->children()) == 0) {
                $arr[$r->getName()] = strval($r);
            } else {
                $arr[$r->getName()][] = xml2array($r);
            }
        }
        return $arr;
    }
}

if (!function_exists('days_in_month')) {
    function days_in_month($month, $year)
    {
        return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
    }
}

if (!function_exists('getCustomerName')) {
    function getCustomerName($customerId)
    {
        $result = array();
        if ($customerId > 0) {
            $CI = &get_instance();
            $CI->db->select('customerName');
            $CI->db->from('customers');
            $CI->db->where('customerId', $customerId);
            $query = $CI->db->get();
            $result = $query->result();
        }

        // debug($result);
        if (count($result) == 1) return $result[0]->customerName;
        else return '';
    }
}

if (!function_exists('getWarehouseById')) {
    function getWarehouseById($wareId)
    {
        $result = array();
        if ($wareId > 0) {
            $CI = &get_instance();
            $CI->db->select('Name');
            $CI->db->from('warehouse');
            $CI->db->where('ID', $wareId);
            $query = $CI->db->get();
            $result = $query->result();
        }
        if (count($result) == 1) return $result[0]->Name;
        else return '';
    }
}

if (!function_exists('getSupplierName')) {
    function getSupplierName($supplier_id)
    {
        $result = array();
        if ($supplier_id > 0) {
            $CI = &get_instance();
            $CI->db->select('name');
            $CI->db->from('suppliers');
            $CI->db->where('supplier_id', $supplier_id);
            $query = $CI->db->get();
            $result = $query->result();
        }
        if (count($result) == 1) return $result[0]->name;
        else return '';
    }
}

if (!function_exists('getItemNameById')) {
    function getItemNameById($id)
    {
        $result = array();
        if ($id > 0) {
            $CI = &get_instance();
            $CI->db->select('name');
            $CI->db->from('products');
            $CI->db->where('id', $id);
            $query = $CI->db->get();
            $result = $query->result();
        }

        if (count($result) == 1) return $result[0]->name;
        else return '';
    }
}

if (!function_exists('getSupplierData')) {
    function getSupplierData($supplier_id)
    {
        $result = array();
        if ($supplier_id > 0) {
            $CI = &get_instance();
            $CI->db->select('*');
            $CI->db->from('suppliers');
            $CI->db->where('supplier_id', $supplier_id);
            $query = $CI->db->get();
            $result = $query->result();
        }
        if (count($result) == 1) return $result[0];
        else return '';
    }
}

if (!function_exists('getUserName')) {
    function getUserName($userId)
    {
        $result = array();
        if ($userId > 0) {
            $CI = &get_instance();
            $CI->db->select('firstname, lastname, adminId');
            $CI->db->from('users');
            $CI->db->where('userId', $userId);
            $query = $CI->db->get();
            $result = $query->result();
        }
        if (count($result) == 1) {
            if ($userId > 2) return $result[0]->firstname . ' ' . $result[0]->lastname;
            else return 'מערכת';
        } else {
            return '';
        }
    }
}


function sendSms($message_text, $sender, $recepients)
{
    $response = null;

    $url = "https://019sms.co.il/api";
    $xml = '<?xml version="1.0" encoding="UTF-8"?>
        <sms>
        <user>
        <username>callupnew</username>
        <password>Qw3e4r123</password>
        </user>
        <source>' . $sender . '</source>
        <destinations>
        <phone id="someid1">' . substr($recepients, 1) . '</phone>
        </destinations>
        <message>' . ($message_text) . '</message>
        </sms>';
    $CR = curl_init();
    curl_setopt($CR, CURLOPT_URL, $url);
    curl_setopt($CR, CURLOPT_POST, 1);
    curl_setopt($CR, CURLOPT_FAILONERROR, true);
    curl_setopt($CR, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($CR, CURLOPT_HTTPHEADER, array("charset=utf-8"));
    curl_setopt($CR, CURLOPT_TIMEOUT, 30);
    $result = curl_exec($CR);

    $error = curl_error($CR);

    if (!empty($error)) echo "Error: " . $error;
    else {
        $response = new SimpleXMLElement($result);
    }
    return $response;
}

if (!function_exists('checkIfCurrentUserIsAdmin')) {
    function checkIfCurrentUserIsAdmin($userId)
    {
        $CI = &get_instance();
        $CI->db->select('userLevel');
        $CI->db->from('users');
        $CI->db->where('userId', $userId);
        $query = $CI->db->get();

        $result = $query->result();
        if (!empty($result) && isset($result[0]) && $result[0]->userLevel == 1) return true;
        else return false;
    }
}

if (!function_exists('checkUserPermessions')) {
    function checkUserPermessions($userId)
    {
        $CI = &get_instance();
        $CI->db->select('view_permissions');
        $CI->db->from('users');
        $CI->db->where('userId', $userId);
        $query = $CI->db->get();

        $result = $query->result();
        if (!empty($result) && isset($result[0]) && $result[0]->view_permissions == 1) return true;
        else return false;
    }
}

if (!function_exists('checkIfCurrentUserIsAgent')) {
    function checkIfCurrentUserIsAgent($userId)
    {
        $CI = &get_instance();
        $CI->db->select('userLevel');
        $CI->db->from('users');
        $CI->db->where('userId', $userId);
        $query = $CI->db->get();

        $result = $query->result();
        if (!empty($result) && isset($result[0]) && $result[0]->userLevel == 4) return true;
        else return false;
    }
}

if (!function_exists('getSupplierNewInvoiceNo')) {
    function getSupplierNewInvoiceNo()
    {
        $CI = &get_instance();
        $CI->db->select('invoice_id');
        $CI->db->from('suppliers_invoices');
        $CI->db->order_by('invoice_id', 'DESC');
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        return $result->invoice_id + 1;
    }
}

if (!function_exists('getSupplierNewInvoiceNo')) {
    function getSupplierNewInvoiceNo()
    {
        $CI = &get_instance();
        $CI->db->select('invoice_id');
        $CI->db->from('suppliers_invoices');
        $CI->db->order_by('invoice_id', 'DESC');
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        return $result->invoice_id +1;
    }
}

if (!function_exists('getCustomerNewInvoiceNo')) {
    function getCustomerNewInvoiceNo()
    {
        $CI = &get_instance();
        $CI->db->select('invoice_id');
        $CI->db->from('customer_invoices');
        $CI->db->order_by('invoice_id', 'DESC');
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        return $result->invoice_id +1;
    }
}
if (!function_exists('getCustomerNewShippingNo')) {
    function getCustomerNewShippingNo()
    {
        $CI = &get_instance();
        $CI->db->select('shipping_id');
        $CI->db->from('customer_shipping');
        $CI->db->order_by('shipping_id', 'DESC');
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        if(!empty($result)){
            return $result->shipping_id +1;
        }else{ return 1; }
    }
}

if (!function_exists('getNewOrderNo')) {
    function getNewOrderNo()
    {
        $CI = &get_instance();
        $CI->db->select('id');
        $CI->db->from('orders');
        $CI->db->order_by('id', 'DESC');
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        return $result->id +1;
    }
}

if (!function_exists('getSupplierCredit')) {
    function getSupplierCredit($supplier_id)
    {
        $CI = &get_instance();
        $CI->db->select('credit');
        $CI->db->from('suppliers');
        $CI->db->where('supplier_id', $supplier_id);
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        if(!empty($result)){
            return $result->credit;
        }else{
            return 0; 
        }
    }
}

if (!function_exists('getCustomerCredit')) {
    function getCustomerCredit($customerId)
    {
        $CI = &get_instance();
        $CI->db->select('credits');
        $CI->db->from('customers');
        $CI->db->where('customerId', $customerId);
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        if(!empty($result)){
            return $result->credits;
        }else{
            return 0; 
        }
    }
}


if (!function_exists('getPaymentBox')) {
    function getPaymentBox($box_id)
    {
        $CI = &get_instance();
        $CI->db->select('name');
        $CI->db->from('customer_invoices_boxes');
        $CI->db->where('box_id', $box_id);
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        return $result->name;
    }
}

if (!function_exists('getBankName')) {
    function getBankName($bank_id)
    {
        $CI = &get_instance();
        $CI->db->select('bank_name');
        $CI->db->from('banks_codes');
        $CI->db->where('bank_code', $bank_id);
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        if(!empty($result)){
            return $result->bank_name;
        }
        else{ return "";}
    
        
    }
}
if (!function_exists('getBranchName')) {
    function getBranchName($bank_id, $branch_id)
    {
        $CI = &get_instance();
        $CI->db->select('branch_name');
        $CI->db->from('branch_codes');
        $CI->db->where('bank_code', $bank_id);
        $CI->db->where('branch_code', $branch_id);
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        if(!empty($result)){
            return $result->branch_name;
        }
        else{ return "";}
        
    }
}


if (!function_exists('getPaymentMethod')) {
    function getPaymentMethod($type_id)
    {
        $CI = &get_instance();
        $CI->db->select('name');
        $CI->db->from('customer_invoices_payments_type');
        $CI->db->where('type_id', $type_id);
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        return $result->name;
    }
}

if (!function_exists('getProductDetails')) {
    function getProductDetails($id)
    {
        $CI = &get_instance();
        $CI->db->select('name, type, description, price, code, category_id, quantity, status, manufacturer_id, colors, discount, special, main_image, images');
        $CI->db->from('products');
        $CI->db->where('id', $id);
        $CI->db->limit(1);
        $query = $CI->db->get();
        $result = $query->row();
        return $result;
    }
}

if (!function_exists('getProductCode')) {
    function getProductCode($id)
    {
        $CI = &get_instance();
        $CI->db->select('code');
        $CI->db->from('products');
        $CI->db->where('id', $id);
        $CI->db->limit(1);
        $query = $CI->db->get();
        $result = $query->row();
        return $result;
    }
}
 
if (!function_exists('getWarehouseQuantity')) {
    function getWarehouseQuantity($warehouse_id, $products_id)
    {
        $CI = &get_instance();
        $CI->db->select('quantity');
        $CI->db->from('warehouse_items');
        $CI->db->where('warehouse_id', $warehouse_id);
        $CI->db->where('product_id', $products_id);
        $CI->db->limit(1);
        $query = $CI->db->get();

        $result = $query->row();
        if(!empty($result) && isset($result)){
            return $result->quantity;
        }else{
            return 0; 
        }
    }
}