<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014 - 2015, British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package	CodeIgniter
 * @author	EllisLab Dev Team
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
 * @copyright	Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
 * @license	http://opensource.org/licenses/MIT	MIT License
 * @link	http://codeigniter.com
 * @since	Version 1.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * CodeIgniter Array Helpers
 *
 * @package		CodeIgniter
 * @subpackage	Helpers
 * @category	Helpers
 * @author		EllisLab Dev Team
 * @link		http://codeigniter.com/user_guide/helpers/array_helper.html
 */

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

if ( ! function_exists('element'))
{
	/**
	 * Element
	 *
	 * Lets you determine whether an array index is set and whether it has a value.
	 * If the element is empty it returns NULL (or whatever you specify as the default value.)
	 *
	 * @param	string
	 * @param	array
	 * @param	mixed
	 * @return	mixed	depends on what the array contains
	 */
	
}

function predata($value)
{
	echo "<pre>";
	print_r($value);
	echo "</pre>";
	return true;
}

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"]);
}

function encodeValue($id) {
  $id_str = (string) $id;
  $offset = rand(0, 9);
  $encoded = chr(79 + $offset);
  for ($i = 0, $len = strlen($id_str); $i < $len; ++$i) {
    $encoded .= chr(65 + $id_str[$i] + $offset);
  }
  $encoded = strtolower($encoded);
  return $encoded;
}

function decodeValue($encoded) {
	$encoded = strtoupper($encoded);
  $offset = ord($encoded[0]) - 79;
  $encoded = substr($encoded, 1);
  for ($i = 0, $len = strlen($encoded); $i < $len; ++$i) {
    $encoded[$i] = ord($encoded[$i]) - $offset - 65;
  }
  return (int) $encoded;
}
## for conver dateformat
if ( ! function_exists('convertdateFormat'))
{
	function convertdateFormat($date,$format){
	
		$changeDate = date($format,strtotime($date));
		return $changeDate;
	}
}
## for default dateformat
if ( ! function_exists('defaultdateFormat'))
{
	function dfltdttmFormat($datetime){
		$changeDate = date('jS M,Y h:i:s A',strtotime($datetime));
		return $changeDate; 
	}
}
## for default dateformat
if ( ! function_exists('defaultdateFormat'))
{
	function dfltdtFormat($date){
		$changeDate = date('jS M,Y',strtotime($date));
		return $changeDate; 
	}
}
## for Admin Email
if ( ! function_exists('getAdminemail'))
{
	function getAdminemail()
	{
		$obj =& get_instance();
		$obj->db->select('fld_email');
		$obj->db->where('fld_id','1');
		$query= $obj->db->get('tbl_administrator');
		$crow = $query->row();
		$email = $crow->fld_email;				
		return $email;	
	}
}
## for Admin From Email
if ( ! function_exists('getAdminFromemail'))
{
	function getAdminFromemail()
	{
		$obj =& get_instance();
		$obj->db->select('fld_email');
		$obj->db->where('fld_id','1');
		$query= $obj->db->get('tbl_administrator');
		$crow = $query->row();
		$email = $crow->fld_email;				
		return $email;	
	}
}
function getbasicsettings()
{
	$obj =& get_instance();
	$obj->db->select("*");
	$obj->db->where("fld_id", "1");
	$result = $obj->db->get("tbl_settings");
	if($result->num_rows()>0)
	{
		return $result->row();
	}		
}
## for Email Template
if ( ! function_exists('Emailtemplate'))
{
	function Emailtemplate($id="")
	{	
		$obj =& get_instance();
		$obj->db->select('*');
		$obj->db->where('fld_id',$id);
		$query = $obj->db->get('tbl_email_templates');
        //echo $obj->db->last_query();
        if($query -> num_rows() > 0)
        {
			$emailtemplateinfo = $query -> row();
		}
		return $emailtemplateinfo;
	}
}
## for get today sale info
if ( ! function_exists('GetTodaysale'))
{
	function GetTodaysale($outletid,$userid)
	{	
		$currdate = date('Y-m-d');
		$totalamount  =0;
		$obj =& get_instance();
		$obj->db->select('SUM(fld_netamount) as totalamount');
		$obj->db->where('fld_outletid',$outletid);
		if($userid>0)
		{
			$obj->db->where('fld_userid',$userid);
		}
		$obj->db->where("DATE_FORMAT(fld_datetime,'%Y-%m-%d') ", $currdate);
		$obj->db->where("(fld_status='completed')");
		$obj->db->where('fld_del', '0');
		$query = $obj->db->get('tbl_billing');
       // echo $obj->db->last_query();
        if($query -> num_rows() > 0)
        {
			$row = $query -> row();
			$totalamount  = $row->totalamount;
		}
		if($totalamount=="")
		{
			$totalamount = 0;
		}
		return $totalamount;
	}
}
## for get today sale info
if ( ! function_exists('GetTodayInvoices'))
{
	function GetTodayInvoices($outletid,$userid)
	{	
		$currdate = date('Y-m-d');
		$totalinvocies  =0;
		$obj =& get_instance();
		$obj->db->select('COUNT(fld_id) as totalinvocies');
		$obj->db->where('fld_outletid',$outletid);
		if($userid>0)
		{
			$obj->db->where('fld_userid',$userid);
		}
		$obj->db->where("(fld_status='completed')");
		$obj->db->where("DATE_FORMAT(fld_datetime,'%Y-%m-%d') ", $currdate);
		$obj->db->where('fld_del', '0');
		$query = $obj->db->get('tbl_billing');
       // echo $obj->db->last_query();
        if($query -> num_rows() > 0)
        {
			$row = $query -> row();
			$totalinvocies  = $row->totalinvocies;
		}
		return $totalinvocies;
	}
}
## for get today sale info
if ( ! function_exists('GetTodayOrdersBystatus'))
{
	function GetTodayOrdersBystatus($outletid,$userid,$status)
	{	
		$currdate = date('Y-m-d');
		$totalinvocies  =0;
		$obj =& get_instance();
		$obj->db->select('COUNT(fld_id) as totalinvocies');
		$obj->db->where('fld_outletid',$outletid);
		if($userid>0)
		{
			$obj->db->where('fld_userid',$userid);
		}
		$obj->db->where('fld_status',$status);
		$obj->db->where("DATE_FORMAT(fld_datetime,'%Y-%m-%d') ", $currdate);
		$obj->db->where('fld_del', '0');
		$query = $obj->db->get('tbl_billing');
       // echo $obj->db->last_query();
        if($query -> num_rows() > 0)
        {
			$row = $query -> row();
			$totalinvocies  = $row->totalinvocies;
		}
		return $totalinvocies;
	}
}

