<?php
class  Accounting extends Main{
	
private $conn;
public $tableprefix;

public function  __construct()
	{
		$this->conn = $this->connect(DBHOST, DBUSER, DBPASSWORD);
		$this->tableprefix = TBLPREFIX_ACCOUNTING;
		$this->usedatabase(CUSTOMERDB);
	}
	
/*Function to get Company settings*/
public function get_company_settings($where="",$orderby="",$limit="")
	{
		$fields =  "*";
		$companysettings =  $this->getRows($fields,$this->tableprefix."sys_prefs",  "  ".$where." ".$orderby." ".$limit);	
		return $companysettings;
	}

/*Function to get Currency */
public function get_currencies($where="",$orderby="",$limit="")
	{
		$fields =  "*";
		$currencies =  $this->getRows($fields,$this->tableprefix."currencies",  "  ".$where." ".$orderby." ".$limit);	
		return $currencies;
	}

/*Function to get Fiscal Years */
public function get_fiscalyears($where="",$orderby="",$limit="")
	{
		$fields =  "*";
		$fiscal_years =  $this->getRows($fields,$this->tableprefix."fiscal_year",  "  ".$where." ".$orderby." ".$limit);	
		return $fiscal_years;
	}	

/*Function to get Dimensions */
public function get_dimensions($where="",$orderby="",$limit="")
	{
		$fields =  "*";
		$dimensions =  $this->getRows($fields,$this->tableprefix."dimensions",  "  ".$where." ".$orderby." ".$limit);	
		return $dimensions;
	}

/*Function to get Sales Types */
public function get_sales_types($where="",$orderby="",$limit="")
	{
		$fields =  "*";
		$sales_types =  $this->getRows($fields,$this->tableprefix."sales_types",  "  ".$where." ".$orderby." ".$limit);	
		return $sales_types;
	}

/******************************/
/*Functions for Sales Invoices*/
/******************************/

/*Function to get Sales Invoices Data*/
public function get_sales_invoices_data($where,$orderby,$limit)
	{
		$fields =  "*";
		$get_sales_invoices_data =  $this->getRows($fields,$this->tableprefix."invoices",  "  ".$where." ".$orderby." ".$limit);	
		return $get_sales_invoices_data;
	}

/*Function to set Sales Invoice Data*/
public function set_sales_invoice_data($invoice_id,$key,$value)
	{
		setSession('sales_invoice_'.$key.$invoice_id,$value);
	}	

/*Function to get Sales Invoice Data*/
public function get_sales_invoice_data($invoice_id,$key)
	{
		if(!getSession('sales_invoice_'.$key.$invoice_id))
			$this->set_sales_invoice_data($invoice_id,$key,"");
		return getSession('sales_invoice_'.$key.$invoice_id);
	}
	
/*Function to get Sales Invoice Item Search Suggestions*/
public function get_sales_invoice_item_search_suggestions($search_value,$limit=25)
	{
	
		$suggestions = array();
		$tbl_items = TBLPREFIX_OPOS."items";
		$tbl_stock_master = $this->tableprefix."stock_master";
		$fields = "*";  
		$items =  $this->getRows($fields,$tbl_stock_master,  " WHERE inactive=0 AND ( stock_id LIKE '%$search_value%' || description LIKE '%$search_value%' || long_description LIKE '%$search_value%') AND cp_store = 'items' ORDER BY description ASC ");
		foreach($items as $row)
			{
				//if(!empty($row['description'])){$suggestions[] = $row['stock_id'].'|'.drop_multiple_slashes($row['description']);}
				if(!empty($row['description']))
				{
					$suggestions[] = $row['stock_id'].'|'.drop_multiple_slashes($row['description']);
				}
				else
				{
					$item_number_data = $this->getRow("*",$tbl_items," WHERE accounting_stock_id='".$row['stock_id']."' ");
					$suggestions[] = $item_number_data['accounting_stock_id'].'|'.drop_multiple_slashes($item_number_data['item_number']);
				}
				
			}
		/*$item_number =  $this->getRows($fields,$tbl_items,  " WHERE deleted=0 AND status=1 AND ( item_number LIKE '%$search_value%') ORDER BY item_number ASC ");
		foreach($item_number as $row)
			{
				$suggestions[] = $row['item_id'].'|'.$row['item_number'];  
			}*/
		if(!empty($search_value))
		{		
		  $items =  $this->getRows($fields,$tbl_items,  " WHERE deleted=0 AND status=1 AND ( item_number LIKE '%$search_value%') ORDER BY item_number ASC ");
		  foreach($items as $row)
			  {
				  if(!empty($row['name']))
				  {
					  $suggestions[] = $row['accounting_stock_id'].'|'.drop_multiple_slashes($row['name']);
				  }
				  else
				  {
					  $suggestions[] = $row['accounting_stock_id'].'|'.drop_multiple_slashes($row['item_number']);
				  } 
				  //if(!empty($row['item_number'])){$suggestions[] = $row['accounting_stock_id'].'|'.drop_multiple_slashes($row['item_number']);}
			  }
		 }
		if(count($suggestions > $limit))
			{
				$suggestions = array_slice($suggestions, 0,$limit);
			}
		return $suggestions;		
			
	}	

/*Function to set Sales Invoice Cart*/
public function set_sales_invoice_cart($invoice_id,$sales_invoice_cart_data)
	{
		setSession('sales_invoice_cart'.$invoice_id,$sales_invoice_cart_data);
	}	

/*Function to get Sales Invoice Cart*/
public function get_sales_invoice_cart($invoice_id)
	{
		if(!getSession('sales_invoice_cart'.$invoice_id))
			$this->set_sales_invoice_cart($invoice_id,array());
		return getSession('sales_invoice_cart'.$invoice_id);
	}	
	
/*Function to Set Sales Invoice Saved Items to Cart*/
public function set_sales_invoice_saved_items_to_cart($invoice_id)
	{
		global $SESSION_CP;
		if(!array_key_exists('sales_invoice_cart'.$invoice_id, $SESSION_CP))
		{
			$get_sales_invoice_cart = $this->get_sales_invoice_cart($invoice_id);
			if(empty($get_sales_invoice_cart))
			{
				$get_sales_invoice_cart_data = $this->get_sales_invoices_data($where=" WHERE invoice_id = '$invoice_id'",$orderby,$limit);
				//printArray($get_sales_invoice_cart_data);
				if(!empty($get_sales_invoice_cart_data))
				{
					$sales_invoice_items = json_decode(base64_decode($get_sales_invoice_cart_data[0]['invoice_items']),true);//
					//printArray($sales_invoice_items);
					$this->set_sales_invoice_cart($invoice_id,$sales_invoice_items);
				}
			}
		}
	}	

/*Function to get Sales Invoice Cart Items*/	
public function get_sales_invoice_cart_items($invoice_id)
	{
		if(!empty($invoice_id))
		{
			$this->set_sales_invoice_saved_items_to_cart($invoice_id);
		}
		return $this->get_sales_invoice_cart($invoice_id);
	}

/*Function to add Sales Invoice Item to Cart*/	
public function add_sales_invoice_item_to_cart($invoice_id=NULL,$stock_id,$quantity=1,$discount=0,$price=NULL,$description=NULL)
	{
		//make sure item exists in database.
		$checkItem = $this->getRow("*",$this->tableprefix."stock_master"," WHERE stock_id='".$stock_id."' ");//printArray($checkItem);//exit();
		if(empty($checkItem) && ($checkItem['stock_id'] != $stock_id))
		{
			if(!$checkItem['stock_id'])return false;
		}
		
		//Get items in the sales invoice so far.
		$items = $this->get_sales_invoice_cart_items($invoice_id);//printArray($items);//exit();
		
		//We need to loop through all items in the sales invoice cart.
        //If the item is already there, get it's key($updatekey).
        //We also need to get the next key that we are going to use in case we need to add the
        //item to the list. Since items can be deleted, we can't use a count. we use the highest key + 1.

        $maxkey=0;                       //Highest key so far
		$insertkey=0;                    //Key to use for new entry.
		$updatekey=0;                    //Key to use to update(quantity)
		$itemalreadyininvoice=FALSE;     //We did not find the item yet.

		foreach ($items as $item)
		{
            //We primed the loop so maxkey is 0 the first time.
            //Also, we have stored the key in the element itself so we can compare.
            //There is an array function to get the associated key for an element, but I like it better
            //like that!

			if($maxkey <= $item['line'])
			{
				$maxkey = $item['line'];
			}

			if($item['stock_id']==$stock_id)
			{
				$itemalreadyininvoice=TRUE;
				$updatekey = $item['line'];
			}
		}

		$insertkey = $maxkey+1;
		
		/*Get Item Price*/
		$item_prices_data = $this->getRow("*",$this->tableprefix."prices"," WHERE stock_id='".$stock_id."' ");//printArray($item_prices_data);
		
		//array records are identified by $insertkey and item_id is just another field.
		$description = ($description!=NULL) ? ($description): ($checkItem['long_description']);
		$description = newline_to_br_preg_replace(cleanSQL($description));
		$description = br_to_newline_preg_replace(drop_multiple_slashes($description));
		$item = array(($insertkey)=>
			array(
				'line'=>$insertkey,
				'stock_id'=>$stock_id,
				'name'=>drop_multiple_slashes($checkItem['description']),
				//'description'=>$description!=NULL ? drop_multiple_slashes($description): drop_multiple_slashes($checkItem['long_description']),
				'description'=>$description,
				'quantity'=>$quantity,
				'discount'=>$discount,
				'price'=>$price!=NULL ? $price: $item_prices_data['price']
				)
		);
		//printArray($items);//exit();
		//Item already exists
		if($itemalreadyininvoice)
		{
			$items[$updatekey]['quantity']+=$quantity;
		}
		else
		{
			//add to existing array
			$items+=$item;
		}
		
		//printArray($items);
		$this->set_sales_invoice_cart($invoice_id,$items);
		return true;
		
	}
	
/*Function to edit Sales Invoice Item to Cart*/
public function edit_sales_invoice_item_to_cart($invoice_id=NULL,$line,$quantity,$discount,$price,$description=NULL)
	{
		$items = $this->get_sales_invoice_cart_items($invoice_id);
		//printArray($items);
		if(isset($items[$line]))
		{
			$items[$line]['quantity'] = $quantity;
			$items[$line]['discount'] = $discount;
			$items[$line]['price'] = $price;
			if($description!=NULL)
			{
				$description = newline_to_br_preg_replace(cleanSQL($description));
				$description = br_to_newline_preg_replace(drop_multiple_slashes($description));
				$items[$line]['description'] = ($description);
			}
			$this->set_sales_invoice_cart($invoice_id,$items);
		}
		//printArray($items);
		return false;
	}	
	
/*Function to delete Sales Invoice Item from Cart*/
public function delete_sales_invoice_item_to_cart($invoice_id,$line)
	{
		$items = $this->get_sales_invoice_cart_items($invoice_id);
		//printArray($items);
		unset($items[$line]);
		//printArray($items);
		$this->set_sales_invoice_cart($invoice_id,$items);
	}		
	
/*Function to get Sales Invoice Customer Search Suggestions*/	
public function get_sales_invoice_customer_search_suggestions($search_value,$limit=25)
	{
	
		$suggestions = array();
		$tbl_customers_persons = $this->tableprefix."crm_persons";  
		$tbl_customers_contacts = $this->tableprefix."crm_contacts";  
		$inner_join=" INNER JOIN $tbl_customers_contacts ON $tbl_customers_persons.id = $tbl_customers_contacts.person_id AND type='customer' ";
		$condition = " WHERE inactive=0 AND (ref LIKE '%$search_value%' || name LIKE '%$search_value%' || name2 LIKE '%$search_value%' || phone LIKE '%$search_value%' || phone2 LIKE '%$search_value%')";			  
		$customers = $this->getRows("*",$tbl_customers_persons,$inner_join." ".$condition." ORDER BY name ASC ");
		foreach($customers as $row)
		{
			if($row['name']=="" && $row['name2']=="")
			{
				$suggestions[] = $row['person_id'].'|'.drop_multiple_slashes($row['ref']);
			}
			else
			{
				$suggestions[] = $row['person_id'].'|'.drop_multiple_slashes($row['name'])." ".drop_multiple_slashes($row['name2']);
			}
		}
		
		if(count($suggestions > $limit))
			{
				$suggestions = array_slice($suggestions, 0,$limit);
			}
		return $suggestions;		
				
	}	
	
/*Function to set Sales Invoice Customer*/
public function set_sales_invoice_customer($invoice_id,$customer_id)
	{
		setSession('sales_invoice_customer'.$invoice_id,$customer_id);
	}
	
/*Function to get Sales Invoice Customer*/	
public function get_sales_invoice_customer($invoice_id)
	{
		if(!getSession('sales_invoice_customer'.$invoice_id))
			$this->set_sales_invoice_customer(-1);
		return getSession('sales_invoice_customer'.$invoice_id);
	}		
	
/*Function to Get Customers Data*/
public function get_sales_invoice_customers_data($where,$orderby,$limit)
	{
		return $this->getRows("*",$this->tableprefix."crm_persons",  "  ".$where." ".$orderby." ".$limit);
	}
	
/*Function to set Sales Invoice Add Fees to Cart*/
public function set_sales_invoice_fees_cart($invoice_id,$sale_invoice_fees)
	{
		setSession('sales_invoice_fees_cart'.$invoice_id,$sale_invoice_fees);
	}	

/*Function to get Sales Invoice Add Fees Cart*/	
public function get_sales_invoice_fees_cart($invoice_id)
	{
		if(!getSession('sales_invoice_fees_cart'.$invoice_id))
			$this->set_sales_invoice_fees_cart($invoice_id,array());
		return getSession('sales_invoice_fees_cart'.$invoice_id);
	}
	
/*Function to Set Sales Invoice Multiple Fees to Cart*/
public function set_sales_invoice_saved_fees_to_cart($invoice_id)
	{
		global $SESSION_CP;
		if(!array_key_exists('sales_invoice_fees_cart'.$invoice_id, $SESSION_CP))
		{
			$get_sales_invoice_fees_cart = $this->get_sales_invoice_fees_cart($invoice_id);
			if(empty($get_sales_invoice_fees_cart))
			{
				$sale_invoice_fees_data = $this->get_sales_invoice_fees_data("WHERE add_fees_invoice_id='$invoice_id' ");
				//printArray($sale_invoice_fees_data);
				if(!empty($sale_invoice_fees_data))
				{
					$sale_invoice_fees = array(); 
					foreach($sale_invoice_fees_data as $key=>$each_sale_invoice_fees)
					{
						$sale_invoice_fees[$each_sale_invoice_fees['add_fees_line']] = $each_sale_invoice_fees;
					}
				}
				$this->set_sales_invoice_fees_cart($invoice_id,$sale_invoice_fees);
			}
		}
	}	
	
/*Function to get Sales Invoice Fees Cart Items*/	
public function get_sales_invoice_fees_cart_items($invoice_id)
	{
		if(!empty($invoice_id))
		{
			//$this->set_sales_invoice_saved_fees_to_cart($invoice_id);
		}
		return $this->get_sales_invoice_fees_cart($invoice_id);
	}				
	
/*Function to add Sales Invoice Add Fees to Cart*/	
public function add_sales_invoice_fees_to_cart($invoice_id=NULL,$sale_invoice_add_fees_id,$sale_invoice_add_fees_invoice_id,$sale_invoice_add_fees_type,$sale_invoice_add_fees_value,$sale_invoice_add_fees_description)
	{
        //Get fees in the sales invoice so far.
		$sale_invoice_fees = $this->get_sales_invoice_fees_cart_items($invoice_id);//printArray($sale_invoice_fees);//exit();
		
		//We need to loop through all fees in the sales invoice cart.
        //If the fee is already there, get it's key($updatekey).
        //We also need to get the next key that we are going to use in case we need to add the
        //fee to the list. Since fees can be deleted, we can't use a count. we use the highest key + 1.

        $maxkey=0;                       //Highest key so far
		$insertkey=0;                    //Key to use for new entry.
		$updatekey=0;                    //Key to use to update(quantity)
		$itemalreadyininvoice=FALSE;     //We did not find the fee yet.

		foreach ($sale_invoice_fees as $sale_invoice_fee)
		{
            //We primed the loop so maxkey is 0 the first time.
            //Also, we have stored the key in the element itself so we can compare.
            //There is an array function to get the associated key for an element, but I like it better
            //like that!

			if($maxkey <= $sale_invoice_fee['add_fees_line'])
			{
				$maxkey = $sale_invoice_fee['add_fees_line'];
			}
		}

		$insertkey = $maxkey+1;
		
		//array records are identified by $insertkey and item_id is just another field.
		$sale_invoice_add_fees_description = newline_to_br_preg_replace(cleanSQL($sale_invoice_add_fees_description));
		$sale_invoice_add_fees_description = br_to_newline_preg_replace(drop_multiple_slashes($sale_invoice_add_fees_description));
		$sale_invoice_fee = array(($insertkey)=>
			array(
				'add_fees_line'=>$insertkey,
				'add_fees_id'=>$sale_invoice_add_fees_id,
				'add_fees_invoice_id'=>$sale_invoice_add_fees_invoice_id,
				'add_fees_type'=>$sale_invoice_add_fees_type,
				'add_fees_value'=>$sale_invoice_add_fees_value,
				//'add_fees_description'=>$sale_invoice_add_fees_description!=NULL ? drop_multiple_slashes($sale_invoice_add_fees_description): ""
				'add_fees_description'=>$sale_invoice_add_fees_description!=NULL ? ($sale_invoice_add_fees_description): ""
				)
		);
		//printArray($sale_invoice_fee);//exit();
		
		//add to existing array
		$sale_invoice_fees+=$sale_invoice_fee;

		//echo "<pre>";print_r($sale_invoice_fees);echo "</pre>";exit();
		$this->set_sales_invoice_fees_cart($invoice_id,$sale_invoice_fees);
		return true;
	}

/*Function to edit Sales Invoice Add Fees to Cart*/
public function edit_sales_invoice_fees_to_cart($invoice_id=NULL,$sale_invoice_add_fees_line,$sale_invoice_add_fees_id,$sale_invoice_add_fees_invoice_id,$sale_invoice_add_fees_type,$sale_invoice_add_fees_value,$sale_invoice_add_fees_description)
	{
		$sale_invoice_fees = $this->get_sales_invoice_fees_cart_items($invoice_id);
		$sale_invoice_add_fees_description = newline_to_br_preg_replace(cleanSQL($sale_invoice_add_fees_description));
		$sale_invoice_add_fees_description = br_to_newline_preg_replace(drop_multiple_slashes($sale_invoice_add_fees_description));
		if(isset($sale_invoice_fees[$sale_invoice_add_fees_line]))
		{
			$sale_invoice_fees[$sale_invoice_add_fees_line]['add_fees_id'] = $sale_invoice_add_fees_id;
			$sale_invoice_fees[$sale_invoice_add_fees_line]['add_fees_line'] = $sale_invoice_add_fees_line;
			$sale_invoice_fees[$sale_invoice_add_fees_line]['add_fees_invoice_id'] = $sale_invoice_add_fees_invoice_id;
			$sale_invoice_fees[$sale_invoice_add_fees_line]['add_fees_type'] = $sale_invoice_add_fees_type;
			$sale_invoice_fees[$sale_invoice_add_fees_line]['add_fees_value'] = $sale_invoice_add_fees_value;
			//$sale_invoice_fees[$sale_invoice_add_fees_line]['add_fees_description'] = drop_multiple_slashes($sale_invoice_add_fees_description);
			$sale_invoice_fees[$sale_invoice_add_fees_line]['add_fees_description'] = ($sale_invoice_add_fees_description);
			$this->set_sales_invoice_fees_cart($invoice_id,$sale_invoice_fees);
		}
		return false;
	}	

/*Function to delete Sales Invoice Fees from Cart*/
public function delete_sales_invoice_fees_cart($invoice_id,$sale_invoice_add_fees_line)
	{
		$sale_invoice_fees = $this->get_sales_invoice_fees_cart_items($invoice_id);
		unset($sale_invoice_fees[$sale_invoice_add_fees_line]);
		$this->set_sales_invoice_fees_cart($invoice_id,$sale_invoice_fees);
	}
	
/*Function to Get Sale Invoice Fees Data*/
public function get_sales_invoice_fees_data($where,$orderby,$limit)
	{
		return $this->getRows("*",$this->tableprefix."invoices_fees",  "  ".$where." ".$orderby." ".$limit);
	}			

/*Function to Empty Invoice Item Cart*/
public function empty_sales_invoice_cart($invoice_id)
	{
		clearSession("sales_invoice_cart".$invoice_id);
	}

/*Function to Empty Invoice Customer*/	
public function delete_sales_invoice_customer($invoice_id)
	{
		clearSession("sales_invoice_customer".$invoice_id);
	}

/*Function to Empty Invoice Data*/
public function delete_sales_invoice_data($invoice_id,$key)
	{
		clearSession("sales_invoice_".$key.$invoice_id);
	}	
	
/*Function to Empty Invoice Fees Cart*/
public function empty_sales_invoice_fees_cart($invoice_id)
	{
		clearSession("sales_invoice_fees_cart".$invoice_id);
	}	

/*Function to Empty Invoice Sessions*/	
public function clear_sales_invoice_all($invoice_id)
	{
		$this->empty_sales_invoice_cart($invoice_id);
		$this->empty_sales_invoice_fees_cart($invoice_id);
		$this->delete_sales_invoice_customer("-1");
		$this->delete_sales_invoice_customer($invoice_id);
		$this->delete_sales_invoice_data($invoice_id,"title");
		$this->delete_sales_invoice_data($invoice_id,"summary");
		$this->delete_sales_invoice_data($invoice_id,"number");
		$this->delete_sales_invoice_data($invoice_id,"date");
		$this->delete_sales_invoice_data($invoice_id,"payment_due");
		$this->delete_sales_invoice_data($invoice_id,"note");
	}
	
/*Function to For Generate Sales Invoice Email*/	
public function send_sales_invoice_email($invoice_id)
	{
		
		global $SESSION_CUSTOMER;
		$account_name = $SESSION_CUSTOMER['account_name'];
		
		/*Get Company Settings*/
		$accounting_settings = getApplicationsSettingsData();
	    $accounting_settingsArray = $accounting_settings[ACCOUNTING];
		
		/*Get Sales Invoice Information*/
		$sales_invoices_data = $this->get_sales_invoices_data($where=" WHERE invoice_id='$invoice_id' ");
		$sales_invoices_data = $sales_invoices_data[0];
		$customer_id = $sales_invoices_data['customer_id'];
		$invoice_title = drop_multiple_slashes($sales_invoices_data['invoice_title']);
		//$invoice_summary = drop_multiple_slashes($sales_invoices_data['invoice_summary']);
		$invoice_summary = drop_multiple_slashes(new_line_html($sales_invoices_data['invoice_summary']));
		$invoice_number = $sales_invoices_data['invoice_number'];
		$invoice_date = $sales_invoices_data['invoice_date'];
		$invoice_date = date_create($invoice_date);
		$invoice_date = date_format($invoice_date,"d-m-Y");
		$invoice_payment_due = $sales_invoices_data['invoice_payment_due'];
		$invoice_payment_due = date_create($invoice_payment_due);
		$invoice_payment_due = date_format($invoice_payment_due,"d-m-Y");
		$invoice_note = drop_multiple_slashes($sales_invoices_data['invoice_note']);
		$invoice_items = $sales_invoices_data['invoice_items'];
		
		/*Get Sales Invoice Customer Data*/
		$sales_invoice_customers_data = $this->get_sales_invoice_customers_data($where=" WHERE inactive=0 AND id='$customer_id' ");
		$sales_invoice_customers_data = $sales_invoice_customers_data[0];
		$customer_email = $sales_invoice_customers_data['email'];
		if($sales_invoice_customers_data['name'] == "" && $sales_invoice_customers_data['name2'] == "")
		$customer_name = $sales_invoice_customers_data['ref'];
		else
		$customer_name = $sales_invoice_customers_data['name'].' '.$sales_invoice_customers_data['name2'];
		
	    $invoice_email_subject = "Invoice #".$invoice_id." from ".$accounting_settingsArray['coy_name'];
		$invoice_header_title = "Invoice"; 
	    $coy_logo_phisical_path = ZROOT."accounting/company/".$account_name."/images/".$accounting_settingsArray['coy_logo'];
	    if(file_exists($coy_logo_phisical_path))
	    {
		  $coy_logo = ZBPATH."accounting/company/".$account_name."/images/".$accounting_settingsArray['coy_logo'];
		  $invoice_header_title = '<img src="'.$coy_logo.'" border="0" class="img-responsive img-thumbnail" style="max-width:250px;">';
	    }
	    else
	    {	
		  $invoice_header_title = drop_multiple_slashes($accounting_settingsArray['coy_name']);
	    } 
		
		global $currency_symbol;
		$invoice_subtotal = 0; 
		$invoice_discount_total = 0; 
		$invoice_total = 0; 
		$invoice_items_html = '';
		$sales_invoice_cart_data = json_decode(base64_decode($invoice_items),true);
		foreach($sales_invoice_cart_data as $each_cart_data)
		{
			$price = $each_cart_data['price'];
			$quantity = $each_cart_data['quantity'];
			$discount = $each_cart_data['discount'];
			$price_total = ($price*$quantity);
			$discount_amount = ($price_total*$discount)/100;
			$amount = ($price_total-$discount_amount);
			$invoice_subtotal +=$price_total;
			$invoice_discount_total +=$discount_amount;
			$invoice_total +=$amount;
			$invoice_items_html .= '
				<tr role="row">
					<td style="width:20%;text-align:left;height:30px;vertical-align:middle;">'.drop_multiple_slashes($each_cart_data['name']).'</td>
					<td style="width:40%;text-align:left;vertical-align:middle;">'.drop_multiple_slashes($each_cart_data['description']).'</td>
					<td style="width:10%;text-align:center;vertical-align:middle;">'.$currency_symbol.' '.numberFormatDsiplay($price).'</td>
					<td style="width:10%;text-align:center;vertical-align:middle;">'.$each_cart_data['quantity'].'</td>
					<td style="width:10%;text-align:center;vertical-align:middle;">'.$discount.'</td>
					<td style="width:10%;text-align:right;vertical-align:middle;">'.$currency_symbol.' '.numberFormatDsiplay($amount).'</td>
				</tr>';
		}
		
		$sales_invoice_cart_fees = $this->get_sales_invoice_fees_data($where=" WHERE add_fees_invoice_id = '$invoice_id'");
		foreach($sales_invoice_cart_fees as $key=>$each_fees_data)
		{
		   $invoice_add_fees_line = $each_fees_data['add_fees_line'];
		   $invoice_add_fees_id = $each_fees_data['add_fees_id'];
		   $invoice_add_fees_invoice_id = $each_fees_data['add_fees_invoice_id'];
		   $invoice_add_fees_type = $each_fees_data['add_fees_type'];
		   $invoice_add_fees_value = $each_fees_data['add_fees_value'];
		   $invoice_add_fees_description = $each_fees_data['add_fees_description'];
		   //$invoice_add_fees_description = str_replace('"',"&#34;",$invoice_add_fees_description); 
		   
		   $invoice_add_fees_description = (!empty($invoice_add_fees_description))?$invoice_add_fees_description:"Fees";
		   
		   $invoice_add_fees_value_display = $invoice_add_fees_value;
		   if($invoice_add_fees_type == 1)
		   {
			  $invoice_subtotal += $invoice_add_fees_value;
			  $invoice_total += $invoice_add_fees_value;
		   }
		   else
		   {
			  $invoice_add_fees_value_display = ($invoice_total*$invoice_add_fees_value)/100;
			  $invoice_subtotal += $invoice_add_fees_value_display;
			  $invoice_total += $invoice_add_fees_value_display;
		   } 
		   $invoice_items_html .= '
				<tr role="row">
					<td style="width:90%;text-align:left;height:30px;vertical-align:middle;" colspan="5">'.drop_multiple_slashes(new_line_html($invoice_add_fees_description)).'</td>
					<td style="width:10%;text-align:right;vertical-align:middle;">'.$currency_symbol.' '.numberFormatDsiplay($invoice_add_fees_value_display).'</td>
				</tr>';
		}
		
	    $invoice_email_body  = '';
	    $invoice_email_body .='
	    <html>
	    <body style="font-family:Source Sans Pro, Helvetica Neue, Helvetica, Arial, sans-serif;font-size:14px;color:#333;background-color:#FFF;font-weight:normal">
		  
		  <!-- Invoice Header -->
		  <p style="font-weight:normal;"><h1 style="text-align:center;font-weight:normal;">'.$invoice_header_title.'</h1></p>
		  
		  <!-- Invoice Content -->
		  <p style="border-bottom: 2px solid #000;clear:both;">
			  <!-- Invoice Title and Summary -->
			  <div style="width:65%;float:left;">
				<p><h2 style="font-weight:normal">'.$invoice_title.'</h2></p>
				<p>'.$invoice_summary.'</p>
			  </div>
			  <div style="width:35%;float:right;">
				<p><h3 style="font-weight:normal">Invoice Number : '.$invoice_number.'</h3></p>
				<p>
					<b>Invoice Date : </b>'.$invoice_date.'<br>
					<b>Invoice Payment Due : </b>'.$invoice_payment_due.'
				</p>
			  </div>
		  </p>
		  <p style="border-bottom: 1px solid #000;clear:both;">	  
			  <!-- Invoice Company and Customer -->
			  <div style="width:65%;float:left;">
				<p><h3 style="font-weight:normal">Invoice From</h3></p>
				<p>
					<b>'.drop_multiple_slashes($accounting_settingsArray['coy_name']).'</b><br>
					'.drop_multiple_slashes($accounting_settingsArray['postal_address']).'<br>
					<b>Phone : </b>'.$accounting_settingsArray['phone'].'<br>
					<b>Email : </b>'.$accounting_settingsArray['email'].'
				</p>
			  </div>
			  <div style="width:35%;float:right;">
				<p><h3 style="font-weight:normal">Invoice To</h3></p>
				<p>
					<b>'.drop_multiple_slashes($customer_name).'</b><br>
					'.drop_multiple_slashes($sales_invoice_customers_data['address']).'<br>
					<b>Phone : </b>'.$sales_invoice_customers_data['phone'].'<br>
					<b>Email : </b>'.$sales_invoice_customers_data['email'].'
				</p>
			  </div>
		  </p>
		  <p style="border-bottom: 1px solid #000;clear:both;">
		  	  <table width="100%" border="0" cellpadding="0" cellspacing="0">
			  	 <thead>
				 	<tr role="row">
						<th style="width:20%;text-align:left;height:35px;vertical-align:middle;">Name</th>
						<th style="width:40%;text-align:left;vertical-align:middle;">Description</th>
						<th style="width:10%;text-align:center;vertical-align:middle;">Price</th>
						<th style="width:10%;text-align:center;vertical-align:middle;">Quantity</th>
						<th style="width:10%;text-align:center;vertical-align:middle;">Discount %</th>
						<th style="width:10%;text-align:right;vertical-align:middle;">Amount</th>
					</tr>
				 </thead>
				 <body>
				 	<tr><td colspan="6" style="border-bottom: 1px solid #000;"></td></tr>
					'.$invoice_items_html.'
					<tr><td colspan="6" style="border-bottom: 2px solid #000;"></td></tr>
					<tr><td colspan="6" style="text-align:left;height:40px;vertical-align:middle;"><h3 style="font-weight:normal">&nbsp;Amount Due</h3></td></tr>
					<tr><td colspan="6" style="border-bottom: 1px solid #000;"></td></tr>
					<tr>
						<td style="width:80%;text-align:left;font-weight:bold;height:35px;vertical-align:middle;" colspan="5">&nbsp;Sub Total</td>
						<td style="width:20%;text-align:right;">'.$currency_symbol.' '.numberFormatDsiplay($invoice_subtotal).'</td>
					</tr>
					<tr>
						<td style="width:80%;text-align:left;font-weight:bold;height:35px;vertical-align:middle;" colspan="5">&nbsp;Total Discounts</td>
						<td style="width:20%;text-align:right;">'.$currency_symbol.' '.numberFormatDsiplay($invoice_discount_total).'</td>
					</tr>
					<tr>
						<td style="width:80%;text-align:left;font-weight:bold;height:35px;vertical-align:middle;" colspan="5">&nbsp;Total</td>
						<td style="width:20%;text-align:right;">'.$currency_symbol.' '.numberFormatDsiplay($invoice_total).'</td>
					</tr>
					<tr><td colspan="6" style="border-bottom: 1px solid #000;"></td></tr>
				 </body>
			  </table>
		  </p>
		  <p style="clear:both;text-align:center;">'.$invoice_note.'</p>
		  
	    </body>
	    </html>';
		
		$invoiceemaildataArray = array();
	    $invoiceemaildataArray["is_smtp"] = true;
	    $invoiceemaildataArray["from_email"] = !empty($accounting_settingsArray['email'])?$accounting_settingsArray['email']:FROM_EMAIL;
	    $invoiceemaildataArray["from_name"] = !empty($accounting_settingsArray['coy_name'])?$accounting_settingsArray['coy_name']:FROM_NAME;
	    $invoiceemaildataArray["to_email"] = $customer_email;
	    $invoiceemaildataArray["to_name"] = $customer_name;
	    $invoiceemaildataArray["email_subject"] = $invoice_email_subject;
	    $invoiceemaildataArray["email_message_html"] = $invoice_email_body;
	    //print_r($invoiceemaildataArray);
	    $invoiceemail_status = ZentroveEmail($invoiceemaildataArray);
	    $invoiceemail_statusArray = explode("|",$invoiceemail_status);
		
		return $invoiceemail_statusArray;
		
	}	
	
/*Function to get Total Sales Invoices*/	
public function getTotalInvoices($condition="")
	{
		$invoices =  $this->getRows("COUNT(invoice_id) as total_invoices",$this->tableprefix."invoices",$condition);
		return $invoices[0]['total_invoices'];
	}
	
/*Function to get Total Sales Invoices Amount*/	
public function getTotalInvoicesAmount($condition="")
	{
		$invoices =  $this->getRows("SUM(invoice_total) as total_invoices_amount",$this->tableprefix."invoices",$condition);
		return $invoices[0]['total_invoices_amount'];
	}

/*Function to get Total Outstanding Sales Invoices*/	
public function getTotalOutstandingInvoices()
	{
		$invoices =  $this->getRows("COUNT(invoice_id) as total_invoices",$this->tableprefix."invoices"," WHERE is_paid=0 ");
		return $invoices[0]['total_invoices'];
	}
	
/*Function to get Total Outstanding Sales Invoices Amount*/	
public function getTotalOutstandingInvoicesAmount()
	{
		$invoices =  $this->getRows("SUM(invoice_total) as total_invoices_amount",$this->tableprefix."invoices"," WHERE is_paid=0 ");
		return $invoices[0]['total_invoices_amount'];
	}
	
/*Function to get Total Paid Sales Invoices*/	
public function getTotalPaidInvoices()
	{
		$invoices =  $this->getRows("COUNT(invoice_id) as total_invoices",$this->tableprefix."invoices"," WHERE is_paid=1 ");
		return $invoices[0]['total_invoices'];
	}
	
/*Function to get Total Paid Sales Invoices Amount*/	
public function getTotalPaidInvoicesAmount()
	{
		$invoices =  $this->getRows("SUM(invoice_total) as total_invoices_amount",$this->tableprefix."invoices"," WHERE is_paid=1 ");
		return $invoices[0]['total_invoices_amount'];
	}

/************************/
/*Functions for Reports */
/************************/

/*Function to get Total Sales Orders*/
public function getTotalSalesOrders($conditions)
	{
		$sales_orders =  $this->getRows("COUNT(*) as total_sales_orders",$this->tableprefix."sales_orders",$conditions);
		return $sales_orders[0]['total_sales_orders'];
	}
	
/*Function to get Total Sales Orders Amount*/
public function getTotalSalesOrdersAmount($conditions)
	{
		$sales_orders =  $this->getRows("SUM(net_total) as total_sales_orders_amount",$this->tableprefix."sales_orders",$conditions);
		return $sales_orders[0]['total_sales_orders_amount'];
	}	

/*Function to get Sales Orders Data*/
public function get_sales_orders($where="",$groupby="",$orderby="",$limit="")
	{
		return $this->getRows("*",$this->tableprefix."sales_orders"," ".$where." ".$groupby." ".$orderby." ".$limit);
	}	
	
/*Function to get Sales Order Details Data*/
public function get_sales_order_details($where="",$groupby="",$orderby="",$limit="")
	{
		return $this->getRows("*",$this->tableprefix."sales_order_details"," ".$where." ".$groupby." ".$orderby." ".$limit);
	}
	
/*Function to get Sales Order Customer Data*/
public function get_sales_order_customer($where="",$orderby="",$limit="")
	{
		$tbl_customers_persons = $this->tableprefix."crm_persons";  
		$tbl_customers_contacts = $this->tableprefix."crm_contacts";  
		$inner_join=" INNER JOIN $tbl_customers_contacts ON $tbl_customers_persons.id = $tbl_customers_contacts.person_id AND type='customer' ";
		return $this->getRows("*",$tbl_customers_persons,$inner_join." ".$where." ".$orderby." ".$limit);
	}		
	
/*Function to get Chart Accounts Heads*/
public function getHeadAccounts($where="",$orderby="",$limit="")
	{
		return $this->getRows("*",$this->tableprefix."chart_types"," ".$where." ".$orderby." ".$limit);
	}
	
/*Function to get Chart Sub Accounts*/
public function getSubAccounts($where="",$orderby="",$limit="")
	{
		return $this->getRows("*",$this->tableprefix."chart_master"," ".$where." ".$orderby." ".$limit);
	}
	
/*Function to get Chart Sub Accounts*/
public function getGLTransactions($fields="*",$where="",$orderby="",$limit="")
	{
		return $this->getRows($fields,$this->tableprefix."gl_trans"," ".$where." ".$orderby." ".$limit);
	}	
	
/*Function to Get COGS Report*/
public function getCOGSReport($start_date,$end_date)
	{
		
		$inventoriescogs = array();
		
		$table_items = TBLPREFIX_OPOS."items";
		$table_inventory = TBLPREFIX_OPOS."inventory";
		$table_receivings_items = TBLPREFIX_OPOS."receivings_items";
		
		//Cost of existing inventory at the beginning of the report period
		//return "SELECT SUM(cost_price) as xcost FROM $table_inventory as ppiv,$table_items as ppit WHERE ppit.item_id = ppiv.trans_items AND DATE(trans_date) = $start_date ";
		$sql_xcost = $this->dbqueryexe("SELECT SUM(cost_price) as xcost FROM $table_inventory as ppiv,$table_items as ppit WHERE ppit.item_id = ppiv.trans_items AND DATE(trans_date) = $start_date");
		$result_xcost = mysql_fetch_array($sql_xcost);
		$inventoriescogs['xcost'] = $result_xcost['xcost'];
		
	    //Cost of inventory purchased during the report period
	    //return "SELECT SUM(item_cost_price) as ycost FROM $table_inventory as ppiv,$table_receivings_items as pprit WHERE pprit.item_id = ppiv.trans_items AND (DATE(trans_date) >= $start_date AND DATE(trans_date) <= $end_date)";
		$sql_ycost = $this->dbqueryexe("SELECT SUM(item_cost_price) as ycost FROM $table_inventory as ppiv,$table_receivings_items as pprit WHERE pprit.item_id = ppiv.trans_items AND (DATE(trans_date) >= $start_date AND DATE(trans_date) <= $end_date)");
		$result_ycost = mysql_fetch_array($sql_ycost);
		$inventoriescogs['ycost'] = $result_ycost['ycost'];
		
		//Cost of inventory on hand at the end of the report period
		//return "SELECT SUM(cost_price) as zcost FROM $table_inventory as ppiv,$table_items as ppit WHERE ppit.item_id = ppiv.trans_items AND DATE(trans_date) = $end_date AND quantity>0";
		$sql_zcost = $this->dbqueryexe("SELECT SUM(cost_price) as zcost FROM $table_inventory as ppiv,$table_items as ppit WHERE ppit.item_id = ppiv.trans_items AND DATE(trans_date) = $end_date AND quantity>0");
		$result_zcost = mysql_fetch_array($sql_zcost);
		$inventoriescogs['zcost'] = $result_zcost['zcost'];
	    
		return $inventoriescogs;
	}

/******************************/
/*Functions for Sales Projects*/
/******************************/

/*Function to get Sales Projects Data*/
public function get_sales_projects_data($where,$orderby,$limit)
	{
		$fields =  "*";
		$get_sales_projects_data =  $this->getRows($fields,$this->tableprefix."wt_projects",  "  ".$where." ".$orderby." ".$limit);	
		return $get_sales_projects_data;
	}
						
/*Function to get Sales Project Data*/
public function get_sales_project_data($project_id)
	{
		$fields = "*";
		$get_sales_projects_data =  $this->getRow($fields,$this->tableprefix."wt_projects", " where id  = '".$project_id."'  " );	
		return $get_sales_projects_data;
	}
	
/*Function to close database connection*/					
public function close()
	{
		$this->close_db($this->conn);
	}					
	
}
?>