function createBillNo($outletid)
{	
	$obj =& get_instance();
	$obj->db->select('fld_invoiceprefix');
	$obj->db->where("fld_id",$outletid);

	$query2= $obj->db->get('tbl_outlets');
	$rowoutlet = $query2->row();
	$orderprefix = $rowoutlet->fld_invoiceprefix;
	
	$orderprefixlen  = strlen($orderprefix);
	$gettotalchars = $orderprefixlen + 5;
	$obj =& get_instance();
	$obj->db->select("max(SUBSTRING(fld_billno," . $gettotalchars . ")*1) as billno");
	$obj->db->where("fld_billno!=",'');
	$obj->db->where("fld_billno LIKE '".$orderprefix."%'");
	$query= $obj->db->get('tbl_billing');
	//echo $obj->db->last_query();
	$rowordno = $query->row();
	$maxcodeno = $rowordno->billno;
	if($maxcodeno=="") $maxcodeno = 0;
	$maxcodeno += 1;
	$code = "";
	//echo $maxcodeno;
	if($maxcodeno < 10)
	{
		$code = $orderprefix."00000" . $maxcodeno;
	}
	elseif($maxcodeno <100)
	{
		$code = $orderprefix."0000" . $maxcodeno;
	}
	elseif($maxcodeno <1000)
	{
		$code = $orderprefix."000" . $maxcodeno;
	}
	elseif($maxcodeno <10000)
	{
		$code = $orderprefix."00" . $maxcodeno;
	}
	elseif($maxcodeno <100000)
	{
		$code = $orderprefix."0" . $maxcodeno;
	}
	else
	{
		$code = $orderprefix.$maxcodeno;
	}
	//echo $code;
	return $code;
}

function createDemandRefno($orderprefix)
{	
	$orderprefixlen  = strlen($orderprefix);
	$gettotalchars = $orderprefixlen + 5;
	$obj =& get_instance();
	$obj->db->select("max(SUBSTRING(fld_refno," . $gettotalchars . ")*1) as refno");
	$obj->db->where("fld_refno!=",'');
	$obj->db->where("fld_refno LIKE '".$orderprefix."%'");
	$query= $obj->db->get('tbl_demand');
	//echo $obj->db->last_query();
	$rowordno = $query->row();
	$maxcodeno = $rowordno->refno;
	if($maxcodeno=="") $maxcodeno = 0;
	$maxcodeno += 1;
	$code = "";
	//echo $maxcodeno;
	if($maxcodeno < 10)
	{
		$code = $orderprefix."00000" . $maxcodeno;
	}
	elseif($maxcodeno <100)
	{
		$code = $orderprefix."0000" . $maxcodeno;
	}
	elseif($maxcodeno <1000)
	{
		$code = $orderprefix."000" . $maxcodeno;
	}
	elseif($maxcodeno <10000)
	{
		$code = $orderprefix."00" . $maxcodeno;
	}
	elseif($maxcodeno <100000)
	{
		$code = $orderprefix."0" . $maxcodeno;
	}
	else
	{
		$code = $orderprefix.$maxcodeno;
	}
	//echo $code;
	return $code;
}
function createOutletCode()
{	
	$orderprefix = 'OC';
	$obj =& get_instance();
	$obj->db->select('max(SUBSTRING(fld_code,4)*1) as code');
	$obj->db->where("fld_code!=",'');
	$query= $obj->db->get('tbl_outlets');
	//echo $obj->db->last_query();
	$rowordno = $query->row();
	$maxcodeno = $rowordno->code;
	if($maxcodeno=="") $maxcodeno = 0;
	$maxcodeno += 1;
	$code = "";
	//echo $maxcodeno;
	if($maxcodeno < 10)
	{
		$code = $orderprefix."00000" . $maxcodeno;
	}
	elseif($maxcodeno <100)
	{
		$code = $orderprefix."0000" . $maxcodeno;
	}
	elseif($maxcodeno <1000)
	{
		$code = $orderprefix."000" . $maxcodeno;
	}
	elseif($maxcodeno <10000)
	{
		$code = $orderprefix."00" . $maxcodeno;
	}
	elseif($maxcodeno <100000)
	{
		$code = $orderprefix."0" . $maxcodeno;
	}
	else
	{
		$code = $orderprefix.$maxcodeno;
	}
	//echo $code;
	return $code;
}

function arrProductType()
{
	$arroption = array();
	$obj =& get_instance();
	$obj->db->distinct();
	$obj->db->select("fld_type");
	$results = $obj->db->get('tbl_products');
	if($results->num_rows()>0)
	{
		foreach($results->result() as $row)
		{
			$arroption[$row->fld_type] = $row->fld_type;
		}
	}
	return $arroption;
}


function arrOrderStatus()
{	
	$arrorderstatus['pending'] ="Pending";
	$arrorderstatus['onhold'] ="On Hold";
	$arrorderstatus['cancelled'] ="Cancelled";
	$arrorderstatus['delivered'] ="Delivered";
	$arrorderstatus['completed'] ="Completed";
	$arrorderstatus['acknowledgestock'] ="Acknowledge Stock";
	$arrorderstatus['cancelorder'] ="Cancel Order";
	$arrorderstatus['open'] ="Open";
	$arrorderstatus['close'] ="Close";
	return $arrorderstatus;
}
function arrOSColor()
{	
	$arrorderstatus['invoices'] ='primary';
	$arrorderstatus['pending'] ='primary';
	$arrorderstatus['onhold'] ='warning';
	$arrorderstatus['cancelled'] ='danger';
	$arrorderstatus['delivered'] ='primary';
	$arrorderstatus['completed'] ='success';
	$arrorderstatus['acknowledgestock'] ='danger';
	$arrorderstatus['cancelorder'] ='danger';
	$arrorderstatus['stockavaiable'] ='success';
	$arrorderstatus['minstockvaluenearby'] ='warning';
	$arrorderstatus['minstockvalue'] ='danger';
	$arrorderstatus['outofstock'] ='danger';
	$arrorderstatus['specialdiscount'] ='primary';
	$arrorderstatus['gift'] ='success';
	$arrorderstatus['open'] ='success';
	$arrorderstatus['close'] ='danger';
	return $arrorderstatus;
}


function minstockStatus($minvalue,$stockvalue)
{

	$arrstatus ='outofstock';
	if($minvalue>=$stockvalue)
	{
		$arrstatus ='minstockvalue';
	}
	elseif(($minvalue+5)>$stockvalue)
	{
		$arrstatus ='minstockvaluenearby';
	}
	elseif($minvalue<$stockvalue)
	{
		$arrstatus ='stockavaiable';
	}	

	return $arrstatus;
}
function mobilemasking($phone)
{ 
	return substr($phone, 0,3) . "xxxx" . substr($phone, 7,3);
}

if ( ! function_exists('calculate_time'))
{
	function calculate_time($date){
		$seconds  = strtotime(date('Y-m-d H:i:s')) - strtotime($date);

			$months = floor($seconds / (3600*24*30));
			$day = floor($seconds / (3600*24));
			$hours = floor($seconds / 3600);
			$mins = floor(($seconds - ($hours*3600)) / 60);
			$secs = floor($seconds % 60);

			if($seconds < 60)
				$time = $secs." seconds ago";
			else if($seconds < 60*60 )
				$time = $mins." min ago";
			else if($seconds < 24*60*60)
				$time = $hours." hours ago";
			else if($seconds < 24*60*60)
				$time = $day." day ago";
			else
				$time = $months." month ago";

			return $time;
	}
}

function getFinancialYear()
{
	if(date('m') > 4)
	{
	$y = date('Y');
	$pt = date('Y', strtotime('+1 year'));
	//$fy = $y."-04-01".":".$pt."-03-31";
		$fy = $pt."-03-31";
	}
	else
	{
	$y = date('Y', strtotime('-1 year'));
	$pt = date('Y');
	//$fy = $y."-04-01".":".$pt."-03-31";
	$fy = $pt."-03-31";
	}
	return $fy;
}
