<?php

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

class User extends CI_Model {

    public function __construct() {
        parent::__construct();

        //load database library
        $this->load->database();
    }

    /*
     * Fetch user data
     */
     function getReport($id = ""){
     if(!empty($id)){
      $this->db->order_by("id","desc");
      $query = $this->db->get_where('sales', array('customer_id' => $id))->result_array();
      return $query;
     }else{
    $customer = $this->db->get_where('companies', array('group_id' =>'3'));
             foreach($customer->result_array() as $row ){
               $query = $this->db->get_where('sales', array('customer_id' => $row['id']))->result_array();
               return $query;
               }
               }
    }
     public function getLastReference($id) {//print_r($id);die();
        $this->db->limit(1);
        $this->db->order_by('id','desc');
        $q =$this->db->get_where('sales',array('biller_id' => $id), 1);
        if ($q->num_rows() > 0) {
          $return = $q->row()-> reference_no;
        }
        else{
         
       $value = "no sales";
               $return = $value;
        }
        return $return;
    }
      public function getDummyReference($id) {
         if(!empty($id)){
              $this->db->limit(1);
        $this->db->order_by('id','desc');
        $q =$this->db->get_where('sales',array('biller_id' => $id), 1);
        if ($q->num_rows() > 0) {//print_r($q->row()->dummy_reference);die();
              return $q->row()->dummy_reference;
        }
         }
         else{
        return FALSE;
         }
          //return $return;
    }
     public function getPrinterByID($id) {
        $q = $this->db->get_where('printers', array('id' => $id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
     function getSetting()
    {
        $q = $this->db->get('pos_settings');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
    function getuser($id = ""){
        if(!empty($id)){
            $query = $this->db->get_where('users', array('id' => $id));
            return $query->row_array();
        }else{
            $query = $this->db->get('users');
            return $query->result_array();
        }
    }

    function getbrand($id = ""){
        if(!empty($id)){
            $query = $this->db->get_where('brands', array('id' => $id));
            return $query->row_array();
        }else{
            $query = $this->db->get('brands');
            return $query->result_array();
        }
    }

    function getproduct($id = ""){
  /*  $product= array();
        if(!empty($id)){
        $warehouse = $this->db->get_where('warehouses_products', array('warehouse_id' => $id));//print_r($warehouse->result_array());die();
        foreach($warehouse->result_array() as $row){
        
            $query = $this->db->get_where('products', array('id' => $row['product_id']))->result_array();
           // print_r($query);
        /* $product = array(		"id"				=> $row['id'],
					"code"				=> $row['code'],
					"name"				=> $row['name'],
					"unit"				=> $row['unit'],
					"cost"				=> $row['cost'],
					"profit"			=> $row['profit'],
					"profit%"			=> $row['profit%'],
					"price"				=> $row['price'],
					"alert_quantity"		=> $row['alert_quantity'],
					"image"				=> $row['image'],
					"category_id"			=> $row['category_id'],
					"subcategory_id"		=> $row['subcategory_id'],
					"cf1" 				=> $row['cf1'], 
					"cf2" 				=> $row['cf2'], 
					"cf3" 				=> $row['cf3'],
					"cf4" 				=> $row['cf4'],
					"cf5" 				=> $row['cf5'],
					"cf6" 				=> $row['cf6'],
					"quantity"			=> $row['quantity'],
					"tax_rate"			=> $row['tax_rate'],
					"track_quantity"		=> $row['track_quantity'],
					"details"			=> $row['details'],
					"warehouse"			=> $row['warehouse'],
					"barcode_symbology"		=> $row['barcode_symbology'],
					"file"				=> $row['file'],
					"product_details"		=> $row['product_details'],
					"tax_method"			=> $row['tax_method'],
					"type"				=> $row['type'],
					"supplier1"			=> $row['supplier1'],
					"supplier1price"		=> $row['supplier1price'],
					"supplier2"			=> $row['supplier2'],
					"supplier2price"		=> $row['supplier2price'],
					"supplier3"			=> $row['supplier3'],
					"supplier3price"		=> $row['supplier3price'],
					"supplier4"			=> $row['supplier4'],
					"supplier4price"		=> $row['supplier4price'],
					"supplier5"			=> $row['supplier5'],
					"supplier5price"		=> $row['supplier5price'],
					"promotion"			=> $row['promotion'],
					"promo_price"			=> $row['promo_price'],
					"start_date"			=> $row['start_date'],
					"end_date"			=> $row['end_date'],
					"supplier1_part_no"		=> $row['supplier1_part_no'],
					"supplier2_part_no"		=> $row['supplier2_part_no'],
					"supplier3_part_no"		=> $row['supplier3_part_no'],
					"supplier4_part_no"		=> $row['supplier4_part_no'],
					"supplier5_part_no"		=> $row['supplier5_part_no'],
					"sale_unit"			=> $row['sale_unit'],
					"purchase_unit"			=> $row['purchase_unit'],
					"brand"				=> $row['brand'],
					"slug"				=> $row['slug'],
					"featured"			=> $row['featured'],
					"weight"			=> $row['weight'],
					"hsn_code"			=> $row['hsn_code'],
					"views"				=> $row['views'],
					"hide"				=> $row['hide'],
					"second_name"			=> $row['second_name'],
         
         );*/	
           /* }  return  $query;
            
        }else{
            $query = $this->db->get('products');
            return $query->result_array();
        }*/
         if(!empty($id)){
            $this->db->select('u.*,s.*');
            $this->db->from('warehouses_products as s');
            $this->db->where('s.warehouse_id' , $id);
            $this->db->join('products as u', ' u.id = s.product_id');
             $this->db->order_by('u.code', 'ASC');
           $query = $this->db->get();
           
        return $query->result();
    }
    }
    function getcategories($id = ""){
        if(!empty($id)){
            $query = $this->db->get_where('categories', array('id' => $id));
            return $query->row_array();
        }else{
            $query = $this->db->get('categories');
            return $query->result_array();
        }
    }
    function getcompaines($id = ""){
          $result = array(); 
        if(!empty($id)){
            $query = $this->db->get_where('companies', array('warehouse_id' => $id,'group_id' => '3'))->result_array();
           foreach($query as $row){
                $credit = $this->db->get_where('sales', array('customer_id' =>$row['id']))->result_array();
                 $paid=$grandtotal=$gran=$pid=0;
         $tot_credit =0;
         
         $data = array(
                    "id"					=>$row['id'],
                    "group_id"				=>$row['group_id'],
                    "group_name"			=>$row['group_name'],
                    "customer_group_id"		=>$row['customer_group_id'],
                    "customer_group_name"	=>$row['customer_group_name'],
                    "name" 					=>$row['name'],
                    "company"				=>$row['company'],
                    "vat_no"				=>$row['vat_no'],
                    "address"				=>$row['address'],
                    "city"					=>$row['city'],
                    "state"					=>$row['state'],
                    "postal_code"			=>$row['postal_code'],
                    "country"				=>$row['country'],
                    "phone"					=>$row['phone'],
                    "email"					=>$row['email'],
                    "cf1"					=>$row['cf1'],
                    "cf2"					=>$row['cf2'],
                    "cf3"					=>$row['cf3'],
                    "cf4"					=>$row['cf4'],
                    "cf5"					=>$row['cf5'],
                    "cf6"					=>$row['cf6'],
                    "invoice_footer"		=>$row['invoice_footer'],
                    "payment_term"			=>$row['payment_term'],
                    "logo"					=>$row['logo'],
                    "award_points"			=>$row['award_points'],
                    "deposit_amount"		=>$row['deposit_amount'],
                    "price_group_id"		=>$row['price_group_id'],
                    "price_group_name"		=>$row['price_group_name']
                   
                    );
          
         if($credit){
            foreach($credit as $row2){
              
                if($row2['payment_status'] != "Paid"){
                $paid += $row2['paid'];
                $grandtotal += $row2['grand_total'];
                $pid +=$paid;
                $tot_credit = $grandtotal  - $paid;
                $tat_com = $this->formatDecimal($tot_credit);
               $data['credit_balance'] = "$tat_com" ;
                    
            }
         
            }
         }else{
              $data['credit_balance'] = "0" ;
         }
              $result[] = $data;
             
            }
            return $result;
        }else{
            $companies = $this->db->get_where('companies', array('group_id' => '3'))->result_array();
            foreach($companies as $row){
                $credit = $this->db->get_where('sales', array('customer_id' =>$row['id']))->result_array();
                 $paid=$grandtotal=$gran=$pid=0;
         $tot_credit =0;
         
         $data = array(
                    "id"					=>$row['id'],
                    "group_id"				=>$row['group_id'],
                    "group_name"			=>$row['group_name'],
                    "customer_group_id"		=>$row['customer_group_id'],
                    "customer_group_name"	=>$row['customer_group_name'],
                    "name" 					=>$row['name'],
                    "company"				=>$row['company'],
                    "vat_no"				=>$row['vat_no'],
                    "address"				=>$row['address'],
                    "city"					=>$row['city'],
                    "state"					=>$row['state'],
                    "postal_code"			=>$row['postal_code'],
                    "country"				=>$row['country'],
                    "phone"					=>$row['phone'],
                    "email"					=>$row['email'],
                    "cf1"					=>$row['cf1'],
                    "cf2"					=>$row['cf2'],
                    "cf3"					=>$row['cf3'],
                    "cf4"					=>$row['cf4'],
                    "cf5"					=>$row['cf5'],
                    "cf6"					=>$row['cf6'],
                    "invoice_footer"		=>$row['invoice_footer'],
                    "payment_term"			=>$row['payment_term'],
                    "logo"					=>$row['logo'],
                    "award_points"			=>$row['award_points'],
                    "deposit_amount"		=>$row['deposit_amount'],
                    "price_group_id"		=>$row['price_group_id'],
                    "price_group_name"		=>$row['price_group_name']
                   
                    );
          
         if($credit){
            foreach($credit as $row2){
              
                if($row2['payment_status'] != "Paid"){
                $paid += $row2['paid'];
                $grandtotal += $row2['grand_total'];
                $pid +=$paid;
                $tot_credit = $grandtotal  - $paid;
                $tat_com = $this->formatDecimal($tot_credit);
               $data['credit_balance'] = "$tat_com" ;
                    
            }
         
            }
         }else{
              $data['credit_balance'] = "0" ;
         }
              $result[] = $data;
             
            }
            return $result;
        }
    }
    
   function getbiller($id = ""){
     $response = array();
        if(!empty($id)){
            $query = $this->db->get_where('companies', array('id' => $id));
            foreach($query->row_array() as $row ){
           // print_r($row);die();
            }
           // return $query->row_array();
        }else{
            $query = $this->db->get_where('companies', array('group_id' => null));
             foreach($query->result_array() as $row ){
           // $user = $this->db->get_where('users',array('biller_id'=> $row['id']))->row()->id;
             $user_id= $this->db->from('users')->where('biller_id',$row['id'])->get()->row();
           
             /*$user_id =  $this->db
             ->select('id')
             ->from('users')
             ->where('biller_id',$row['id'])
             ->where('biller_id',NULL)
           ->get()->result();*/
             
           if(!empty($user_id)){
            $biller = array(
            			   "id" 			=> $row['id'],
            			   "user_id"			=>  $user_id->id,
				    "group_id" 			=> $row['group_id'],
				    "group_name" 		=> $row['group_name'],
				    "customer_group_id" 	=> $row['customer_group_id'],
				    "customer_group_name" 	=> $row['customer_group_name'],
				    "name" 			=> $row['name'],
				    "company" 			=> $row['company'],
				    "vat_no" 			=> $row['vat_no'],
				    "address" 			=> $row['address'],
				    "city" 			=> $row['city'],
				    "state" 			=> $row['state'],
				    "postal_code" 		=> $row['postal_code'],
				    "country" 			=> $row['country'],
				    "phone" 			=> $row['phone'],
				    "email" 			=> $row['email'],
				    "cf1" 			=> $row['cf1'], 
				    "cf2" 			=> $row['cf2'], 
				    "cf3" 			=> $row['cf3'],
				    "cf4" 			=> $row['cf4'],
				    "cf5" 			=> $row['cf5'],
				    "cf6" 			=> $row['cf6'],
				    "invoice_footer" 		=> $row['invoice_footer'],
				    "payment_term" 		=> $row['payment_term'],
				    "logo" 			=> $row['logo'],
				    "award_points" 		=> $row['award_points'],
				    "deposit_amount" 		=> $row['deposit_amount'],
				    "price_group_id" 		=> $row['price_group_id'],
				    "price_group_name" 		=> $row['price_group_name'],
				    );
			$response[] = $biller;	   
           
           }
           else{
            $biller = array(
            			   "id" 			=> $row['id'],
            			   "user_id"			=> 1,
				    "group_id" 			=> $row['group_id'],
				    "group_name" 		=> $row['group_name'],
				    "customer_group_id" 	=> $row['customer_group_id'],
				    "customer_group_name" 	=> $row['customer_group_name'],
				    "name" 			=> $row['name'],
				    "company" 			=> $row['company'],
				    "vat_no" 			=> $row['vat_no'],
				    "address" 			=> $row['address'],
				    "city" 			=> $row['city'],
				    "state" 			=> $row['state'],
				    "postal_code" 		=> $row['postal_code'],
				    "country" 			=> $row['country'],
				    "phone" 			=> $row['phone'],
				    "email" 			=> $row['email'],
				    "cf1" 			=> $row['cf1'], 
				    "cf2" 			=> $row['cf2'], 
				    "cf3" 			=> $row['cf3'],
				    "cf4" 			=> $row['cf4'],
				    "cf5" 			=> $row['cf5'],
				    "cf6" 			=> $row['cf6'],
				    "invoice_footer" 		=> $row['invoice_footer'],
				    "payment_term" 		=> $row['payment_term'],
				    "logo" 			=> $row['logo'],
				    "award_points" 		=> $row['award_points'],
				    "deposit_amount" 		=> $row['deposit_amount'],
				    "price_group_id" 		=> $row['price_group_id'],
				    "price_group_name" 		=> $row['price_group_name'],
				    );
			$response[] = $biller;	   
            }
          }
           return $response; 
        }
    }
    function getsuspend($id = ""){
     $response = array();
  
         if(!empty($id))
         {
              $query = $this->db->get_where('suspended_bills',array('created_by' =>$id))->result_array();//print_r($query);die();
               foreach($query as $row){
               	$pduct = $this->db->get_where('suspended_items',array('suspend_id'=>$row['id']))->result_array();//print_r($product);die();
               	 $product = array();
               	 foreach($pduct as $rows){
               	  $pro = array(
                         			'id'				=> $rows['id'],
						'suspend_id'			=> $rows['suspend_id'],
						'id'				=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'				=> $rows['item_tax'],
						'tax_rate'			=> $rows['tax_rate_id'],
				// 		'tax'				=> $rows['tax'],
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=> $rows['real_unit_price'],
						'product_unit_id'		=> $rows['product_unit_id'],
						'product_unit_code'		=> $rows['product_unit_code'],
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $product[]= $pro;
                          }//print_r($product);die();
           	$data = array(
                          	'id'			=> $row['id'],
				'date'			=> $row['date'],	
				'customer_id'		=> $row['customer_id'],
				'customer'		=> $row['customer'],
				'count'			=> $row['count'],	
				'order_discount_id'	=> $row['order_discount_id'],	
				'order_tax_id'		=> $row['order_tax_id'],	
				'total'			=> $row['total'],
				'biller_id'		=> $row['biller_id'],	
				'warehouse_id'		=> $row['warehouse_id'],	
				'created_by'		=> $row['created_by'],	
				'suspend_note'		=> $row['suspend_note'],	
				'shipping'		=> $row['shipping'],							  	  	
				'cgst'			=> $row['cgst'],
				'sgst'			=> $row['sgst'],
				'igst'			=> $row['igst'],
                        'products' =>$product,
                         
                          
               			
                        	);
                        	
                        	
                      
                       $response[] = $data;	
                        	}
               
         }
         else
         {
             
               $query = $this->db->get('suspended_bills')->result_array();//print_r($query);die();
               foreach($query as $row){
               	$pduct = $this->db->get_where('suspended_items',array('suspend_id'=>$row['id']))->result_array();//print_r($product);die();
               	 foreach($pduct as $rows){
               	  $pro = array(
                         			'id'				=> $rows['id'],
						'suspend_id'			=> $rows['suspend_id'],
						'id'				=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'			=> $rows['item_tax'],
						'tax_rate_id'			=> $rows['tax_rate_id'],
				// 		'tax'				=> $rows['tax'],
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=> $rows['real_unit_price'],
						'product_unit_id'		=> $rows['product_unit_id'],
						'product_unit_code'		=> $rows['product_unit_code'],
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $product[]= $pro;
                          }//print_r($product);die();
           	$data = array(
                          	'id'			=> $row['id'],
				'date'			=> $row['date'],	
				'customer_id'		=> $row['customer_id'],
				'customer'		=> $row['customer'],
				'count'			=> $row['count'],	
				'order_discount_id'	=> $row['order_discount_id'],	
				'order_tax_id'		=> $row['order_tax_id'],	
				'total'			=> $row['total'],
				'biller_id'		=> $row['biller_id'],	
				'warehouse_id'		=> $row['warehouse_id'],	
				'created_by'		=> $row['created_by'],	
				'suspend_note'		=> $row['suspend_note'],	
				'shipping'		=> $row['shipping'],							  	  	
				'cgst'			=> $row['cgst'],
				'sgst'			=> $row['sgst'],
				'igst'			=> $row['igst'],
                        'products' =>$product,
                         
                          
               			
                        	);
                        	
                        	
                      
                       $response[] = $data;	
                        	}
               
         }
        return  $response;
    }

    function getpayments($id = ""){

        $this->db->select('payments.amount,payments.note,payments.paid_by,sales.note,sales.staff_note');
        $this->db->from('sales');
       // $this->db->where('payments.sale_id',$id);
        $this->db->join('payments', 'payments.sale_id = sales.id','left');
        $query=$this->db->get();
          return $query->result_array();

    }
    
     function paymentview($id = ""){
     
        if(!empty($id)){//print_r($id);die();
            $query = $this->db->get_where('payments', array('sale_id' => $id));
            return $query->result_array();
        } 
        return  FALSE;
    }
    
    /***************************open and close register************************/
   function getregister($id = ""){
        if(!empty($id)){
            $q = $this->db->get_where('pos_register', array('user_id' => $id, 'status' => 'open'), 1);
	        if ($q->num_rows() > 0)
	         {
	            return $q->row();
	         }
        }
            return  FALSE;
       
    }
 public function openRegister($data)
    {
        if ($this->db->insert('pos_register', $data)) {
            return TRUE;
        }
        return FALSE;
    }

    public function getOpenRegisters()
    {
        $this->db->select("date, user_id, cash_in_hand, CONCAT(" . $this->db->dbprefix('users') . ".first_name, ' ', " . $this->db->dbprefix('users') . ".last_name, ' - ', " . $this->db->dbprefix('users') . ".email) as user", FALSE)
            ->join('users', 'users.id=pos_register.user_id', 'left');
        $q = $this->db->get_where('pos_register', array('status' => 'open'));
        if ($q->num_rows() > 0) {
            foreach ($q->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return FALSE;

    }

    public function closeRegister($rid, $user_id, $data)
    {
        $prdocts=array();
        if (!$rid) {
            $rid = $this->session->userdata('register_id');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }
        $date   = $data['closed_at'];
        if ($data['transfer_opened_bills'] == -1) {
            $this->db->delete('suspended_bills', array('created_by' => $user_id));
        } elseif ($data['transfer_opened_bills'] != 0) {
            $this->db->update('suspended_bills', array('created_by' => $data['transfer_opened_bills']), array('created_by' => $user_id));
        }
        if ($this->db->update('pos_register', $data, array('id' => $rid, 'user_id' => $user_id)))
        {
            $warehouse_id = $this->db->get_where('users', array('id' => $user_id))->row()->warehouse_id;
            $procts =$this->db->get_where('warehouses_products',array('warehouse_id'=>$warehouse_id))->result_array();
            foreach($procts as $row)
            {
                $product_id = $row['product_id'];
                $product_qty = $row['quantity'];
                $product_name= $this->db->get_where('products',array('id'=>$product_id))->row()->name;
                $unit_price = $this->db->get_where('products',array('id'=>$product_id))->row()->price;
                $brand = $this->db->get_where('products',array('id'=>$product_id))->row()->brand;
                
                 $dat = date('Y-m-d', strtotime($date));
                 $today = date('Y-m-d');
                 if($today ==  $dat )
                 {
                    //$ts = ('Y-m-d',$ts);
                    $tomrw          = date('Y-m-d', strtotime('+1 day', strtotime($dat)));
                 }
                $data =array(
        						'product_id'      => $product_id,
                                'product_name'    => $product_name,
                                'date'            => $date,
                                'compare_date'    => $tomrw,
                                'warehouse_id'    => $warehouse_id,
                                'brand '        =>$brand,
                                'unit_price'=>$unit_price,
                                'previous_stock'=> $product_qty,
                                'current_stock'=>$product_qty
                    );
        		$prdocts[] = $data;	
            }
         $this->addProductDailyOffline($prdocts);
             return TRUE;
        }
        return FALSE;
    }	

    /*
     * Insert user data
     */
     public function getinsert($sData,$items) {
$this->db->insert('suspended_items', $items);

      return TRUE; 

}

  public function mapPost($data) {
        if(!empty($data)){
            $update = $this->db->insert('map', $data);
            return TRUE;
        }else{
            return false;
        }
    }

    public function putcompaines($data, $id) {
        if(!empty($data) && !empty($id)){
            $update = $this->db->update('companies', $data, array('id'=>$id));
            return TRUE;
        }else{
            return false;
        }
    }
 public function addcompaines($data) {
        if(!empty($data)){
            $update = $this->db->insert('companies', $data);
            return TRUE;
        }else{
            return false;
        }
    }
    
    function getgroup($id = ""){
        if(!empty($id)){
            $query = $this->db->get_where('customer_groups', array('id' => $id));
            return $query->row_array();
        }else{
            $query = $this->db->get('customer_groups');
            return $query->result_array();
        }
    }
    function getpricegroup($id = ""){
        if(!empty($id)){
            $query = $this->db->get_where('price_groups', array('id' => $id));
            return $query->row_array();
        }else{
            $query = $this->db->get('price_groups');
            return $query->result_array();
        }
    }
    
    function getSaleDetailsView($id){ 
        if(!empty($id)){
                  $this->db->order_by("id","desc");
          $query = $this->db->get_where('sales',array('id'=>$id))->result_array();//print_r($query);die();
          
if(!empty($query)){
	foreach($query as  $row)
	{
	   
    		$prouduct = $this->db->get_where('sale_items',array('sale_id'=>$id))->result_array();
    		$payment_by =$this->db->get_where('payments',array('sale_id'=>$id))->result_array();
    		
    		if(!empty($payment_by)){
    		   // print_r($payment_by);die();
    		   if(count($payment_by) > 1) {
    		        $this->db->limit('1');
    		       $paid_by = $this->db->get_where('payments',array('sale_id'=>$id))->row()->paid_by;
    		   }
    		   else{
    		        $paid_by = $this->db->get_where('payments',array('sale_id'=>$id))->row()->paid_by;
    		        
    		   }
    		}
    			 $products = array();
               	 foreach($prouduct as $rows){
               	     $biller_id = $row['biller_id'];
               	     $second_name = $this->db->get_where('products',array('id'=> $rows['product_id']))->row()->second_name;
               	 $tax_method = $this->db->get_where('products',array('id'=> $rows['product_id']))->row()->tax_method;
               	  $prod = array(
                         			'sale_item_id'			=> $rows['id'],
						'sale_id'			=> $rows['sale_id'],
						'product_id'			=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
						'second_name'       =>$second_name,
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'				=> $rows['item_tax'],
						'tax_rate'			=> $rows['tax_rate_id'],
						'tax_method'				=> $tax_method,
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=>$rows['net_unit_price'],
						'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
						'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $products[]= $prod;
                          $url = 'http://printsa.cignestrade.com/welcome/'.$rows['sale_id'].'';
                          }
                          $company=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->company;
                          $vat=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->vat_no;
                          $address=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->address;
                          $city=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->city;
                          $state=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->state;
                          $postal_code=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->postal_code;
                          $country=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->country;
                          $phone=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->phone;
                          $email=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->email;
                           $biller = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->name;
                            $biller_company = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->company;
                            $biller_warehouse_id = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->warehouse_id;
                            $biller_vat = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->vat_no;
                            $biller_address=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->address;
                         $biller_city=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->city;
                         $biller_state=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->state;
                         $biller_postal_code=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->postal_code;
                         $biller_country=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->country;
                         $biller_phone=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->phone;
                          $biller_email=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->email;
                           
                            $biller_company_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf1;
                        $biller_name_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf2;
                        $biller_vat_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf3;
                        $biller_phone_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf4;
                        $biller_address_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf5;
                        $biller_city_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf6;
                        
                        
                         $customer_company_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf1;
                        $customer_name_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf2;
                        $customer_vat_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf3;
                        $customer_phone_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf4;
                        $customer_address_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf5;
                        $customer_city_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf6;
                           
                          // print_r( $row['biller_id']);die();
                           if($row['warehouse_id'] == $biller_warehouse_id){
                            $first_name = $this->db->get_where('users', array('warehouse_id' => $row['warehouse_id']))->row()->first_name;
                             $last_name = $this->db->get_where('users', array('warehouse_id' =>$row['warehouse_id']))->row()->last_name;
                             $sale = $first_name." ".$last_name;
                           }
                           else{
                               $sale ="Admin";
                           }
                             ///print_r($sale);die();
        	$data = array(
                        			'id' 				=> $row['id'],
						'date'				=> $row['date'],
						'sale_associate' =>$sale,
						'reference_no'			=> $row['reference_no'],
						'dummy_reference'=>$row['dummy_reference'],
						'customer_id'			=> $row['customer_id'],
						'customer'			=> $row['customer'],
						'company'		=> $biller_company,
						'vat'			=> $vat,
						'vat_number'    =>$biller_vat,
						'address'		=> $address,
						'city'			=> $city,
						'state'			=> $state,
						'postal_code'	=> $postal_code,
						'country'		=> $country,
						'phone'			=> $phone,
						'email'			=> $email,
						'biller_id'			=> $row['biller_id'],
						'biller'			=> $biller,
						'biller_address'		=> $biller_address,
						'biller_city'			=> $biller_city,
						'biller_state'			=> $biller_state,
						'biller_postal_code'	=> $biller_postal_code,
						'biller_country'		=> $biller_country,
						'biller_phone'			=> $biller_phone,
						'biller_email'			=> $biller_email,
						
							'arabic_customerr_company'		     => !empty($customer_company_arabic)?$customer_company_arabic:'',
						'arabic_customer_address'	 => !empty($customer_address_arabic)?$customer_address_arabic:'',
						'arabic_customer_name'	=> !empty($customer_name_arabic)?$customer_name_arabic:'',
						'arabic_customer_city'	=> !empty($customer_city_arabic)?$customer_city_arabic:'',
						'arabic_customer_phone'	=> !empty($customer_phone_arabic)?$customer_phone_arabic:'',
						'arabic_customer_vat_number'	=> !empty($customer_vat_arabic)?$customer_vat_arabic:'',
						
						'arabic_biller_company'		     => !empty($biller_company_arabic)?$biller_company_arabic:'',
						'arabic_biller_state'	 => !empty($biller_address_arabic)?$biller_address_arabic:'',
						'arabic_biller_address'	=> !empty($biller_name_arabic)?$biller_name_arabic:'',
						'arabic_biller_country'	=> !empty($biller_city_arabic)?$biller_city_arabic:'',
						'arabic_biller_city'	=> !empty($biller_phone_arabic)?$biller_phone_arabic:'',
						'arabic_biller_address_1'	=> !empty($biller_vat_arabic)?$biller_vat_arabic:'',
						
						
						
						
						
						
						
						'paid_by'=> !empty($paid_by)?$paid_by:'',
						'warehouse_id'			=> $row['warehouse_id'],
						'note'				=> $row['note'],
						'staff_note'			=> $row['staff_note'],
						'total'				=> $row['total'],
						'product_discount'		=> $row['product_discount'],
						'order_discount_id'		=> $row['order_discount_id'],
						'total_discount'		=> $row['total_discount'],
						'order_discount'		=> $row['order_discount'],
						'product_tax'			=> $row['product_tax'],
						'order_tax_id'			=> $row['order_tax_id'],
						'order_tax'			=> $row['order_tax'],
						'total_tax'			=> $row['total_tax'],
						'shipping'			=> $row['shipping'],
						'grand_total'			=> $row['grand_total'],
						'sale_status'			=> $row['sale_status'],
						'payment_status'		=> $row['payment_status'],
						'payment_term'			=> $row['payment_term'],
						'due_date'			=> $row['due_date'],
						'created_by'			=> $row['created_by'],
						'updated_by'			=> $row['updated_by'],
						'updated_at'			=> $row['updated_at'],
						'total_items'			=> $row['total_items'],
						'pos'				=> $row['pos'],
						'paid'				=> $row['paid'],
						'return_id'			=> $row['return_id'],
						'delete_id'			=> $row['delete_id'],
						'surcharge'			=> $row['surcharge'],
						'attachment'			=> $row['attachment'],
						'return_sale_ref'		=> $row['return_sale_ref'],
						'sale_id'			=> $row['sale_id'],
						'return_sale_total'		=> $row['return_sale_total'],
						'rounding'			=> $row['rounding'],
						'suspend_note'			=> $row['suspend_note'],
						'api'				=> $row['api'],
						'shop'				=> $row['shop'],
						'address_id'			=> $row['address_id'],
						'reserve_id'			=> $row['reserve_id'],
						'hash'				=> $row['hash'],
						'manual_payment'		=> $row['manual_payment'],
						'cgst'				=> $row['cgst'],
						'sgst'				=> $row['sgst'],
						'igst'				=> $row['igst'],
                       				'product'			=> $products,
                       				'url'				=> $url,
                    );
                    /* $customer_details 	= $this->getCompanyByID($data['customer_id']);
                 $data['customer_details']= $customer_details ;*/
                $response[] = $data;
                return $data;
               // print_r($data['customer_id']);die();

}
}
else
{
     $response= array();
                
}
        }
        return false;
    }
    
    function getview($start,$end){
        if(!empty($id)){
            $this->db->select('u.*,s.*');
            $this->db->from('sales as s');
            $this->db->where('s.id' , $id);
            $this->db->join('sale_items as u', ' u.sale_id = s.id');
           $query = $this->db->get();
        return $query->result();
        }
        else
        {
        $this->db->order_by("id","desc");
          $query = $this->db->get('sales')->result_array();
        
	foreach(array_slice($query, $start,  $end) as  $row)
	{
    		$prouduct = $this->db->get_where('sale_items',array('sale_id'=>$row['id']))->result_array();
    			 $products = array();
               	 foreach($prouduct as $rows){
               	 
               	  $prod = array(
                         			'sale_item_id'			=> $rows['id'],
						'sale_id'			=> $rows['sale_id'],
						'product_id'			=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'				=> $rows['item_tax'],
						'tax_rate'			=> $rows['tax_rate_id'],
				// 		'tax'				=> $rows['tax'],
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=> $rows['net_unit_price'],
						'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
						'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $products[]= $prod;
                          $url = 'http://printsa.cignestrade.com/welcome/'.$rows['sale_id'].'';
                          }
                          $company=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->company;
                          $vat=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->vat_no;
                          $address=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->address;
                          $city=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->city;
                          $state=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->state;
                          $postal_code=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->postal_code;
                          $country=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->country;
                          $phone=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->phone;
                          $email=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->email;
                          $biller = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->name;
        	$data = array(
                        			'id' 				=> $row['id'],
						'date'				=> $row['date'],
						'reference_no'			=> $row['reference_no'],
							'dummy_reference'=>$row['dummy_reference'],
						'customer_id'			=> $row['customer_id'],
						'customer'			=> $row['customer'],
						'company'		=> $company,
						'vat'			=> $vat,
						'address'		=> $address,
						'city'			=> $city,
						'state'			=> $state,
						'postal_code'	=> $postal_code,
						'country'		=> $country,
						'phone'			=> $phone,
						'email'			=> $email,
						'biller_id'			=> $row['biller_id'],
						'biller'			=> $biller,
						'warehouse_id'			=> $row['warehouse_id'],
						'note'				=> $row['note'],
						'staff_note'			=> $row['staff_note'],
						'total'				=> $row['total'],
						'product_discount'		=> $row['product_discount'],
						'order_discount_id'		=> $row['order_discount_id'],
						'total_discount'		=> $row['total_discount'],
						'order_discount'		=> $row['order_discount'],
						'product_tax'			=> $row['product_tax'],
						'order_tax_id'			=> $row['order_tax_id'],
						'order_tax'			=> $row['order_tax'],
						'total_tax'			=> $row['total_tax'],
						'shipping'			=> $row['shipping'],
						'grand_total'			=> $row['grand_total'],
						'sale_status'			=> $row['sale_status'],
						'payment_status'		=> $row['payment_status'],
						'payment_term'			=> $row['payment_term'],
						'due_date'			=> $row['due_date'],
						'created_by'			=> $row['created_by'],
						'updated_by'			=> $row['updated_by'],
						'updated_at'			=> $row['updated_at'],
						'total_items'			=> $row['total_items'],
						'pos'				=> $row['pos'],
						'paid'				=> $row['paid'],
						'return_id'			=> $row['return_id'],
						'delete_id'			=> $row['delete_id'],
						'surcharge'			=> $row['surcharge'],
						'attachment'			=> $row['attachment'],
						'return_sale_ref'		=> $row['return_sale_ref'],
						'sale_id'			=> $row['sale_id'],
						'return_sale_total'		=> $row['return_sale_total'],
						'rounding'			=> $row['rounding'],
						'suspend_note'			=> $row['suspend_note'],
						'api'				=> $row['api'],
						'shop'				=> $row['shop'],
						'address_id'			=> $row['address_id'],
						'reserve_id'			=> $row['reserve_id'],
						'hash'				=> $row['hash'],
						'manual_payment'		=> $row['manual_payment'],
						'cgst'				=> $row['cgst'],
						'sgst'				=> $row['sgst'],
						'igst'				=> $row['igst'],
                       				'product'			=> $products,
                       				'url'				=> $url,
                    );
                    /* $customer_details 	= $this->getCompanyByID($data['customer_id']);
                 $data['customer_details']= $customer_details ;*/
                $response[] = $data;
                
               // print_r($data['customer_id']);die();
}
   }            
              
       
        return  $response;
        
    }
    
       function getviews($start,$end,$biller_id){
        if(!empty($id)){
            $this->db->select('u.*,s.*');
            $this->db->from('sales as s');
            $this->db->where('s.id' , $id);
            $this->db->join('sale_items as u', ' u.sale_id = s.id');
           $query = $this->db->get();
        return $query->result();
        }
        else
        {
        $this->db->order_by("id","desc");
          $query = $this->db->get_where('sales',array('biller_id'=>$biller_id))->result_array();
if(!empty($query)){
	foreach(array_slice($query, $start,  $end) as  $row)
	{
	   
    		$prouduct = $this->db->get_where('sale_items',array('sale_id'=>$row['id']))->result_array();
    		$payment_by =$this->db->get_where('payments',array('sale_id'=>$row['id']))->result_array();
    		
    		if(!empty($payment_by)){
    		   // print_r($payment_by);die();
    		   if(count($payment_by) > 1) {
    		       
    		       $paid_by = $this->db->get_where('payments',array('sale_id'=>$row['id']))->row()->paid_by;
    		   }
    		   else{
    		        $paid_by = $this->db->get_where('payments',array('sale_id'=>$row['id']))->row()->paid_by;
    		        
    		   }
    		}
    			 $products = array();
               	 foreach($prouduct as $rows){
               	    //   $second_name = $this->db->get_where('products',array('id'=> $rows['product_id']))->row()->second_name;
               	//  $tax_method = $this->db->get_where('products',array('id'=> $rows['product_id']))->row()->tax_method;
               	  $prod = array(
                         			'sale_item_id'			=> $rows['id'],
						'sale_id'			=> $rows['sale_id'],
						'product_id'			=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
				// 		'second_name'       =>$second_name,
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'				=> $rows['item_tax'],
						'tax_rate'			=> $rows['tax_rate_id'],
				// 		'tax_method'				=> $tax_method,
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=>$rows['net_unit_price'],
						'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
						'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $products[]= $prod;
                          $url = 'http://printsa.cignestrade.com/welcome/'.$rows['sale_id'].'';
                          }
                          $company=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->company;
                          $vat=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->vat_no;
                          $address=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->address;
                          $city=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->city;
                          $state=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->state;
                          $postal_code=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->postal_code;
                          $country=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->country;
                          $phone=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->phone;
                          $email=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->email;
                           $biller = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->name;
                            $biller_company = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->company;
                            $biller_warehouse_id = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->warehouse_id;
                            $biller_vat = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->vat_no;
                            $biller_address=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->address;
                         $biller_city=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->city;
                         $biller_state=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->state;
                         $biller_postal_code=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->postal_code;
                         $biller_country=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->country;
                         $biller_phone=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->phone;
                          $biller_email=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->email;
                           
                            $biller_company_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf1;
                        $biller_name_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf2;
                        $biller_vat_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf3;
                        $biller_phone_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf4;
                        $biller_address_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf5;
                        $biller_city_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf6;
                        
                        
                         $customer_company_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf1;
                        $customer_name_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf2;
                        $customer_vat_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf3;
                        $customer_phone_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf4;
                        $customer_address_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf5;
                        $customer_city_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf6;
                           
                          // print_r( $row['biller_id']);die();
                           if($row['warehouse_id'] == $biller_warehouse_id){
                            $first_name = $this->db->get_where('users', array('warehouse_id' => $row['warehouse_id']))->row()->first_name;
                             $last_name = $this->db->get_where('users', array('warehouse_id' =>$row['warehouse_id']))->row()->last_name;
                             $sale = $first_name." ".$last_name;
                           }
                           else{
                               $sale ="Admin";
                           }
                             ///print_r($sale);die();
        	$data = array(
                        			'id' 				=> $row['id'],
						'date'				=> $row['date'],
						'sale_associate' =>$sale,
						'reference_no'			=> $row['reference_no'],
						'dummy_reference'=>$row['dummy_reference'],
						'customer_id'			=> $row['customer_id'],
						'customer'			=> $row['customer'],
						'company'		=> $biller_company,
						'vat'			=> $vat,
						'vat_number'    =>$biller_vat,
						'address'		=> $address,
						'city'			=> $city,
						'state'			=> $state,
						'postal_code'	=> $postal_code,
						'country'		=> $country,
						'phone'			=> $phone,
						'email'			=> $email,
						'biller_id'			=> $row['biller_id'],
						'biller'			=> $biller,
						'biller_address'		=> $biller_address,
						'biller_city'			=> $biller_city,
						'biller_state'			=> $biller_state,
						'biller_postal_code'	=> $biller_postal_code,
						'biller_country'		=> $biller_country,
						'biller_phone'			=> $biller_phone,
						'biller_email'			=> $biller_email,
						
							'arabic_customerr_company'		     => !empty($customer_company_arabic)?$customer_company_arabic:'',
						'arabic_customer_address'	 => !empty($customer_address_arabic)?$customer_address_arabic:'',
						'arabic_customer_name'	=> !empty($customer_name_arabic)?$customer_name_arabic:'',
						'arabic_customer_city'	=> !empty($customer_city_arabic)?$customer_city_arabic:'',
						'arabic_customer_phone'	=> !empty($customer_phone_arabic)?$customer_phone_arabic:'',
						'arabic_customer_vat_number'	=> !empty($customer_vat_arabic)?$customer_vat_arabic:'',
						
						'arabic_biller_company'		     => !empty($biller_company_arabic)?$biller_company_arabic:'',
						'arabic_biller_state'	 => !empty($biller_address_arabic)?$biller_address_arabic:'',
						'arabic_biller_address'	=> !empty($biller_name_arabic)?$biller_name_arabic:'',
						'arabic_biller_country'	=> !empty($biller_city_arabic)?$biller_city_arabic:'',
						'arabic_biller_city'	=> !empty($biller_phone_arabic)?$biller_phone_arabic:'',
						'arabic_biller_address_1'	=> !empty($biller_vat_arabic)?$biller_vat_arabic:'',
						
						
						
						
						
						
						
						'paid_by'=>!empty($paid_by)?$paid_by:'',
						'warehouse_id'			=> $row['warehouse_id'],
						'note'				=> $row['note'],
						'staff_note'			=> $row['staff_note'],
						'total'				=> $row['total'],
						'product_discount'		=> $row['product_discount'],
						'order_discount_id'		=> $row['order_discount_id'],
						'total_discount'		=> $row['total_discount'],
						'order_discount'		=> $row['order_discount'],
						'product_tax'			=> $row['product_tax'],
						'order_tax_id'			=> $row['order_tax_id'],
						'order_tax'			=> $row['order_tax'],
						'total_tax'			=> $row['total_tax'],
						'shipping'			=> $row['shipping'],
						'grand_total'			=> $row['grand_total'],
						'sale_status'			=> $row['sale_status'],
						'payment_status'		=> $row['payment_status'],
						'payment_term'			=> $row['payment_term'],
						'due_date'			=> $row['due_date'],
						'created_by'			=> $row['created_by'],
						'updated_by'			=> $row['updated_by'],
						'updated_at'			=> $row['updated_at'],
						'total_items'			=> $row['total_items'],
						'pos'				=> $row['pos'],
						'paid'				=> $row['paid'],
						'return_id'			=> $row['return_id'],
						'delete_id'			=> $row['delete_id'],
						'surcharge'			=> $row['surcharge'],
						'attachment'			=> $row['attachment'],
						'return_sale_ref'		=> $row['return_sale_ref'],
						'sale_id'			=> $row['sale_id'],
						'return_sale_total'		=> $row['return_sale_total'],
						'rounding'			=> $row['rounding'],
						'suspend_note'			=> $row['suspend_note'],
						'api'				=> $row['api'],
						'shop'				=> $row['shop'],
						'address_id'			=> $row['address_id'],
						'reserve_id'			=> $row['reserve_id'],
						'hash'				=> $row['hash'],
						'manual_payment'		=> $row['manual_payment'],
						'cgst'				=> $row['cgst'],
						'sgst'				=> $row['sgst'],
						'igst'				=> $row['igst'],
                       				'product'			=> $products,
                       				'url'				=> $url,
                    );
                    /* $customer_details 	= $this->getCompanyByID($data['customer_id']);
                 $data['customer_details']= $customer_details ;*/
                $response[] = $data;
                
               // print_r($data['customer_id']);die();

}
}
else
{
     $response= array();
                
}
   }            
              
       
        return  $response;
        
    }
    
    
    
       function getCreditView($start,$end){
     $response = array();
        if(!empty($id)){
            $this->db->select('u.*,s.*');
            $this->db->from('sales as s');
            $this->db->where('s.id' , $id);
            
            $this->db->join('sale_items as u', ' u.sale_id = s.id');
           $query = $this->db->get();
        return $query->result();
        }
        else
        {
        $this->db->order_by("id","desc");
          $query = $this->db->get_where('sales',array('payment_status'=>'due','sale_status'=>'completed','return_id'=>null))->result_array();
        
	foreach(array_slice($query, $start,  $end) as  $row)
	{
    		$prouduct = $this->db->get_where('sale_items',array('sale_id'=>$row['id']))->result_array();
    			 $products = array();
               	 foreach($prouduct as $rows){
               	//  $second_name = $this->db->get_where('products',array('id'=> $rows['product_id']))->row()->second_name;
               	  $prod = array(
                         			'sale_item_id'			=> $rows['id'],
						'sale_id'			=> $rows['sale_id'],
						'product_id'			=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
				// 		'second_name'       =>$second_name,
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'				=> $rows['item_tax'],
						'tax_rate'			=> $rows['tax_rate_id'],
				// 		'tax'				=> $rows['tax'],
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=> $rows['real_unit_price'],
						'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
						'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $products[]= $prod;
                          if(!empty($rows['sale_id'])){
                          $url = 'http://printsa.cignestrade.com/welcome/'.$rows['sale_id'].'';
                          }
                          else{
                          $url='';
                          }
                          }
                           $biller = $this->db->get_where('companies', array('id' => $row['biller_id']))->row()->name;
        	$data = array(
                        			'id' 				=> $row['id'],
						'date'				=> $row['date'],
						'reference_no'			=> $row['reference_no'],
						'customer_id'			=> $row['customer_id'],
						'customer'			=> $row['customer'],
						'biller_id'			=> $row['biller_id'],
						'biller'			=>  $biller,
						'warehouse_id'			=> $row['warehouse_id'],
						'note'				=> $row['note'],
						'staff_note'			=> $row['staff_note'],
						'total'				=> $row['total'],
						'product_discount'		=> $row['product_discount'],
						'order_discount_id'		=> $row['order_discount_id'],
						'total_discount'		=> $row['total_discount'],
						'order_discount'		=> $row['order_discount'],
						'product_tax'			=> $row['product_tax'],
						'order_tax_id'			=> $row['order_tax_id'],
						'order_tax'			=> $row['order_tax'],
						'total_tax'			=> $row['total_tax'],
						'shipping'			=> $row['shipping'],
						'grand_total'			=> $row['grand_total'],
						'sale_status'			=> $row['sale_status'],
						'payment_status'		=> $row['payment_status'],
						'payment_term'			=> $row['payment_term'],
						'due_date'			=> $row['due_date'],
						'created_by'			=> $row['created_by'],
						'updated_by'			=> $row['updated_by'],
						'updated_at'			=> $row['updated_at'],
						'total_items'			=> $row['total_items'],
						'pos'				=> $row['pos'],
						'paid'				=> $row['paid'],
						'return_id'			=> $row['return_id'],
						'delete_id'			=> $row['delete_id'],
						'surcharge'			=> $row['surcharge'],
						'attachment'			=> $row['attachment'],
						'return_sale_ref'		=> $row['return_sale_ref'],
						'sale_id'			=> $row['sale_id'],
						'return_sale_total'		=> $row['return_sale_total'],
						'rounding'			=> $row['rounding'],
						'suspend_note'			=> $row['suspend_note'],
						'api'				=> $row['api'],
						'shop'				=> $row['shop'],
						'address_id'			=> $row['address_id'],
						'reserve_id'			=> $row['reserve_id'],
						'hash'				=> $row['hash'],
						'manual_payment'		=> $row['manual_payment'],
						'cgst'				=> $row['cgst'],
						'sgst'				=> $row['sgst'],
						'igst'				=> $row['igst'],
                       				'product'			=> $products,
                       				'url'				=> $url,
                    );
                $response[] = $data;	
}
   }            
              
       
        return  $response;
        
    }
function getCreditViews($start,$end,$biller_id){
     $response = array();
        if(!empty($id)){
            $this->db->select('u.*,s.*');
            $this->db->from('sales as s');
            $this->db->where('s.id' , $id);
            
            $this->db->join('sale_items as u', ' u.sale_id = s.id');
           $query = $this->db->get();
        return $query->result();
        }
        else
        {//die("1");
        $this->db->order_by("id","desc");
          $query = $this->db->get_where('sales',array('biller_id'=>$biller_id,'payment_status'=>'due','sale_status'=>'completed','return_id'=>null))->result_array();
          $biller = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->name;
	foreach(array_slice($query, $start,  $end) as  $row)
	{
    		$prouduct = $this->db->get_where('sale_items',array('sale_id'=>$row['id']))->result_array();
    			$payment_by =$this->db->get_where('payments',array('sale_id'=>$row['id']))->result_array();
    		
    		if(!empty($payment_by)){
    		   // print_r($payment_by);die();
    		   if(count($payment_by) > 1) {
    		       
    		       $paid_by = $this->db->get_where('payments',array('sale_id'=>$row['id']))->row()->paid_by;
    		   }
    		   else{
    		        $paid_by = $this->db->get_where('payments',array('sale_id'=>$row['id']))->row()->paid_by;
    		        
    		   }
    		}
    			 $products = array();
               	 foreach($prouduct as $rows){
               	     	 $second_name = $this->db->get_where('products',array('id'=> $rows['product_id']))->row()->second_name;
               	  $tax_method = $this->db->get_where('products',array('id'=> $rows['product_id']))->row()->tax_method;
               	  $prod = array(
                         			'sale_item_id'			=> $rows['id'],
						'sale_id'			=> $rows['sale_id'],
						'product_id'			=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
						'second_name'       =>$second_name,
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'				=> $rows['item_tax'],
						'tax_rate'			=> $rows['tax_rate_id'],
						'tax_method'				=>$tax_method,
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=> $rows['real_unit_price'],
						'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
						'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $products[]= $prod;
                          if(!empty($rows['sale_id'])){
                          $url = 'http://printsa.cignestrade.com/welcome/'.$rows['sale_id'].'';
                          }
                          else{
                          $url='';
                          }
                          }
                          
                          
                      // print_r( $row['biller_id']);die();
                          
                             
                             $company=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->company;
                          $vat=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->vat_no;
                          $address=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->address;
                          $city=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->city;
                          $state=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->state;
                          $postal_code=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->postal_code;
                          $country=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->country;
                          $phone=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->phone;
                          $email=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->email;
                           $biller = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->name;
                            $biller_company = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->company;
                            $biller_vat = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->vat_no;
                            $biller_address=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->address;
                         $biller_city=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->city;
                         $biller_state=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->state;
                         $biller_postal_code=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->postal_code;
                         $biller_country=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->country;
                         $biller_phone=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->phone;
                          $biller_email=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->email;
                             $biller_company_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf1;
                        $biller_name_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf2;
                        $biller_vat_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf3;
                        $biller_phone_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf4;
                        $biller_address_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf5;
                        $biller_city_arabic=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->cf6;
                        $biller_warehouse_id = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->warehouse_id;
                        
                         $customer_company_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf1;
                        $customer_name_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf2;
                        $customer_vat_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf3;
                        $customer_phone_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf4;
                        $customer_address_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf5;
                        $customer_city_arabic=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->cf6;
                           if($row['warehouse_id'] == $biller_warehouse_id){
                            $first_name = $this->db->get_where('users', array('warehouse_id' => $row['warehouse_id']))->row()->first_name;
                             $last_name = $this->db->get_where('users', array('warehouse_id' =>$row['warehouse_id']))->row()->last_name;
                             $sale = $first_name." ".$last_name;
                           }
                           else{
                               $sale ="Admin";
                           }
                             
                          
        	$data = array(
                        			'id' 				=> $row['id'],
						'date'				=> $row['date'],
						'sale_associate' =>$sale,
						'reference_no'			=> $row['reference_no'],
						'dummy_reference'=>$row['dummy_reference'],
						'customer_id'			=> $row['customer_id'],
						'customer'			=> $row['customer'],
						'company'		=> $biller_company,
						'vat'			=> $vat,
						'vat_number'    =>$biller_vat,
						'address'		=> $address,
						'city'			=> $city,
						'state'			=> $state,
						'postal_code'	=> $postal_code,
						'country'		=> $country,
						'phone'			=> $phone,
						'email'			=> $email,
						'biller_id'			=> $row['biller_id'],
						'biller'			=> $biller,
						'biller_address'		=> $biller_address,
						'biller_city'			=> $biller_city,
						'biller_state'			=> $biller_state,
						'biller_postal_code'	=> $biller_postal_code,
						'biller_country'		=> $biller_country,
						'biller_phone'			=> $biller_phone,
						'biller_email'			=> $biller_email,
						
							'arabic_customerr_company'		     => !empty($customer_company_arabic)?$customer_company_arabic:'',
						'arabic_customer_address'	 => !empty($customer_address_arabic)?$customer_address_arabic:'',
						'arabic_customer_name'	=> !empty($customer_name_arabic)?$customer_name_arabic:'',
						'arabic_customer_city'	=> !empty($customer_city_arabic)?$customer_city_arabic:'',
						'arabic_customer_phone'	=> !empty($customer_phone_arabic)?$customer_phone_arabic:'',
						'arabic_customer_vat_number'	=> !empty($customer_vat_arabic)?$customer_vat_arabic:'',
						
						'arabic_biller_company'		     => !empty($biller_company_arabic)?$biller_company_arabic:'',
						'arabic_biller_state'	 => !empty($biller_address_arabic)?$biller_address_arabic:'',
						'arabic_biller_address'	=> !empty($biller_name_arabic)?$biller_name_arabic:'',
						'arabic_biller_country'	=> !empty($biller_city_arabic)?$biller_city_arabic:'',
						'arabic_biller_city'	=> !empty($biller_phone_arabic)?$biller_phone_arabic:'',
						'arabic_biller_address_1'	=> !empty($biller_vat_arabic)?$biller_vat_arabic:'',
						
						
						'paid_by'=>!empty($paid_by)?$paid_by:'',
						'warehouse_id'			=> $row['warehouse_id'],
						'note'				=> $row['note'],
						'staff_note'			=> $row['staff_note'],
						'total'				=> $row['total'],
						'product_discount'		=> $row['product_discount'],
						'order_discount_id'		=> $row['order_discount_id'],
						'total_discount'		=> $row['total_discount'],
						'order_discount'		=> $row['order_discount'],
						'product_tax'			=> $row['product_tax'],
						'order_tax_id'			=> $row['order_tax_id'],
						'order_tax'			=> $row['order_tax'],
						'total_tax'			=> $row['total_tax'],
						'shipping'			=> $row['shipping'],
						'grand_total'			=> $row['grand_total'],
						'sale_status'			=> $row['sale_status'],
						'payment_status'		=> $row['payment_status'],
						'payment_term'			=> $row['payment_term'],
						'due_date'			=> $row['due_date'],
						'created_by'			=> $row['created_by'],
						'updated_by'			=> $row['updated_by'],
						'updated_at'			=> $row['updated_at'],
						'total_items'			=> $row['total_items'],
						'pos'				=> $row['pos'],
						'paid'				=> $row['paid'],
						'return_id'			=> $row['return_id'],
						'delete_id'			=> $row['delete_id'],
						'surcharge'			=> $row['surcharge'],
						'attachment'			=> $row['attachment'],
						'return_sale_ref'		=> $row['return_sale_ref'],
						'sale_id'			=> $row['sale_id'],
						'return_sale_total'		=> $row['return_sale_total'],
						'rounding'			=> $row['rounding'],
						'suspend_note'			=> $row['suspend_note'],
						'api'				=> $row['api'],
						'shop'				=> $row['shop'],
						'address_id'			=> $row['address_id'],
						'reserve_id'			=> $row['reserve_id'],
						'hash'				=> $row['hash'],
						'manual_payment'		=> $row['manual_payment'],
						'cgst'				=> $row['cgst'],
						'sgst'				=> $row['sgst'],
						'igst'				=> $row['igst'],
                       				'product'			=> $products,
                       				'url'				=> $url,
                    );
                $response[] = $data;	
}
   }            
              
       
        return  $response;
        
    }  
    
    function getsaleview($s_id)
	{
		if(!empty($s_id))
		{
			//$this->db->order_by("id","desc");
			$queryz = $this->db->get_where('sales',array('id'=>$s_id))->result_array();
			  $url = 'http://printsa.cignestrade.com/welcome/'.$s_id.'';
			foreach($queryz as  $rowsr)
			{
				//print_r($row['return_id']);die();
			if($rowsr['return_id'] == NULL)	{ 
			$query = $this->db->get_where('sales',array('id'=>$s_id))->result_array();
			  $url = 'http://printsa.cignestrade.com/welcome/'.$s_id.'';
			foreach($query as  $row)
			{ 
			$prouduct = $this->db->get_where('sale_items',array('sale_id'=>$s_id))->result_array();
				$products = array();
				foreach($prouduct as $rows)//print_r($rows);
				{
				    $second_name = $this->db->get_where('products',array('id'=> $rows['product_id']))->row()->second_name;
					$prod = array(
										'sale_item_id'			=> $rows['id'],
										'sale_id'				=> $rows['sale_id'],
										'product_id'					=> $rows['product_id'],
										'code'					=> $rows['product_code'],
										'name'					=> $rows['product_name'],
										'second_name'       => $second_name,
										'net_unit_price'		=> $rows['net_unit_price'],
										'price'					=> $rows['unit_price'],
										'quantity'				=> $rows['quantity'],
										'warehouse_id'			=> $rows['warehouse_id'],
										'tax'					=> $rows['item_tax'],
										'tax_rate'				=> $rows['tax_rate_id'],
								// 		'tax'					=> $rows['tax'],
										'discount'				=> $rows['discount'],
										'item_discount'			=> $rows['item_discount'],
										'subtotal'				=> $rows['subtotal'],
										'serial_no'				=> $rows['serial_no'],
										'option_id'				=> $rows['option_id'],
										'type'					=> $rows['product_type'],
										'real_unit_price'		=> $rows['real_unit_price'],
										'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
										'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
										'unit_quantity'			=> $rows['unit_quantity'],
										'comment'				=> $rows['comment'],
										'gst'					=> $rows['gst'],
										'cgst'					=> $rows['cgst'],
										'sgst'					=> $rows['sgst'],
										'igst'					=> $rows['igst'],
                          
								);
								$products[]= $prod;
                }
                $company=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->company;
                          $vat=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->vat_no;
                          $address=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->address;
                          $city=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->city;
                          $state=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->state;
                          $postal_code=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->postal_code;
                          $country=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->country;
                          $phone=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->phone;
                          $email=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->email;
                           $biller = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->name;
                            $biller_company = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->company;
                            $biller_vat = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->vat_no;
                            $biller_address=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->address;
                         $biller_city=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->city;
                         $biller_state=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->state;
                         $biller_postal_code=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->postal_code;
                         $biller_country=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->country;
                         $biller_phone=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->phone;
                          $biller_email=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->email;
                           
                            $first_name = $this->db->get_where('users', array('warehouse_id' => $row['warehouse_id']))->row()->first_name;
                             $last_name = $this->db->get_where('users', array('warehouse_id' =>$row['warehouse_id']))->row()->last_name;
                             $sale = $first_name." ".$last_name;
                $data = array(
                        			'id' 					=> $row['id'],
									'date'					=> $row['date'],
										'sale_associate' =>$sale,
									'reference_no'			=> $row['reference_no'],
									'dummy_reference'=>$row['dummy_reference'],
									'customer_id'			=> $row['customer_id'],
									'customer'				=> $row['customer'],
									'biller_id'				=> $row['biller_id'],
									'biller'				=> $biller,
													'vat'			=> $vat,
						'vat_number'    =>$biller_vat,
						'address'		=> $address,
						'city'			=> $city,
						'state'			=> $state,
						'postal_code'	=> $postal_code,
						'country'		=> $country,
						'phone'			=> $phone,
						'email'			=> $email,
						'biller_city'			=> $biller_city,
						'biller_state'			=> $biller_state,
						'biller_postal_code'	=> $biller_postal_code,
						'biller_country'		=> $biller_country,
						'biller_phone'			=> $biller_phone,
						'biller_email'			=> $biller_email,
						'paid_by'=>'cash',
									'warehouse_id'			=> $row['warehouse_id'],
									'note'					=> $row['note'],
									'staff_note'			=> $row['staff_note'],
									'total'					=> $row['total'],
									'product_discount'		=> $row['product_discount'],
									'order_discount_id'		=> $row['order_discount_id'],
									'total_discount'		=> $row['total_discount'],
									'order_discount'		=> $row['order_discount'],
									'product_tax'			=> $row['product_tax'],
									'order_tax_id'			=> $row['order_tax_id'],
									'order_tax'				=> $row['order_tax'],
									'total_tax'				=> $row['total_tax'],
									'shipping'				=> $row['shipping'],
									'grand_total'			=> $row['grand_total'],
									'sale_status'			=> $row['sale_status'],
									'payment_status'		=> $row['payment_status'],
									'payment_term'			=> $row['payment_term'],
									'due_date'				=> $row['due_date'],
									'created_by'			=> $row['created_by'],
									'updated_by'			=> $row['updated_by'],
									'updated_at'			=> $row['updated_at'],
									'total_items'			=> $row['total_items'],
									'pos'					=> $row['pos'],
									'paid'					=> $row['paid'],
									'return_id'				=> $row['return_id'],
									'delete_id'				=> $row['delete_id'],
									'surcharge'				=> $row['surcharge'],
									'attachment'			=> $row['attachment'],
									'return_sale_ref'		=> $row['return_sale_ref'],
									'sale_id'				=> $row['sale_id'],
									'return_sale_total'		=> $row['return_sale_total'],
									'rounding'				=> $row['rounding'],
									'suspend_note'			=> $row['suspend_note'],
									'api'					=> $row['api'],
									'shop'					=> $row['shop'],
									'address_id'			=> $row['address_id'],
									'reserve_id'			=> $row['reserve_id'],
									'hash'					=> $row['hash'],
									'manual_payment'		=> $row['manual_payment'],
									'cgst'					=> $row['cgst'],
									'sgst'					=> $row['sgst'],
									'igst'					=> $row['igst'],
									'product'				=> $products,
									'url' 					=>$url
                    );
               // $response[] = $data;	
               }
			}
			else{
			$query = $this->db->get_where('sales',array('id'=>$rowsr['return_id']))->result_array();
			  $url = 'http://printsa.cignestrade.com/welcome/'.$rowsr['return_id'].'';
			foreach($query as  $row)
			{ 
			$prouduct = $this->db->get_where('sale_items',array('sale_id'=>$rowsr['return_id']))->result_array();
				$products = array();
				foreach($prouduct as $rows)//print_r($rows);
				{
				    $second_name = $this->db->get_where('products',array('id'=> $rows['product_id']))->row()->second_name;
					$prod = array(
										'sale_item_id'			=> $rows['id'],
										'sale_id'				=> $rows['sale_id'],
										'product_id'					=> $rows['product_id'],
										'code'					=> $rows['product_code'],
										'name'					=> $rows['product_name'],
										'second_name'       => $second_name,
										'net_unit_price'		=> $rows['net_unit_price'],
										'price'					=> $rows['unit_price'],
										'quantity'				=> $rows['quantity'],
										'warehouse_id'			=> $rows['warehouse_id'],
										'tax'					=> $rows['item_tax'],
										'tax_rate'				=> $rows['tax_rate_id'],
								// 		'tax'					=> $rows['tax'],
										'discount'				=> $rows['discount'],
										'item_discount'			=> $rows['item_discount'],
										'subtotal'				=> $rows['subtotal'],
										'serial_no'				=> $rows['serial_no'],
										'option_id'				=> $rows['option_id'],
										'type'					=> $rows['product_type'],
										'real_unit_price'		=> $rows['real_unit_price'],
										'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
										'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
										'unit_quantity'			=> $rows['unit_quantity'],
										'comment'				=> $rows['comment'],
										'gst'					=> $rows['gst'],
										'cgst'					=> $rows['cgst'],
										'sgst'					=> $rows['sgst'],
										'igst'					=> $rows['igst'],
                          
								);
								$products[]= $prod;
                }
                 $company=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->company;
                          $vat=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->vat_no;
                          $address=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->address;
                          $city=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->city;
                          $state=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->state;
                          $postal_code=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->postal_code;
                          $country=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->country;
                          $phone=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->phone;
                          $email=$this->db->get_where('companies', array('id' =>  $row['customer_id']))->row()->email;
                           $biller = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->name;
                            $biller_company = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->company;
                            $biller_vat = $this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->vat_no;
                            $biller_address=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->address;
                         $biller_city=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->city;
                         $biller_state=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->state;
                         $biller_postal_code=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->postal_code;
                         $biller_country=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->country;
                         $biller_phone=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->phone;
                          $biller_email=$this->db->get_where('companies', array('id' =>  $row['biller_id']))->row()->email;
                           
                            $first_name = $this->db->get_where('users', array('warehouse_id' => $row['warehouse_id']))->row()->first_name;
                             $last_name = $this->db->get_where('users', array('warehouse_id' =>$row['warehouse_id']))->row()->last_name;
                             $sale = $first_name." ".$last_name;
                $data = array(
                        			'id' 					=> $row['id'],
									'date'					=> $row['date'],
										'sale_associate' =>$sale,
									'reference_no'			=> $row['reference_no'],
									'dummy_reference'=>$row['dummy_reference'],
									'customer_id'			=> $row['customer_id'],
									'customer'				=> $row['customer'],
									'biller_id'				=> $row['biller_id'],
									'biller'				=> $biller,
									'vat'			=> $vat,
						'vat_number'    =>$biller_vat,
						'address'		=> $address,
						'city'			=> $city,
						'state'			=> $state,
						'postal_code'	=> $postal_code,
						'country'		=> $country,
						'phone'			=> $phone,
						'email'			=> $email,
						'biller_city'			=> $biller_city,
						'biller_state'			=> $biller_state,
						'biller_postal_code'	=> $biller_postal_code,
						'biller_country'		=> $biller_country,
						'biller_phone'			=> $biller_phone,
						'biller_email'			=> $biller_email,
						'paid_by'=>'cash',
									'warehouse_id'			=> $row['warehouse_id'],
									'note'					=> $row['note'],
									'staff_note'			=> $row['staff_note'],
									'total'					=> $row['total'],
									'product_discount'		=> $row['product_discount'],
									'order_discount_id'		=> $row['order_discount_id'],
									'total_discount'		=> $row['total_discount'],
									'order_discount'		=> $row['order_discount'],
									'product_tax'			=> $row['product_tax'],
									'order_tax_id'			=> $row['order_tax_id'],
									'order_tax'				=> $row['order_tax'],
									'total_tax'				=> $row['total_tax'],
									'shipping'				=> $row['shipping'],
									'grand_total'			=> $row['grand_total'],
									'sale_status'			=> $row['sale_status'],
									'payment_status'		=> $row['payment_status'],
									'payment_term'			=> $row['payment_term'],
									'due_date'				=> $row['due_date'],
									'created_by'			=> $row['created_by'],
									'updated_by'			=> $row['updated_by'],
									'updated_at'			=> $row['updated_at'],
									'total_items'			=> $row['total_items'],
									'pos'					=> $row['pos'],
									'paid'					=> $row['paid'],
									'return_id'				=> $row['return_id'],
									'delete_id'				=> $row['delete_id'],
									'surcharge'				=> $row['surcharge'],
									'attachment'			=> $row['attachment'],
									'return_sale_ref'		=> $row['return_sale_ref'],
									'sale_id'				=> $row['sale_id'],
									'return_sale_total'		=> $row['return_sale_total'],
									'rounding'				=> $row['rounding'],
									'suspend_note'			=> $row['suspend_note'],
									'api'					=> $row['api'],
									'shop'					=> $row['shop'],
									'address_id'			=> $row['address_id'],
									'reserve_id'			=> $row['reserve_id'],
									'hash'					=> $row['hash'],
									'manual_payment'		=> $row['manual_payment'],
									'cgst'					=> $row['cgst'],
									'sgst'					=> $row['sgst'],
									'igst'					=> $row['igst'],
									'product'				=> $products,
									'url' 					=>$url
                    );
			}
			}
		}   
		}    
        return  $data;
        
    }
    function getunits($id = ""){
        if(!empty($id)){
            $query = $this->db->get_where('units', array('id' => $id));
            return $query->row_array();
        }else{
            $query = $this->db->get('units');
            return $query->result_array();
        }
    }
    function gettaxrates($id = ""){
        if(!empty($id)){
            $query = $this->db->get_where('tax_rates', array('id' => $id));
            return $query->row_array();
        }else{
            $query = $this->db->get('tax_rates');
            return $query->result_array();
        }
    }
    function getwarehouse($id = ""){
        if(!empty($id)){
            $query = $this->db->get_where('warehouses', array('id' => $id));
            return $query->row_array();
        }else{
            $query = $this->db->get('warehouses');
            return $query->result_array();
        }
    }
 
   
      /*
     * Get rows from the users table
     */
    function getloginRows($email,$pass){//Print_r($pass);die();
       if(!empty($email) && !empty($pass)){
         $query = $this->db->get_where('users', array('username' => $email,'password'=>$pass));//print_r( $query->row_array());die();
           return $query->row_array();
        }else{
            return false;
        }
    }
     public function getReference($field) {
        $q = $this->db->get_where('order_ref', array('ref_id' => '1'), 1);
        if ($q->num_rows() > 0) {
            $ref = $q->row();
            switch ($field) {
                case 'so':
                    $prefix = $this->Settings->sales_prefix;
                    break;
                case 'pos':
                    $prefix = isset($this->Settings->sales_prefix) ? $this->Settings->sales_prefix : '';
                    break;
                case 'qu':
                    $prefix = $this->Settings->quote_prefix;
                    break;
                case 'po':
                    $prefix = $this->Settings->purchase_prefix;
                    break;
                case 'to':
                    $prefix = $this->Settings->transfer_prefix;
                    break;
                case 'do':
                    $prefix = $this->Settings->delivery_prefix;
                    break;
                case 'pay':
                    $prefix = $this->Settings->payment_prefix;
                    break;
                case 'ppay':
                    $prefix = $this->Settings->ppayment_prefix;
                    break;
                case 'ex':
                    $prefix = $this->Settings->expense_prefix;
                    break;
                case 're':
                    $prefix = $this->Settings->return_prefix;
                    break;
                case 'rep':
                    $prefix = $this->Settings->returnp_prefix;
                    break;
                case 'qa':
                    $prefix = $this->Settings->returnp_prefix;
                    break;
                default:
                    $prefix = '';
            }

            // $ref_no = (!empty($prefix)) ? $prefix . '/' : '';
            $ref_no = $prefix;

            if ($this->Settings->reference_format == 1) {
                $ref_no .= date('Y') . "/" . sprintf("%04s", $ref->{$field});
            } elseif ($this->Settings->reference_format == 2) {
                $ref_no .= date('Y') . "/" . date('m') . "/" . sprintf("%04s", $ref->{$field});
            } elseif ($this->Settings->reference_format == 3) {
                $ref_no .= sprintf("%04s", $ref->{$field});
            } else {
                $ref_no .= $this->getRandomReference();
            }

            return $ref_no;
        }
        return FALSE;
    }
    public function updateReference($field) { 
        $q = $this->db->get_where('order_ref', array('ref_id' => '1'), 1);
        if ($q->num_rows() > 0) {
            $ref = $q->row();
            $this->db->update('order_ref', array($field => $ref->{$field} + 1), array('ref_id' => '1'));
            return TRUE;
        }
        return FALSE;
    }
 public function getProductByID($id) {
        $q = $this->db->get_where('products', array('id' => $id), 1);//print_r($q->result());die();
        if ($q->num_rows() > 0) { 
            return $q->row();
        }
        return FALSE;
    } 
    public function UpdateSaleDailyOffline($daily_product= array()) {
       //$this->sma->print_arrays($daily_product);
        foreach ($daily_product as $daily)
        {//echo"1";die();
            $warehouse  = $daily['warehouse_id'];
            $product    = $daily['product_id'];
            $date       = $daily['compare_date'];
            $quantity   = $daily['sale_quantity'];
            
            $this->db->select('*'); 
            $this->db->from('daily_stock');
            $this->db->where('compare_date', $date);
            $this->db->where('product_id', $product);
            $this->db->where('warehouse_id', $warehouse);
            $query = $this->db->get();
            if ($query->num_rows() > 0)
            {
                $sale_quantity = $this->db->get_where('daily_stock',array('product_id'=>$product,'warehouse_id'=>$warehouse,'compare_date'=>$date))->row()->sale_quantity;
                $current_stock = $this->db->get_where('daily_stock',array('product_id'=>$product,'warehouse_id'=>$warehouse,'compare_date'=>$date))->row()->current_stock;

                $sal_qty = $sale_quantity + $quantity;
                $cur_qty = $current_stock - $sal_qty;
                    $this->db->where('warehouse_id', $warehouse);
                    $this->db->where('product_id', $product);
                    $this->db->where('compare_date', $date);
                    $this->db->update('daily_stock',array(
                                             'sale_quantity	'  => $sal_qty,
                                            'current_stock'=>$cur_qty
                                            
                                     ));
                   return TRUE;
            }
            return FALSE;
        }
    }
   
    
    public function addSaleDailyOffline($daily_product= array()) {
        foreach ($daily_product as $daily) {
            $this->db->insert('daily_stock', $daily);
       }
       return false;
    }
    public function addProductDailyOffline($prdocts= array()) {
        
        foreach ($prdocts as $prdcts) {
            $this->db->select('*'); 
            $this->db->from('daily_stock');
            $this->db->where('compare_date', $prdcts['compare_date']);
            $this->db->where('product_id', $prdcts['product_id']);
            $this->db->where('warehouse_id', $prdcts['warehouse_id']);
            $query = $this->db->get();
            if ($query->num_rows() == 0) {
         $this->db->insert('daily_stock', $prdcts);
     } 
    }
     return false;
    }
  public function addSaleOffline($data = array(), $items = array(), $payments = array(), $sid = NULL,$daily_product= array())
      {//print_r($daily_product);die();
      
    // $this->sma->print_arrays($items);
       
        $cost = $this->costing($items);
   //$this->sma->print_arrays($payments);

        if ($this->db->insert('sales', $data)) {
            $sale_id = $this->db->insert_id();
              $this->UpdateSaleDailyOffline($daily_product);
            foreach ($items as $item) {

                $item['sale_id'] = $sale_id;
                $this->db->insert('sale_items', $item);//$this->getProductByID($item['product_id']);
                $sale_item_id = $this->db->insert_id();//print_r($sale_item_id);die();
                if ($data['sale_status'] == 'completed' && $this->getProductByID($item['product_id'])) {

                    $item_costs = $this->item_costing($item);
                    foreach ($item_costs as $item_cost) {
                        if (isset($item_cost['date']) || isset($item_cost['pi_overselling'])) {
                            $item_cost['sale_item_id'] = $sale_item_id;
                            $item_cost['sale_id'] = $sale_id;
                            $item_cost['date'] = date('Y-m-d', strtotime($data['date']));
                            if(! isset($item_cost['pi_overselling'])) {
                                $this->db->insert('costing', $item_cost);
                            }
                        } else {
                            foreach ($item_cost as $ic) {
                                $ic['sale_item_id'] = $sale_item_id;
                                $ic['sale_id'] = $sale_id;
                                $ic['date'] = date('Y-m-d', strtotime($data['date']));
                                if(! isset($ic['pi_overselling'])) {
                                    $this->db->insert('costing', $ic);
                                }
                            }
                        }
                    }
                }
            }

            if ($data['sale_status'] == 'completed') {
                $this->syncPurchaseItems($cost);
            }

            $msg = array();
            if (!empty($payments)) { 
                $paid = 0;
                foreach ($payments as $payment) {
                    if (!empty($payment) && isset($payment['amount'])) {//echo"1";die();
                        $payment['sale_id'] = $sale_id;
                        $payment['reference_no'] = $this->getReference('pay');
                        if ($payment['paid_by'] == 'ppp') {
                            $card_info = array("number" => $payment['cc_no'], "exp_month" => $payment['cc_month'], "exp_year" => $payment['cc_year'], "cvc" => $payment['cc_cvv2'], 'type' => $payment['cc_type']);
                            $result = $this->paypal($payment['amount'], $card_info);
                            if (!isset($result['error'])) {
                                $payment['transaction_id'] = $result['transaction_id'];
                                $payment['date'] = $this->fld($result['created_at']);
                                $payment['amount'] = $result['amount'];
                                $payment['currency'] = $result['currency'];
                                unset($payment['cc_cvv2']);
                                $this->db->insert('payments', $payment);
                                $this->updateReference('pay');
                                $paid += $payment['amount'];
                            } else {
                                $msg[] = lang('payment_failed');
                                if (!empty($result['message'])) {
                                    foreach ($result['message'] as $m) {
                                        $msg[] = '<p class="text-danger">' . $m['L_ERRORCODE'] . ': ' . $m['L_LONGMESSAGE'] . '</p>';
                                    }
                                } else {
                                    $msg[] = lang('paypal_empty_error');
                                }
                            }
                        } elseif ($payment['paid_by'] == 'stripe') {
                            $card_info = array("number" => $payment['cc_no'], "exp_month" => $payment['cc_month'], "exp_year" => $payment['cc_year'], "cvc" => $payment['cc_cvv2'], 'type' => $payment['cc_type']);
                            $result = $this->stripe($payment['amount'], $card_info);
                            if (!isset($result['error'])) {
                                $payment['transaction_id'] = $result['transaction_id'];
                                $payment['date'] = $this->fld($result['created_at']);
                                $payment['amount'] = $result['amount'];
                                $payment['currency'] = $result['currency'];
                                unset($payment['cc_cvv2']);
                                $this->db->insert('payments', $payment);
                                $this->updateReference('pay');
                                $paid += $payment['amount'];
                            } else {
                                $msg[] = lang('payment_failed');
                                $msg[] = '<p class="text-danger">' . $result['code'] . ': ' . $result['message'] . '</p>';
                            }
                        } elseif ($payment['paid_by'] == 'authorize') {
                            $authorize_arr = array("x_card_num" => $payment['cc_no'], "x_exp_date" => ($payment['cc_month'].'/'.$payment['cc_year']), "x_card_code" => $payment['cc_cvv2'], 'x_amount' => $payment['amount'], 'x_invoice_num' => $sale_id, 'x_description' => 'Sale Ref '.$data['reference_no'].' and Payment Ref '.$payment['reference_no']);
                            list($first_name, $last_name) = explode(' ', $payment['cc_holder'], 2);
                            $authorize_arr['x_first_name'] = $first_name;
                            $authorize_arr['x_last_name'] = $last_name;
                            $result = $this->authorize($authorize_arr);
                            if (!isset($result['error'])) {
                                $payment['transaction_id'] = $result['transaction_id'];
                                $payment['approval_code'] = $result['approval_code'];
                                $payment['date'] = $this->fld($result['created_at']);
                                unset($payment['cc_cvv2']);
                                $this->db->insert('payments', $payment);
                                $this->updateReference('pay');
                                $paid += $payment['amount'];
                            } else {
                                $msg[] = lang('payment_failed');
                                $msg[] = '<p class="text-danger">' . $result['msg'] . '</p>';
                            }
                        } else {
                            if ($payment['paid_by'] == 'gift_card') {
                                $this->db->update('gift_cards', array('balance' => $payment['gc_balance']), array('card_no' => $payment['cc_no']));
                                unset($payment['gc_balance']);
                            } elseif ($payment['paid_by'] == 'deposit') {
                                $customer = $this->getCompanyByID($data['customer_id']);
                                $this->db->update('companies', array('deposit_amount' => ($customer->deposit_amount-$payment['amount'])), array('id' => $customer->id));
                            }
                            unset($payment['cc_cvv2']);
                            $this->db->insert('payments', $payment);
                            $payments_id = $this->db->insert_id();
                            $this->updateReference('pay');
                            $paid += $payment['amount'];
                        }
                    }//echo"2";die();
                     $payments_id = $this->db->insert_id() ? $this->db->insert_id() :0;
                    			$date 	= $payment['date'];
					$amount = $payment['amount'];
					$datads = array(
							'type' 			=> 'income',
							'date' 			=> $date,
							'Account' 		=> '5',
							'category' 		=> '8',
							'amount' 		=> $amount,
							'note' 			=> '',
							 'acc_type' 		=> '18',
							'description' 		=> 'Sale',
							'deposit_withdrawal' 	=> 'deposit',
							'payment_id'		=>  $payments_id
							);
					$this->addTransaction($datads,$sale_id);
					 //$this->updateReference('pay');
                }
                $this->syncSalePayments($sale_id);
            }

            $this->syncQuantity($sale_id);
           if ($sid) {
                $this->deleteBill($sid);
            }
            $this->sma->update_award_points($data['grand_total'], $data['customer_id'], $data['created_by']);
            $this->updateReference('so');
            $valu = $this->getSaleDetailsView($sale_id);
            return $valu;
        }

        return false;
    }
    public function addSale($data = array(), $items = array(), $payments = array(), $sid = NULL,$daily_product=array())
    {//print_r($sid);die();
     
     $this->db->insert('daily_stock', $daily_product);
        $cost = $this->costing($items);
   // $this->sma->print_arrays($data);

        if ($this->db->insert('sales', $data)) {
            $sale_id = $this->db->insert_id();

            foreach ($items as $item) {

                $item['sale_id'] = $sale_id;
                $this->db->insert('sale_items', $item);//$this->getProductByID($item['product_id']);
                $sale_item_id = $this->db->insert_id();//print_r($sale_item_id);die();
                if ($data['sale_status'] == 'Completed' && $this->getProductByID($item['product_id'])) {

                    $item_costs = $this->item_costing($item);
                    foreach ($item_costs as $item_cost) {
                        if (isset($item_cost['date']) || isset($item_cost['pi_overselling'])) {
                            $item_cost['sale_item_id'] = $sale_item_id;
                            $item_cost['sale_id'] = $sale_id;
                            $item_cost['date'] = date('Y-m-d', strtotime($data['date']));
                            if(! isset($item_cost['pi_overselling'])) {
                                $this->db->insert('costing', $item_cost);
                            }
                        } else {
                            foreach ($item_cost as $ic) {
                                $ic['sale_item_id'] = $sale_item_id;
                                $ic['sale_id'] = $sale_id;
                                $ic['date'] = date('Y-m-d', strtotime($data['date']));
                                if(! isset($ic['pi_overselling'])) {
                                    $this->db->insert('costing', $ic);
                                }
                            }
                        }
                    }
                }
            }

            if ($data['sale_status'] == 'Completed') {
                $this->syncPurchaseItems($cost);
            }

            $msg = array();
            if (!empty($payments)) { 
                $paid = 0;
                foreach ($payments as $payment) {
                    if (!empty($payment) && isset($payment['amount']) && $payment['amount'] != 0) {
                        $payment['sale_id'] = $sale_id;
                        $payment['reference_no'] = $this->getReference('pay');
                        if ($payment['paid_by'] == 'ppp') {
                            $card_info = array("number" => $payment['cc_no'], "exp_month" => $payment['cc_month'], "exp_year" => $payment['cc_year'], "cvc" => $payment['cc_cvv2'], 'type' => $payment['cc_type']);
                            $result = $this->paypal($payment['amount'], $card_info);
                            if (!isset($result['error'])) {
                                $payment['transaction_id'] = $result['transaction_id'];
                                $payment['date'] = $this->fld($result['created_at']);
                                $payment['amount'] = $result['amount'];
                                $payment['currency'] = $result['currency'];
                                unset($payment['cc_cvv2']);
                                $this->db->insert('payments', $payment);
                                $this->updateReference('pay');
                                $paid += $payment['amount'];
                            } else {
                                $msg[] = lang('payment_failed');
                                if (!empty($result['message'])) {
                                    foreach ($result['message'] as $m) {
                                        $msg[] = '<p class="text-danger">' . $m['L_ERRORCODE'] . ': ' . $m['L_LONGMESSAGE'] . '</p>';
                                    }
                                } else {
                                    $msg[] = lang('paypal_empty_error');
                                }
                            }
                        } elseif ($payment['paid_by'] == 'stripe') {
                            $card_info = array("number" => $payment['cc_no'], "exp_month" => $payment['cc_month'], "exp_year" => $payment['cc_year'], "cvc" => $payment['cc_cvv2'], 'type' => $payment['cc_type']);
                            $result = $this->stripe($payment['amount'], $card_info);
                            if (!isset($result['error'])) {
                                $payment['transaction_id'] = $result['transaction_id'];
                                $payment['date'] = $this->fld($result['created_at']);
                                $payment['amount'] = $result['amount'];
                                $payment['currency'] = $result['currency'];
                                unset($payment['cc_cvv2']);
                                $this->db->insert('payments', $payment);
                                $this->updateReference('pay');
                                $paid += $payment['amount'];
                            } else {
                                $msg[] = lang('payment_failed');
                                $msg[] = '<p class="text-danger">' . $result['code'] . ': ' . $result['message'] . '</p>';
                            }
                        } elseif ($payment['paid_by'] == 'authorize') {
                            $authorize_arr = array("x_card_num" => $payment['cc_no'], "x_exp_date" => ($payment['cc_month'].'/'.$payment['cc_year']), "x_card_code" => $payment['cc_cvv2'], 'x_amount' => $payment['amount'], 'x_invoice_num' => $sale_id, 'x_description' => 'Sale Ref '.$data['reference_no'].' and Payment Ref '.$payment['reference_no']);
                            list($first_name, $last_name) = explode(' ', $payment['cc_holder'], 2);
                            $authorize_arr['x_first_name'] = $first_name;
                            $authorize_arr['x_last_name'] = $last_name;
                            $result = $this->authorize($authorize_arr);
                            if (!isset($result['error'])) {
                                $payment['transaction_id'] = $result['transaction_id'];
                                $payment['approval_code'] = $result['approval_code'];
                                $payment['date'] = $this->fld($result['created_at']);
                                unset($payment['cc_cvv2']);
                                $this->db->insert('payments', $payment);
                                $this->updateReference('pay');
                                $paid += $payment['amount'];
                            } else {
                                $msg[] = lang('payment_failed');
                                $msg[] = '<p class="text-danger">' . $result['msg'] . '</p>';
                            }
                        } else {
                            if ($payment['paid_by'] == 'gift_card') {
                                $this->db->update('gift_cards', array('balance' => $payment['gc_balance']), array('card_no' => $payment['cc_no']));
                                unset($payment['gc_balance']);
                            } elseif ($payment['paid_by'] == 'deposit') {
                                $customer = $this->getCompanyByID($data['customer_id']);
                                $this->db->update('companies', array('deposit_amount' => ($customer->deposit_amount-$payment['amount'])), array('id' => $customer->id));
                            }
                            unset($payment['cc_cvv2']);
                            $this->db->insert('payments', $payment);
                            $payments_id = $this->db->insert_id();
                            $this->updateReference('pay');
                            $paid += $payment['amount'];
                        }
                    }
                     $payments_id = $this->db->insert_id() ? $this->db->insert_id() :0;
                    			$date 	= $payment['date'];
					$amount = $payment['amount'];
					$datads = array(
							'type' 			=> 'income',
							'date' 			=> $date,
							'Account' 		=> '5',
							'category' 		=> '8',
							'amount' 		=> $amount,
							'note' 			=> '',
							 'acc_type' 		=> '18',
							'description' 		=> 'Sale',
							'deposit_withdrawal' 	=> 'deposit',
							'payment_id'		=>  $payments_id
							);
					$this->addTransaction($datads,$sale_id);
                }
                $this->syncSalePayments($sale_id);
            }

            $this->syncQuantity($sale_id);
           if ($sid) {
                $this->deleteBill($sid);
            }
            $this->sma->update_award_points($data['grand_total'], $data['customer_id'], $data['created_by']);
            $this->updateReference('pos');
            return $sale_id;
        }

        return false;
    }
    public function addTransaction($data,$sale)
    { 
		
		$data['sale_id'] = $sale;
		if ($this->db->insert('transaction', $data))
		{
			$transaction_id = $this->db->insert_id();
			return true;
        }
        return FALSE;
    }
  public function addSales($data = array(), $items = array(), $payment = array(), $si_return = array())
    {

        if (empty($si_return)) {
            $cost = $this->costing($items);
  
        }

        if ($this->db->insert('sales', $data)) {
            $sale_id = $this->db->insert_id();
            if ($this->getReference('so') == $data['reference_no']) {
                $this->updateReference('so');
                 $this->updateReference('re');
            }
            foreach ($items as $item) {

                $item['sale_id'] = $sale_id;
                $this->db->insert('sale_items', $item);
                $sale_item_id = $this->db->insert_id();
                if ($data['sale_status'] == 'Completed' && empty($si_return)) {

                    $item_costs = $this->item_costing($item);
                    foreach ($item_costs as $item_cost) {
                        if (isset($item_cost['date']) || isset($item_cost['pi_overselling'])) {
                            $item_cost['sale_item_id'] = $sale_item_id;
                            $item_cost['sale_id'] = $sale_id;
                            $item_cost['date'] = date('Y-m-d', strtotime($data['date']));
                            if(! isset($item_cost['pi_overselling'])) {
                                $this->db->insert('costing', $item_cost);
                            }
                        } else {
                            foreach ($item_cost as $ic) {
                                $ic['sale_item_id'] = $sale_item_id;
                                $ic['sale_id'] = $sale_id;
                                $ic['date'] = date('Y-m-d', strtotime($data['date']));
                                if(! isset($ic['pi_overselling'])) {
                                    $this->db->insert('costing', $ic);
                                }
                            }
                        }
                    }

                }
            }

            if ($data['sale_status'] == 'Completed') {
                $this->syncPurchaseItems($cost);
            }

            if (!empty($si_return)) {
                foreach ($si_return as $return_item) {
                    $product = $this->getProductByID($return_item['product_id']);
                    if ($product->type == 'combo') {
                        $combo_items = $this->getProductComboItems($return_item['product_id'], $return_item['warehouse_id']);
                        foreach ($combo_items as $combo_item) {
                            $this->UpdateCostingAndPurchaseItem($return_item['id'], $combo_item->id, ($return_item['quantity']*$combo_item->qty));
                        }
                    } else {
                        $this->UpdateCostingAndPurchaseItem($return_item['id'], $return_item['product_id'], $return_item['quantity']);
                    }
                }
                $this->db->update('sales', array('return_sale_ref' => $data['return_sale_ref'], 'surcharge' => $data['surcharge'],'return_sale_total' => $data['grand_total'], 'return_id' => $sale_id), array('id' => $data['sale_id']));
            }

            if ($data['payment_status'] == 'partial' || $data['payment_status'] == 'paid' && !empty($payment)) {
                if (empty($payment['reference_no'])) {
                    $payment['reference_no'] = $this->getReference('pay');
                }
                $payment['sale_id'] = $sale_id;
                if ($payment['paid_by'] == 'gift_card') {
                    $this->db->update('gift_cards', array('balance' => $payment['gc_balance']), array('card_no' => $payment['cc_no']));
                    unset($payment['gc_balance']);
                    $this->db->insert('payments', $payment);
                } else {
                    if ($payment['paid_by'] == 'deposit') {
                        $customer = $this->getCompanyByID($data['customer_id']);
                        $this->db->update('companies', array('deposit_amount' => ($customer->deposit_amount-$payment['amount'])), array('id' => $customer->id));
                    }
                    
                    $this->db->insert('payments', $payment);
                    $payments_id= $this->db->insert_id();
                    $datads = array(
							'type' 			=> 'income',
							'date' 			=> $payment['date'],
							'Account' 		=> '5',
							'category' 		=> '8',
							'amount' 		=> $payment['amount'],
							'note' 			=> '',
							 'acc_type' 		=> '18',
							'description' 		=> 'Sale',
							'deposit_withdrawal' 	=> 'deposit',
							'payment_id'		=>  $payments_id
							);
					$this->addTransaction($datads,$payment['sale_id']);
                }
                if ($this->getReference('pay') == $payment['reference_no']) {
                    $this->updateReference('pay');
                }
                $this->syncSalePayments($sale_id);
            }

            $this->syncQuantity($sale_id);
            $this->update_award_points($data['grand_total'], $data['customer_id'], $data['created_by']);
            return $sale_id;
        }

        return false;
    }
    public function getCostingLines($sale_item_id, $product_id, $sale_id = NULL)
    {
        if ($sale_id) { $this->db->where('sale_id', $sale_id); }
        $orderby = ($this->Settings->accounting_method == 1) ? 'asc' : 'desc';
        $this->db->order_by('id', $orderby);
        $q = $this->db->get_where('costing', array('sale_item_id' => $sale_item_id, 'product_id' => $product_id));
        if ($q->num_rows() > 0) {
            foreach (($q->result()) as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return FALSE;
    }

    public function UpdateCostingAndPurchaseItem($item_id, $product_id, $quantity)
    {//print_r($this->getCostingLines($item_id, $product_id));die();
        $bln_quantity = $quantity;//print_r($quantity);die();
        if ($costings = $this->getCostingLines($item_id, $product_id)) {//echo"a";die();
            foreach ($costings as $costing) {//echo"b";die();

                if ($quantity != 0) {//echo"c";die();
                    $pi = $this->getPurchaseItemByID($costing->purchase_item_id);
                    if ($pi->quantity_received >= $quantity) {//echo"d";die();
                        $this->setPurchaseItem(['id' => $pi->id, 'product_id' => $pi->product_id, 'option_id' => $pi->option_id], $quantity);
                        $quantity = 0;
                    } else {//echo"e";die();
                        $this->setPurchaseItem(['id' => $pi->id, 'product_id' => $pi->product_id, 'option_id' => $pi->option_id], $pi->quantity_received);
                        $quantity = ($quantity-$pi->quantity_received);
                    }
                }
//echo"f";die();
                if ($costing->quantity > $bln_quantity && $bln_quantity != 0) {
                    $qty = $costing->quantity - $bln_quantity;
                    $bln = $costing->quantity_balance && $costing->quantity_balance >= $bln_quantity ? $costing->quantity_balance - $bln_quantity : 0;
                    $this->db->update('costing', array('quantity' => $qty, 'quantity_balance' => $bln), array('id' => $costing->id));
                    $bln_quantity = 0;
                } elseif ($costing->quantity <= $bln_quantity && $bln_quantity != 0) {
                    $this->db->delete('costing', array('id' => $costing->id));
                    $bln_quantity = ($bln_quantity - $costing->quantity);
                }

                if ($quantity == 0 && $bln_quantity == 0) { break; }
            }
        }

    }
    public function deleteBill($id)
    {

        if ($this->db->delete('suspended_items', array('suspend_id' => $id)) && $this->db->delete('suspended_bills', array('id' => $id))) {
            return true;
        }

        return FALSE;
    }
     public function getSaleByID($id) {
        $q = $this->db->get_where('sales', array('id' => $id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
     public function getSalePayments($sale_id) {
        $q = $this->db->get_where('payments', array('sale_id' => $sale_id));
        if ($q->num_rows() > 0) {
            foreach (($q->result()) as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return FALSE;
    }

     public function syncSalePayments($id) { 
        $sale =  $this->getSaleByID($id);
        if ($payments = $this->getSalePayments($id)) {
            $paid = 0;
            $grand_total = $sale->grand_total+$sale->rounding;
            foreach ($payments as $payment) {
                $paid += $payment->amount;
            }

            $payment_status = $paid == 0 ? 'Pending' : $sale->payment_status;
            if ($this->sma->formatDecimal($grand_total) == $this->formatDecimal($paid)) {
                $payment_status = 'paid';
            } elseif ($sale->due_date <= date('Y-m-d') && !$sale->sale_id) {
                $payment_status = 'due';
            } elseif ($paid != 0) {
                $payment_status = 'partial';
            }

            if ($this->db->update('sales', array('paid' => $paid, 'payment_status' => $payment_status), array('id' => $id))) {
                return true;
     
			}
		}
	}
     public function getAllSaleItems($sale_id) {
        $q = $this->db->get_where('sale_items', array('sale_id' => $sale_id));
        if ($q->num_rows() > 0) {
            foreach (($q->result()) as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return FALSE;
    }
     public function syncVariantQty($variant_id, $warehouse_id, $product_id = NULL) {
        $balance_qty = $this->getBalanceVariantQuantity($variant_id);
        $wh_balance_qty = $this->getBalanceVariantQuantity($variant_id, $warehouse_id);
        if ($this->db->update('product_variants', array('quantity' => $balance_qty), array('id' => $variant_id))) {
            if ($this->getWarehouseProductsVariants($variant_id, $warehouse_id)) {
                $this->db->update('warehouses_products_variants', array('quantity' => $wh_balance_qty), array('option_id' => $variant_id, 'warehouse_id' => $warehouse_id));
            } else {
                if($wh_balance_qty) {
                    $this->db->insert('warehouses_products_variants', array('quantity' => $wh_balance_qty, 'option_id' => $variant_id, 'warehouse_id' => $warehouse_id, 'product_id' => $product_id));
                }
            }
            return TRUE;
        }
        return FALSE;
    }
	 public function getBalanceQuantity($product_id, $warehouse_id= NULL) {//print_r($warehouse_id );die("fghfg");
        $this->db->select('SUM(COALESCE(quantity_balance, 0)) as stock', FALSE);
        $this->db->where('product_id', $product_id)->where('quantity_balance !=', 0);
        if ($warehouse_id) {
            $this->db->where('warehouse_id', $warehouse_id);
        }
        $this->db->group_start()->where('status', 'received')->or_where('status', 'partial')->group_end();
        $q = $this->db->get('purchase_items');//print_r($q->result_array());die();
        if ($q->num_rows() > 0) {
            $data = $q->row();
            return $data->stock;
        }
        return 0;
    
    }
     public function syncProductQty($product_id, $warehouse_id) {//print_r($product_id);die();
        $balance_qty = $this->getBalanceQuantity($product_id);
        $wh_balance_qty = $this->getBalanceQuantity($product_id, $warehouse_id);//print_r($wh_balance_qty );die();
        if ($this->db->update('products', array('quantity' => $balance_qty), array('id' => $product_id))) {
            if ($this->getWarehouseProducts($product_id, $warehouse_id)) {//print_r($wh_balance_qty );die("1");
                $this->db->update('warehouses_products', array('quantity' => $wh_balance_qty), array('product_id' => $product_id, 'warehouse_id' => $warehouse_id));
            } else {//print_r($wh_balance_qty );die("2");
                if( !$wh_balance_qty) { $wh_balance_qty = 0; }
                $product = $this->getProductByID($product_id);
                $this->db->insert('warehouses_products', array('quantity' => $wh_balance_qty, 'product_id' => $product_id, 'warehouse_id' => $warehouse_id, 'avg_cost' => $product->cost));
            }
            return TRUE;
        }
        return FALSE;
    }
     public function syncQuantity($sale_id = NULL, $purchase_id = NULL, $oitems = NULL, $product_id = NULL) {
        if ($sale_id) {

            $sale_items = $this->getAllSaleItems($sale_id);//print_r($sale_items);die();
            foreach ($sale_items as $item) {
                if ($item->product_type == 'standard') {
                    $this->syncProductQty($item->product_id, $item->warehouse_id);//print_r($item->warehouse_id);die();
                    if (isset($item->option_id) && !empty($item->option_id)) {
                        $this->syncVariantQty($item->option_id, $item->warehouse_id, $item->product_id);
                    }
                } elseif ($item->product_type == 'combo') {
                    $wh = $this->Settings->overselling ? NULL : $item->warehouse_id;
                    $combo_items = $this->getProductComboItems($item->product_id, $wh);
                    foreach ($combo_items as $combo_item) {
                        if($combo_item->type == 'standard') {
                            $this->syncProductQty($combo_item->id, $item->warehouse_id);
                        }
                    }
                }
            }

        } elseif ($purchase_id) {

            $purchase_items = $this->getAllPurchaseItems($purchase_id);
            foreach ($purchase_items as $item) {
                $this->syncProductQty($item->product_id, $item->warehouse_id);
                if (isset($item->option_id) && !empty($item->option_id)) {
                    $this->syncVariantQty($item->option_id, $item->warehouse_id, $item->product_id);
                }
            }

        } elseif ($oitems) {

            foreach ($oitems as $item) {
                if (isset($item->product_type)) {
                    if ($item->product_type == 'standard') {
                        $this->syncProductQty($item->product_id, $item->warehouse_id);
                        if (isset($item->option_id) && !empty($item->option_id)) {
                            $this->syncVariantQty($item->option_id, $item->warehouse_id, $item->product_id);
                        }
                    } elseif ($item->product_type == 'combo') {
                        $combo_items = $this->getProductComboItems($item->product_id, $item->warehouse_id);
                        foreach ($combo_items as $combo_item) {
                            if($combo_item->type == 'standard') {
                                $this->syncProductQty($combo_item->id, $item->warehouse_id);
                            }
                        }
                    }
                } else {
                    $this->syncProductQty($item->product_id, $item->warehouse_id);
                    if (isset($item->option_id) && !empty($item->option_id)) {
                        $this->syncVariantQty($item->option_id, $item->warehouse_id, $item->product_id);
                    }
                }
            }

        } elseif ($product_id) {
            $warehouses = $this->getAllWarehouses();
            foreach ($warehouses as $warehouse) {
                $this->syncProductQty($product_id, $warehouse->id);
                if ($product_variants = $this->getProductVariants($product_id)) {
                    foreach ($product_variants as $pv) {
                        $this->syncVariantQty($pv->id, $warehouse->id, $product_id);
                    }
                }
            }
        }
    }
     

    public function syncPurchaseItems($data = array()) { //print_r($data);die("erytyty");
        if (!empty($data)) {
            foreach ($data as $items) {
                foreach ($items as $item) {
                    if (isset($item['pi_overselling'])) {
                        unset($item['pi_overselling']);
                        $option_id = (isset($item['option_id']) && !empty($item['option_id'])) ? $item['option_id'] : NULL;
                        $clause = array('purchase_id' => NULL, 'transfer_id' => NULL, 'product_id' => $item['product_id'], 'warehouse_id' => $item['warehouse_id'], 'option_id' => $option_id);
                        if ($pi = $this->getPurchasedItem($clause)) {
                            $quantity_balance = $pi->quantity_balance + $item['quantity_balance'];
                            $this->db->update('purchase_items', array('quantity_balance' => $quantity_balance), array('id' => $pi->id));
                        } else {
                            $clause['quantity'] = 0;
                            $clause['item_tax'] = 0;
                            $clause['quantity_balance'] = $item['quantity_balance'];
                            $clause['status'] = 'received';
                            $clause['option_id'] = !empty($clause['option_id']) && is_numeric($clause['option_id']) ? $clause['option_id'] : NULL;
                            $this->db->insert('purchase_items', $clause);
                        }
                    } else {
                        if ($item['inventory']) {
                            $this->db->update('purchase_items', array('quantity_balance' => $item['quantity_balance']), array('id' => $item['purchase_item_id']));
                        }
                    }
                }
            }
            return TRUE;
        }
        return FALSE;
    }

    
 public function getProductByCode($code)
    {
        $q = $this->db->get_where('products', array('code' => $code), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
     public function suspendSale($data = array(), $items = array(), $did = NULL)
    {
       // $this->db->insert('daily_stock', $daily_product);
        $sData = array(
            'count' => $data['total_items'],
            'biller_id' => $data['biller_id'],
            'customer_id' => $data['customer_id'],
            'warehouse_id' => $data['warehouse_id'],
            'customer' => $data['customer'],
            'date' => $data['date'],
            'suspend_note' => $data['suspend_note'],
            'total' => $data['grand_total'],
            'order_tax_id' => $data['order_tax_id'],
            'order_discount_id' => $data['order_discount_id'],
            'created_by' =>  $data['created_by']
        );

        if ($did) {

            if ($this->db->update('suspended_bills', $sData, array('id' => $did)) && $this->db->delete('suspended_items', array('suspend_id' => $did))) {
                $addOn = array('suspend_id' => $did);
                end($addOn);
                foreach ($items as &$var) {
                    $var = array_merge($addOn, $var);
                }
                if ($this->db->insert_batch('suspended_items', $items)) {
                    return TRUE;
                }
            }

        } else {

            if ($this->db->insert('suspended_bills', $sData)) {
                $suspend_id = $this->db->insert_id();
                $addOn = array('suspend_id' => $suspend_id);
                end($addOn);
                foreach ($items as &$var) {
                    $var = array_merge($addOn, $var);
                }
                if ($this->db->insert_batch('suspended_items', $items)) {
                    return TRUE;
                }
            }

        }
        return FALSE;
    }
public function getInvoiceByID($id)
    {

        $q = $this->db->get_where('sales', array('id' => $id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }

        return FALSE;
    }
    
 public function insertpayment($items) {
  $this->db->insert('payments', $items);

      return TRUE; 

}
 public function insertproduct($data = array()) {
    $this->db->insert('sale_items', $data);

      return TRUE; 
    
 }
 public function fld($ldate)
    {
        if ($ldate) {
            $date = explode(' ', $ldate);
            $jsd = $this->dateFormats['js_sdate'];
            $inv_date = $date[0];
            $time = $date[1];
            if ($jsd == 'dd-mm-yyyy' || $jsd == 'dd/mm/yyyy' || $jsd == 'dd.mm.yyyy') {
                $date = substr($inv_date, -4) . "-" . substr($inv_date, 3, 2) . "-" . substr($inv_date, 0, 2) . " " . $time;
            } elseif ($jsd == 'mm-dd-yyyy' || $jsd == 'mm/dd/yyyy' || $jsd == 'mm.dd.yyyy') {
                $date = substr($inv_date, -4) . "-" . substr($inv_date, 0, 2) . "-" . substr($inv_date, 3, 2) . " " . $time;
            } else {
                $date = $inv_date;
            }
            return $date;
        } else {
            return '0000-00-00 00:00:00';
        }
    }
 public function addPayment($payment = array(), $customer_id = null)
    {
        if (isset($payment['sale_id']) && isset($payment['paid_by']) && isset($payment['amount'])) {
            $payment['pos_paid'] = $payment['amount'];
            $inv = $this->getInvoiceByID($payment['sale_id']);
            $paid = $inv->paid + $payment['amount'];
            if ($payment['paid_by'] == 'ppp') {
                $card_info = array("number" => $payment['cc_no'], "exp_month" => $payment['cc_month'], "exp_year" => $payment['cc_year'], "cvc" => $payment['cc_cvv2'], 'type' => $payment['cc_type']);
                $result = $this->paypal($payment['amount'], $card_info);
                if (!isset($result['error'])) {
                    $payment['transaction_id'] = $result['transaction_id'];
                    $payment['date'] = $this->fld($result['created_at']);
                    $payment['amount'] = $result['amount'];
                    $payment['currency'] = $result['currency'];
                    unset($payment['cc_cvv2']);
                    $this->db->insert('payments', $payment);
                    $paid += $payment['amount'];
                } else {
                    $msg[] = lang('payment_failed');
                    if (!empty($result['message'])) {
                        foreach ($result['message'] as $m) {
                            $msg[] = '<p class="text-danger">' . $m['L_ERRORCODE'] . ': ' . $m['L_LONGMESSAGE'] . '</p>';
                        }
                    } else {
                        $msg[] = lang('paypal_empty_error');
                    }
                }
            } elseif ($payment['paid_by'] == 'stripe') {
                $card_info = array("number" => $payment['cc_no'], "exp_month" => $payment['cc_month'], "exp_year" => $payment['cc_year'], "cvc" => $payment['cc_cvv2'], 'type' => $payment['cc_type']);
                $result = $this->stripe($payment['amount'], $card_info);
                if (!isset($result['error'])) {
                    $payment['transaction_id'] = $result['transaction_id'];
                    $payment['date'] = $this->fld($result['created_at']);
                    $payment['amount'] = $result['amount'];
                    $payment['currency'] = $result['currency'];
                    unset($payment['cc_cvv2']);
                    $data_pay = array(
					'type' 			=> 'income',
					'date' 			=> $payment['date'],
					'Account' 		=> '4',
					'category' 		=> '8',
					'amount' 		=> $payment['amount'],
					'note' 			=> '',
					 'acc_type' 	=> '18',
					'description' 	=> 'Sale',
					'deposit_withdrawal' => 'deposit'
					);
                   $this->db->insert('transaction',$data_pay);
                     $this->db->insert('payments', $payment);
                    $paid += $payment['amount'];
                } else {
                    $msg[] = lang('payment_failed');
                    $msg[] = '<p class="text-danger">' . $result['code'] . ': ' . $result['message'] . '</p>';
                }

            } elseif ($payment['paid_by'] == 'authorize') {
                $authorize_arr = array("x_card_num" => $payment['cc_no'], "x_exp_date" => ($payment['cc_month'].'/'.$payment['cc_year']), "x_card_code" => $payment['cc_cvv2'], 'x_amount' => $payment['amount'], 'x_invoice_num' => $inv->id, 'x_description' => 'Sale Ref '.$inv->reference_no.' and Payment Ref '.$payment['reference_no']);
                list($first_name, $last_name) = explode(' ', $payment['cc_holder'], 2);
                $authorize_arr['x_first_name'] = $first_name;
                $authorize_arr['x_last_name'] = $last_name;
                $result = $this->authorize($authorize_arr);
                if (!isset($result['error'])) {
                    $payment['transaction_id'] = $result['transaction_id'];
                    $payment['approval_code'] = $result['approval_code'];
                    $payment['date'] = $this->fld($result['created_at']);
                    unset($payment['cc_cvv2']);
                    $this->db->insert('payments', $payment);
                    $paid += $payment['amount'];
                } else {
                    $msg[] = lang('payment_failed');
                    $msg[] = '<p class="text-danger">' . $result['msg'] . '</p>';
                }

            } else {
                if ($payment['paid_by'] == 'gift_card') {
                    $gc = $this->getGiftCardByNO($payment['cc_no']);
                    $this->db->update('gift_cards', array('balance' => ($gc->balance - $payment['amount'])), array('card_no' => $payment['cc_no']));
                } elseif ($customer_id && $payment['paid_by'] == 'deposit') {
                    $customer = $this->getCompanyByID($customer_id);
                    $this->db->update('companies', array('deposit_amount' => ($customer->deposit_amount-$payment['amount'])), array('id' => $customer_id));
                }
                unset($payment['cc_cvv2']);
                
                		$datads = array(
		                		'type' 			=> 'income',
						'date' 			=>  $payment['date'],
		               			 'Account' 		=> '5',
						'category' 		=> '8',
						'amount' 		=>  $payment['amount'],
		                		'note' 			=> '',
						'description' 		=> 'Sale',
						 'acc_type' 		=> '18',
						'deposit_withdrawal' 	=> 'deposit'
            );
			
                $this->db->insert('payments', $payment);
                $this->addTransaction($datads,$payment['sale_id']);
                $paid += $payment['amount'];
            }
            if (!isset($msg)) {
                if ($this->getReference('pay') == $payment['reference_no']) {
                    $this->updateReference('pay');
                }
                $this->syncSalePayments($payment['sale_id']);
                return array('status' => 1, 'msg' => '');
            }
            
            return array('status' => 0, 'msg' => $msg);

        }
        return false;
    }
    public function getPaymentByID($id)
    {
        $q = $this->db->get_where('payments', array('id' => $id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
     public function updatePayment($id, $data = array(), $customer_id = null)
    {//print_r($data );die();
        $opay = $this->getPaymentByID($id);
        if ($this->db->update('payments', $data, array('id' => $id))) {
            $this->syncSalePayments($data['sale_id']);
            if ($opay->paid_by == 'gift_card') {
                $gc = $this->getGiftCardByNO($opay->cc_no);
                $this->db->update('gift_cards', array('balance' => ($gc->balance+$opay->amount)), array('card_no' => $opay->cc_no));
            } elseif ($opay->paid_by == 'deposit') {
                if (!$customer_id) {
                    $sale = $this->getInvoiceByID($opay->sale_id);
                    $customer_id = $sale->customer_id;
                }
                $customer = $this->getCompanyByID($customer_id);
                $this->db->update('companies', array('deposit_amount' => ($customer->deposit_amount+$opay->amount)), array('id' => $customer->id));
            }
            if ($data['paid_by'] == 'gift_card') {
                $gc = $this->getGiftCardByNO($data['cc_no']);
                $this->db->update('gift_cards', array('balance' => ($gc->balance - $data['amount'])), array('card_no' => $data['cc_no']));
            } elseif ($customer_id && $data['paid_by'] == 'deposit') {
                $customer = $this->getCompanyByID($customer_id);
                $this->db->update('companies', array('deposit_amount' => ($customer->deposit_amount-$data['amount'])), array('id' => $customer_id));
            }
            return true;
        }
        else
        {
        if($this->db->insert('payments', $data)) {
            $this->syncSalePayments($data['sale_id']);
            if ($opay->paid_by == 'gift_card') {
                $gc = $this->getGiftCardByNO($opay->cc_no);
                $this->db->update('gift_cards', array('balance' => ($gc->balance+$opay->amount)), array('card_no' => $opay->cc_no));
            } elseif ($opay->paid_by == 'deposit') {
                if (!$customer_id) {
                    $sale = $this->getInvoiceByID($opay->sale_id);
                    $customer_id = $sale->customer_id;
                }
                $customer = $this->getCompanyByID($customer_id);
                $this->db->update('companies', array('deposit_amount' => ($customer->deposit_amount+$opay->amount)), array('id' => $customer->id));
            }
            if ($data['paid_by'] == 'gift_card') {
                $gc = $this->getGiftCardByNO($data['cc_no']);
                $this->db->update('gift_cards', array('balance' => ($gc->balance - $data['amount'])), array('card_no' => $data['cc_no']));
            } elseif ($customer_id && $data['paid_by'] == 'deposit') {
                $customer = $this->getCompanyByID($customer_id);
                $this->db->update('companies', array('deposit_amount' => ($customer->deposit_amount-$data['amount'])), array('id' => $customer_id));
            }
            return true;
        }
        }
        return false;
    }
    public function getInvoicePayments($sale_id)
    {
        $q = $this->db->get_where("payments", array('sale_id' => $sale_id));
        if ($q->num_rows() > 0) {
            foreach (($q->result()) as $row) {
                $data[] = $row;
            }

            return $data;
        }

        return FALSE;
    }
     public function getCompanyByID($id) {
        $q = $this->db->get_where('companies', array('id' => $id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
    public function getGiftCardByNO($no) {
        $q = $this->db->get_where('gift_cards', array('card_no' => $no), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
     public function authorize($authorize_data)
    {
        $this->load->library('authorize_net');
        // $authorize_data = array( 'x_card_num' => '4111111111111111', 'x_exp_date' => '12/20', 'x_card_code' => '123', 'x_amount' => '25', 'x_invoice_num' => '15454', 'x_description' => 'References');
        $this->authorize_net->setData($authorize_data);

        if( $this->authorize_net->authorizeAndCapture() ) {
            $result = array(
                'transaction_id' => $this->authorize_net->getTransactionId(),
                'approval_code' => $this->authorize_net->getApprovalCode(),
                'created_at' => date($this->dateFormats['php_ldate']),
            );
            return $result;
        } else {
            return array('error' => 1, 'msg' => $this->authorize_net->getError());
        }
    }
     function stripe($amount = 0, $card_info = array(), $desc = '')
    {
        $this->load->admin_model('stripe_payments');
        //$card_info = array( "number" => "4242424242424242", "exp_month" => 1, "exp_year" => 2016, "cvc" => "314" );
        //$amount = $amount ? $amount*100 : 3000;
        unset($card_info['type']);
        $amount = $amount * 100;
        if ($amount && !empty($card_info)) {
            $token_info = $this->stripe_payments->create_card_token($card_info);
            if (!isset($token_info['error'])) {
                $token = $token_info->id;
                $data = $this->stripe_payments->insert($token, $desc, $amount, $this->default_currency->code);
                if (!isset($data['error'])) {
                    $result = array('transaction_id' => $data->id,
                        'created_at' => date($this->dateFormats['php_ldate'], $data->created),
                        'amount' => ($data->amount / 100),
                        'currency' => strtoupper($data->currency)
                    );
                    return $result;
                } else {
                    return $data;
                }
            } else {
                return $token_info;
            }
        }
        return false;
    }
  function paypal($amount = NULL, $card_info = array(), $desc = '')
    {
        $this->load->admin_model('paypal_payments');
        //$card_info = array( "number" => "5522340006063638", "exp_month" => 2, "exp_year" => 2016, "cvc" => "456", 'type' => 'MasterCard' );
        //$amount = $amount ? $amount : 30.00;
        if ($amount && !empty($card_info)) {
            $data = $this->paypal_payments->Do_direct_payment($amount, $this->default_currency->code, $card_info, $desc);
            if (!isset($data['error'])) {
                $result = array('transaction_id' => $data['TRANSACTIONID'],
                    'created_at' => date($this->dateFormats['php_ldate'], strtotime($data['TIMESTAMP'])),
                    'amount' => $data['AMT'],
                    'currency' => strtoupper($data['CURRENCYCODE'])
                );
                return $result;
            } else {
                return $data;
            }
        }
        return false;
    }
/***************************COSTING******************************************/

    public function costing($items) {
        $citems = array();
       // $cost = array();
        foreach ($items as $item) { 
            $option = (isset($item['option_id']) && !empty($item['option_id']) && $item['option_id'] != 'null' && $item['option_id'] != 'false') ? $item['option_id'] : '';
            $pr = $this->getProductByID($item['product_id']);
            $item['option_id'] = $option;
            if ($pr && $pr->type == 'standard') {
                if (isset($citems['p' . $item['product_id'] . 'o' . $item['option_id']])) {
                    $citems['p' . $item['product_id'] . 'o' . $item['option_id']]['aquantity'] += $item['quantity'];
                } else {
                    $citems['p' . $item['product_id'] . 'o' . $item['option_id']] = $item;
                    $citems['p' . $item['product_id'] . 'o' . $item['option_id']]['aquantity'] = $item['quantity'];
                }
            } elseif ($pr && $pr->type == 'combo') {
                $wh = $this->Settings->overselling ? NULL : $item['warehouse_id'];
                $combo_items = $this->getProductComboItems($item['product_id'], $wh);
                foreach ($combo_items as $combo_item) {
                    if ($combo_item->type == 'standard') {
                        if (isset($citems['p' . $combo_item->id . 'o' . $item['option_id']])) {
                            $citems['p' . $combo_item->id . 'o' . $item['option_id']]['aquantity'] += ($combo_item->qty*$item['quantity']);
                        } else {
                            $cpr = $this->getProductByID($combo_item->id);
                            if ($cpr->tax_rate) {
                                $cpr_tax = $this->getTaxRateByID($cpr->tax_rate);
                                if ($cpr->tax_method) {
                                    $item_tax = $this->formatDecimal((($combo_item->unit_price) * $cpr_tax->rate) / (100 + $cpr_tax->rate));
                                    $net_unit_price = $combo_item->unit_price - $item_tax;
                                    $unit_price = $combo_item->unit_price;
                                } else {
                                    $item_tax = $this->formatDecimal((($combo_item->unit_price) * $cpr_tax->rate) / 100);
                                    $net_unit_price = $combo_item->unit_price;
                                    $unit_price = $combo_item->unit_price + $item_tax;
                                }
                            } else {
                                $net_unit_price = $combo_item->unit_price;
                                $unit_price = $combo_item->unit_price;
                            }
                            $cproduct = array('product_id' => $combo_item->id, 'product_name' => $cpr->name, 'product_type' => $combo_item->type, 'quantity' => ($combo_item->qty*$item['quantity']), 'net_unit_price' => $net_unit_price, 'unit_price' => $unit_price, 'warehouse_id' => $item['warehouse_id'], 'item_tax' => $item_tax, 'tax_rate_id' => $cpr->tax_rate, 'tax' => ($cpr_tax->type == 1 ? $cpr_tax->rate.'%' : $cpr_tax->rate), 'option_id' => NULL, 'product_unit_id' => $cpr->unit);
                            $citems['p' . $combo_item->id . 'o' . $item['option_id']] = $cproduct;
                            $citems['p' . $combo_item->id . 'o' . $item['option_id']]['aquantity'] = ($combo_item->qty*$item['quantity']);
                        }
                    }
                }
            }
        }
       //$this->sma->print_arrays($citems);
        $cost = array();
        foreach ($citems as $item) {
            $item['aquantity'] = $citems['p' . $item['product_id'] . 'o' . $item['option_id']]['aquantity'];
            $cost[] = $this->item_costing($item, TRUE);//print_r($cost);die();
        }
        return $cost;
    }
    
    public function formatDecimal($number, $decimals = null)
    {
        if (!is_numeric($number)) {
            return null;
        }
        if (!$decimals && $decimals !== 0) {
            $decimals = $this->Settings->decimals;
        }
        return number_format($number, $decimals, '.', '');
    }
    
    public function getTaxRateByID($id) {
        $q = $this->db->get_where('tax_rates', array('id' => $id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
    
    public function getProductComboItems($pid, $warehouse_id = NULL) {
        $this->db->select('products.id as id, combo_items.item_code as code, combo_items.quantity as qty, products.name as name, products.type as type, combo_items.unit_price as unit_price, warehouses_products.quantity as quantity')
            ->join('products', 'products.code=combo_items.item_code', 'left')
            ->join('warehouses_products', 'warehouses_products.product_id=products.id', 'left')
            ->group_by('combo_items.id');
        if($warehouse_id) {
            $this->db->where('warehouses_products.warehouse_id', $warehouse_id);
        }
        $q = $this->db->get_where('combo_items', array('combo_items.product_id' => $pid));
        if ($q->num_rows() > 0) {
            foreach (($q->result()) as $row) {
                $data[] = $row;
            }

            return $data;
        }
        return FALSE;
    }
   
    public function getUnitByID($id) {
        $q = $this->db->get_where("units", array('id' => $id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
    public function convertToBase($unit, $value) {
        switch($unit->operator) {
            case '*':
                return $value / $unit->operation_value;
                break;
            case '/':
                return $value * $unit->operation_value;
                break;
            case '+':
                return $value - $unit->operation_value;
                break;
            case '-':
                return $value + $unit->operation_value;
                break;
            default:
                return $value;
        }
    }
    public function getPurchasedItems($product_id, $warehouse_id, $option_id = NULL) {
        $orderby = ($this->Settings->accounting_method == 1) ? 'asc' : 'desc';
        $this->db->select('id, quantity, quantity_balance, net_unit_cost, unit_cost, item_tax');
        $this->db->where('product_id', $product_id)->where('warehouse_id', $warehouse_id)->where('quantity_balance !=', 0);
        if (!isset($option_id) || empty($option_id)) {
            $this->db->group_start()->where('option_id', NULL)->or_where('option_id', 0)->group_end();
        } else {
            $this->db->where('option_id', $option_id);
        }
        $this->db->group_start()->where('status', 'received')->or_where('status', 'partial')->group_end();
        $this->db->group_by('id');
        $this->db->order_by('date', $orderby);
        $this->db->order_by('purchase_id', $orderby);
        $q = $this->db->get('purchase_items');
        if ($q->num_rows() > 0) {
            foreach (($q->result()) as $row) {
                $data[] = $row;
            }//print_r($data);die();
            return $data;
        }
        return FALSE;
    }

     public function calculateCost($product_id, $warehouse_id, $net_unit_price, $unit_price, $quantity, $product_name, $option_id, $item_quantity) {
        $pis = $this->getPurchasedItems($product_id, $warehouse_id, $option_id);
        $real_item_qty = $quantity;
        $quantity = $item_quantity;
        $balance_qty = $quantity;
        foreach ($pis as $pi) {
            $cost_row = NULL;
            if (!empty($pi) && $balance_qty <= $quantity && $quantity > 0) {
                $purchase_unit_cost = $pi->unit_cost ? $pi->unit_cost : ($pi->net_unit_cost + ($pi->item_tax / $pi->quantity));
                if ($pi->quantity_balance >= $quantity && $quantity > 0) {
                    $balance_qty = $pi->quantity_balance - $quantity;
                    $cost_row = array('date' => date('Y-m-d'), 'product_id' => $product_id, 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => $pi->id, 'quantity' => $quantity, 'purchase_net_unit_cost' => $pi->net_unit_cost, 'purchase_unit_cost' => $purchase_unit_cost, 'sale_net_unit_price' => $net_unit_price, 'sale_unit_price' => $unit_price, 'quantity_balance' => $balance_qty, 'inventory' => 1, 'option_id' => $option_id);
                    $quantity = 0;
                } elseif ($quantity > 0) {
                    $quantity = $quantity - $pi->quantity_balance;
                    $balance_qty = $quantity;
                    $cost_row = array('date' => date('Y-m-d'), 'product_id' => $product_id, 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => $pi->id, 'quantity' => $pi->quantity_balance, 'purchase_net_unit_cost' => $pi->net_unit_cost, 'purchase_unit_cost' => $purchase_unit_cost, 'sale_net_unit_price' => $net_unit_price, 'sale_unit_price' => $unit_price, 'quantity_balance' => 0, 'inventory' => 1, 'option_id' => $option_id);
                }
            }
            $cost[] = $cost_row;
            if ($quantity == 0) {
                break;
            }
        }
        
        return $cost;
    }
    public function getWarehouseProducts($product_id, $warehouse_id = NULL) {
        if ($warehouse_id) {
            $this->db->where('warehouse_id', $warehouse_id);
        }
        $q = $this->db->get_where('warehouses_products', array('product_id' => $product_id));
        if ($q->num_rows() > 0) {
            foreach (($q->result()) as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return FALSE;
    }
public function getWarehouseProduct($warehouse_id, $product_id) {
        $q = $this->db->get_where('warehouses_products', array('product_id' => $product_id, 'warehouse_id' => $warehouse_id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
function calculateTax($product_details = NULL, $tax_details, $custom_value = NULL, $c_on = NULL) {
        $value = $custom_value ? $custom_value : (($c_on == 'cost') ? $product_details->cost : $product_details->price);
        $tax_amount = 0; $tax = 0;
        if ($tax_details && $tax_details->type == 1 && $tax_details->rate != 0) {
            if ($product_details && $product_details->tax_method == 1) {
                $tax_amount = $this->formatDecimal((($value) * $tax_details->rate) / 100, 4);
                $tax = $this->formatDecimal($tax_details->rate, 0) . "%";
            } else {
                $tax_amount = $this->formatDecimal((($value) * $tax_details->rate) / (100 + $tax_details->rate), 4);
                $tax = $this->formatDecimal($tax_details->rate, 0) . "%";
            }
        } elseif ($tax_details && $tax_details->type == 2) {
            $tax_amount = $this->formatDecimal($tax_details->rate);
            $tax = $this->formatDecimal($tax_details->rate, 0);
        }
        return array('id' => $tax_details->id, 'tax' => $tax, 'amount' => $tax_amount);
    }

    public function getAddressByID($id) {
        return $this->db->get_where('addresses', ['id' => $id], 1)->row();
    }
  public function calculateAVCost($product_id, $warehouse_id, $net_unit_price, $unit_price, $quantity, $product_name, $option_id, $item_quantity) {
        $product = $this->getProductByID($product_id);
        $real_item_qty = $quantity;
        $wp_details = $this->getWarehouseProduct($warehouse_id, $product_id);
        $con = $wp_details ? $wp_details->avg_cost : $product->cost;
        $tax_rate = $this->getTaxRateByID($product->tax_rate);
        $ctax = $this->calculateTax($product, $tax_rate, $con);
        if ($product->tax_method) {
            $avg_net_unit_cost = $con;
            $avg_unit_cost = ($con + $ctax['amount']);
        } else {
            $avg_unit_cost = $con;
            $avg_net_unit_cost = ($con - $ctax['amount']);
        }
//print_r($warehouse_id);die();
        if ($pis = $this->getPurchasedItems($product_id, $warehouse_id, $option_id)) {
            $cost_row = array();
            $quantity = $item_quantity;
            $balance_qty = $quantity;
            foreach ($pis as $pi) {
                if (!empty($pi) && $pi->quantity > 0 && $balance_qty <= $quantity && $quantity > 0) {
                    if ($pi->quantity_balance >= $quantity && $quantity > 0) {
                        $balance_qty = $pi->quantity_balance - $quantity;
                        $cost_row = array('date' => date('Y-m-d'), 'product_id' => $product_id, 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => $pi->id, 'quantity' => $quantity, 'purchase_net_unit_cost' => $avg_net_unit_cost, 'purchase_unit_cost' => $avg_unit_cost, 'sale_net_unit_price' => $net_unit_price, 'sale_unit_price' => $unit_price, 'quantity_balance' => $balance_qty, 'inventory' => 1, 'option_id' => $option_id);
                        $quantity = 0;
                    } elseif ($quantity > 0) {
                        $quantity = $quantity - $pi->quantity_balance;
                        $balance_qty = $quantity;
                        $cost_row = array('date' => date('Y-m-d'), 'product_id' => $product_id, 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => $pi->id, 'quantity' => $pi->quantity_balance, 'purchase_net_unit_cost' => $avg_net_unit_cost, 'purchase_unit_cost' => $avg_unit_cost, 'sale_net_unit_price' => $net_unit_price, 'sale_unit_price' => $unit_price, 'quantity_balance' => 0, 'inventory' => 1, 'option_id' => $option_id);
                    }
                }
                if (empty($cost_row)) {
                    break;
                }
                $cost[] = $cost_row;
                if ($quantity == 0) {
                    break;
                }
            }
        }
        if ($quantity > 0 && !$this->Settings->overselling) {
           /* $this->session->set_flashdata('error', sprintf(lang("quantity_out_of_stock_for_%s"), ($pi->product_name ? $pi->product_name : $product_name)));
            redirect($_SERVER["HTTP_REFERER"]);*/
            return FALSE;
        } elseif ($quantity > 0) {
            $cost[] = array('date' => date('Y-m-d'), 'product_id' => $product_id, 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => NULL, 'quantity' => $real_item_qty, 'purchase_net_unit_cost' => $avg_net_unit_cost, 'purchase_unit_cost' => $avg_unit_cost, 'sale_net_unit_price' => $net_unit_price, 'sale_unit_price' => $unit_price, 'quantity_balance' => NULL, 'overselling' => 1, 'inventory' => 1);
            $cost[] = array('pi_overselling' => 1, 'product_id' => $product_id, 'quantity_balance' => (0 - $quantity), 'warehouse_id' => $warehouse_id, 'option_id' => $option_id);
        }
        return $cost;
    }
   
   
      public function item_costing($item, $pi = NULL) {
        $item_quantity = $pi ? $item['aquantity'] : $item['quantity'];
        if (!isset($item['option_id']) || empty($item['option_id']) || $item['option_id'] == 'null') {
            $item['option_id'] = NULL;
        }

        if ($this->Settings->accounting_method != 2 && !$this->Settings->overselling) {
            if ($this->getProductByID($item['product_id'])) {
                if ($item['product_type'] == 'standard') {
                    $unit = $this->getUnitByID($item['product_unit_id']);
                    $item['net_unit_price'] = $this->convertToBase($unit, $item['net_unit_price']);
                    $item['unit_price'] = $this->convertToBase($unit, $item['unit_price']);
                    $cost = $this->calculateCost($item['product_id'], $item['warehouse_id'], $item['net_unit_price'], $item['unit_price'], $item['quantity'], $item['product_name'], $item['option_id'], $item_quantity);
                } elseif ($item['product_type'] == 'combo') {
                    $combo_items = $this->getProductComboItems($item['product_id'], $item['warehouse_id']);
                    foreach ($combo_items as $combo_item) {
                        $pr = $this->getProductByCode($combo_item->code);
                        if ($pr->tax_rate) {
                            $pr_tax = $this->getTaxRateByID($pr->tax_rate);
                            if ($pr->tax_method) {
                                $item_tax = $this->sma->formatDecimal((($combo_item->unit_price) * $pr_tax->rate) / (100 + $pr_tax->rate));
                                $net_unit_price = $combo_item->unit_price - $item_tax;
                                $unit_price = $combo_item->unit_price;
                            } else {
                                $item_tax = $this->sma->formatDecimal((($combo_item->unit_price) * $pr_tax->rate) / 100);
                                $net_unit_price = $combo_item->unit_price;
                                $unit_price = $combo_item->unit_price + $item_tax;
                            }
                        } else {
                            $net_unit_price = $combo_item->unit_price;
                            $unit_price = $combo_item->unit_price;
                        }
                        if ($pr->type == 'standard') {
                            $cost[] = $this->calculateCost($pr->id, $item['warehouse_id'], $net_unit_price, $unit_price, ($combo_item->qty * $item['quantity']), $pr->name, NULL, $item_quantity);
                        } else {
                            $cost[] = array(array('date' => date('Y-m-d'), 'product_id' => $pr->id, 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => NULL, 'quantity' => ($combo_item->qty * $item['quantity']), 'purchase_net_unit_cost' => 0, 'purchase_unit_cost' => 0, 'sale_net_unit_price' => $combo_item->unit_price, 'sale_unit_price' => $combo_item->unit_price, 'quantity_balance' => NULL, 'inventory' => NULL));
                        }
                    }
                } else {
                    $cost = array(array('date' => date('Y-m-d'), 'product_id' => $item['product_id'], 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => NULL, 'quantity' => $item['quantity'], 'purchase_net_unit_cost' => 0, 'purchase_unit_cost' => 0, 'sale_net_unit_price' => $item['net_unit_price'], 'sale_unit_price' => $item['unit_price'], 'quantity_balance' => NULL, 'inventory' => NULL));
                }
            } elseif ($item['product_type'] == 'manual') {
                $cost = array(array('date' => date('Y-m-d'), 'product_id' => $item['product_id'], 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => NULL, 'quantity' => $item['quantity'], 'purchase_net_unit_cost' => 0, 'purchase_unit_cost' => 0, 'sale_net_unit_price' => $item['net_unit_price'], 'sale_unit_price' => $item['unit_price'], 'quantity_balance' => NULL, 'inventory' => NULL));
            }

        } else {

            if ($this->getProductByID($item['product_id'])) {
                if ($item['product_type'] == 'standard') {
                    $cost = $this->calculateAVCost($item['product_id'], $item['warehouse_id'], $item['net_unit_price'], $item['unit_price'], $item['quantity'], $item['product_name'], $item['option_id'], $item_quantity);
                } elseif ($item['product_type'] == 'combo') {
                    $combo_items = $this->getProductComboItems($item['product_id'], $item['warehouse_id']);
                    foreach ($combo_items as $combo_item) {
                        $pr = $this->getProductByCode($combo_item->code);
                        if ($pr->tax_rate) {
                            $pr_tax = $this->getTaxRateByID($pr->tax_rate);
                            if ($pr->tax_method) {
                                $item_tax = $this->sma->formatDecimal((($combo_item->unit_price) * $pr_tax->rate) / (100 + $pr_tax->rate));
                                $net_unit_price = $combo_item->unit_price - $item_tax;
                                $unit_price = $combo_item->unit_price;
                            } else {
                                $item_tax = $this->sma->formatDecimal((($combo_item->unit_price) * $pr_tax->rate) / 100);
                                $net_unit_price = $combo_item->unit_price;
                                $unit_price = $combo_item->unit_price + $item_tax;
                            }
                        } else {
                            $net_unit_price = $combo_item->unit_price;
                            $unit_price = $combo_item->unit_price;
                        }
                        $cost[] = $this->calculateAVCost($combo_item->id, $item['warehouse_id'], $net_unit_price, $unit_price, ($combo_item->qty * $item['quantity']), $item['product_name'], $item['option_id'], $item_quantity);
                    }
                } else {
                    $cost = array(array('date' => date('Y-m-d'), 'product_id' => $item['product_id'], 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => NULL, 'quantity' => $item['quantity'], 'purchase_net_unit_cost' => 0, 'purchase_unit_cost' => 0, 'sale_net_unit_price' => $item['net_unit_price'], 'sale_unit_price' => $item['unit_price'], 'quantity_balance' => NULL, 'inventory' => NULL));
                }
            } elseif ($item['product_type'] == 'manual') {
                $cost = array(array('date' => date('Y-m-d'), 'product_id' => $item['product_id'], 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => NULL, 'quantity' => $item['quantity'], 'purchase_net_unit_cost' => 0, 'purchase_unit_cost' => 0, 'sale_net_unit_price' => $item['net_unit_price'], 'sale_unit_price' => $item['unit_price'], 'quantity_balance' => NULL, 'inventory' => NULL));
            }

        }//print_r($item_quantity);die('3');
        return $cost;
    }

      public function getRegisterCardSales($date,$user_id)
    {
        /*if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        //$this->db->select('COUNT(' . $this->db->dbprefix('payments') . '.id) as total_card_slips, SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            $this->db->select('SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date >', $date)->where('paid_by', 'card');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }
    
      public function getRegisterCCSales($date,$user_id)
    {
        /*if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('COUNT(' . $this->db->dbprefix('payments') . '.id) as total_cc_slips, SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date >', $date)->where('paid_by', 'credit');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getRegisterCashSales($date, $user_id)
    {
      /*  if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        //$this->db->select('SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
        $this->db->select('SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date >', $date)->where('paid_by', 'cash');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }
    
    // public function getRegistercreditSalesTot($date,$user_id)
    // {
    //     /*if (!$date) {
    //         $date = $this->session->userdata('register_open_time');
    //     }
    //     if (!$user_id) {
    //         $user_id = $this->session->userdata('user_id');
    //     }*/
    //     $this->db->select('COUNT(' . $this->db->dbprefix('payments') . '.id) as total_card_slips, SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
    //     ->join('sales', 'sales.id=payments.sale_id', 'left')
    //         ->where('type', 'received')->where('payments.date >', $date)->where('paid_by', 'card');
    //     $this->db->where('payments.created_by', $user_id);

    //     $q = $this->db->get('payments');
    //     if ($q->num_rows() > 0) {
    //         return $q->row();
    //     }
    //     return false;
    // }
    
    
     public function getRegistercreditSalesTot($date,$user_id)
    {
       
        $this->db->select('COUNT(grand_total) as count, SUM( COALESCE( grand_total, 0 ) ) AS total', FALSE)
         // $this->db->select('SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
        
        ->where('sales.date >', $date);
        $this->db->where('sales.created_by', $user_id);

        $q = $this->db->get('sales');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }
    
    public function getRegisterReceiptcash($date, $user_id)
    {
      /*  if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date <', $date)->where('paid_by', 'cash');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }
    
    public function getRegisterReceiptcard($date, $user_id)
    {
      /*  if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date <', $date)->where('paid_by', 'card');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getRegisterRefunds($date, $user_id)
    {
        /*if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS returned', FALSE)
            ->join('sales', 'sales.id=payments.return_id', 'left')
            ->where('type', 'returned')->where('payments.date >', $date);
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getRegisterCashRefunds($date, $user_id )
    {
       /* if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS returned', FALSE)
            ->join('sales', 'sales.id=payments.return_id', 'left')
            ->where('type', 'returned')->where('payments.date >', $date)->where('paid_by', 'cash');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getRegisterExpenses($date, $user_id )
    {
        /*if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }-*/
        $this->db->select('SUM( COALESCE( amount, 0 ) ) AS total', FALSE)
            ->where('date >', $date);
        $this->db->where('created_by', $user_id);

        $q = $this->db->get('expenses');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getRegisterChSales($date, $user_id )
    {
       /* if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('COUNT(' . $this->db->dbprefix('payments') . '.id) as total_cheques, SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date >', $date)->where('paid_by', 'Cheque');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getRegisterGCSales($date, $user_id )
    {
        /*if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('COUNT(' . $this->db->dbprefix('payments') . '.id) as total_cheques, SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date >', $date)->where('paid_by', 'gift_card');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getRegisterPPPSales($date, $user_id )
    {
       /* if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('COUNT(' . $this->db->dbprefix('payments') . '.id) as total_cheques, SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date >', $date)->where('paid_by', 'ppp');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getRegisterStripeSales($date, $user_id )
    {
        /*if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('COUNT(' . $this->db->dbprefix('payments') . '.id) as total_cheques, SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date >', $date)->where('paid_by', 'stripe');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }

    public function getRegisterAuthorizeSales($date, $user_id)
    {
       /* if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('COUNT(' . $this->db->dbprefix('payments') . '.id) as total_cheques, SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date >', $date)->where('paid_by', 'authorize');
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }
public function getRegisterSales($date, $user_id)
    {
       /* if (!$date) {
            $date = $this->session->userdata('register_open_time');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }*/
        $this->db->select('SUM( COALESCE( grand_total, 0 ) ) AS total, SUM( COALESCE( amount, 0 ) ) AS paid', FALSE)
            ->join('sales', 'sales.id=payments.sale_id', 'left')
            ->where('type', 'received')->where('payments.date >', $date);
        $this->db->where('payments.created_by', $user_id);

        $q = $this->db->get('payments');
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return false;
    }
     public function getregisterpos()
    {
       $this->db->order_by('id',desc);
        $q = $this->db->get_where('pos_register', array('status' => 'open'), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        }
       
    public function registerData($user_id)
    {
        if (!$user_id) {
            $user_id = $this->session->userdata('id');
        }
        $q = $this->db->get_where('pos_register', array('user_id' => $user_id, 'status' => 'open'), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
  /*  public function closeRegister($rid, $user_id, $data)
    {
        if (!$rid) {
            $rid = $this->session->userdata('register_id');
        }
        if (!$user_id) {
            $user_id = $this->session->userdata('user_id');
        }
        if ($data['transfer_opened_bills'] == -1) {
            $this->db->delete('suspended_bills', array('created_by' => $user_id));
        } elseif ($data['transfer_opened_bills'] != 0) {
            $this->db->update('suspended_bills', array('created_by' => $data['transfer_opened_bills']), array('created_by' => $user_id));
        }
        if ($this->db->update('pos_register', $data, array('id' => $rid, 'user_id' => $user_id))) {
            return true;
        }
        return FALSE;
    }*/
    
   public function updateSale($id, $data, $items = array())
    {
        $this->resetSaleActions($id, FALSE, TRUE);

        if ($data['sale_status'] == 'Completed') {
            $cost = $this->costing($items);
        }

         //$this->sma->print_arrays($cost);

        if ($this->db->update('sales', $data, array('id' => $id)) &&
            $this->db->delete('sale_items', array('sale_id' => $id)) &&
            $this->db->delete('costing', array('sale_id' => $id))) {

            foreach ($items as $item) {

                $item['sale_id'] = $id;
                $this->db->insert('sale_items', $item);
                $sale_item_id = $this->db->insert_id();
                if ($data['sale_status'] == 'Completed' && $this->getProductByID($item['product_id'])) {
                    $item_costs = $this->item_costing($item);
                    foreach ($item_costs as $item_cost) {
                        if (isset($item_cost['date']) || isset($item_cost['pi_overselling'])) {
                            $item_cost['sale_item_id'] = $sale_item_id;
                            $item_cost['sale_id'] = $id;
                            $item_cost['date'] = date('Y-m-d', strtotime($data['date']));
                            if(! isset($item_cost['pi_overselling'])) {
                                $this->db->insert('costing', $item_cost);
                            }
                        } else {
                            foreach ($item_cost as $ic) {
                                $ic['sale_item_id'] = $sale_item_id;
                                $ic['sale_id'] = $id;
                                $item_cost['date'] = date('Y-m-d', strtotime($data['date']));
                                if(! isset($ic['pi_overselling'])) {
                                    $this->db->insert('costing', $ic);
                                }
                            }
                        }
                    }
                }

            }

            if ($data['sale_status'] == 'Completed') {
                $this->syncPurchaseItems($cost);
            }
	   
	   
            $this->syncSalePayments($id);
            $this->syncQuantity($id);
            $sale = $this->getInvoiceByID($id);
            $this->update_award_points($data['grand_total'], $data['customer_id'], $sale->created_by);
            return true;

        }
        return false;
    }
	
	public function resetSaleActions($id, $return_id = NULL, $check_return = NULL)
    {
        if ($sale = $this->getInvoiceByID($id)) {
            
            if ($sale->sale_status == 'Completed') {
                if ($costings = $this->getSaleCosting($id)) {
                    foreach ($costings as $costing) {
                        if ($pi = $this->getPurchaseItemByID($costing->purchase_item_id)) {
                            $this->setPurchaseItem(['id' => $pi->id, 'product_id' => $pi->product_id, 'option_id' => $pi->option_id], $costing->quantity);
                        }
                    }
                }
                $items = $this->getAllInvoiceItems($id);
                $this->syncQuantity(NULL, NULL, $items);
                $this->update_award_points($sale->grand_total, $sale->customer_id, $sale->created_by, TRUE);
                return $items;
            }
        }
    }
	public function getSaleCosting($sale_id)
    {
        $q = $this->db->get_where('costing', array('sale_id' => $sale_id));
        if ($q->num_rows() > 0) {
            foreach (($q->result()) as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return FALSE;
    }
	public function getPurchaseItemByID($id)
    {
        $q = $this->db->get_where('purchase_items', array('id' => $id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
	public function setPurchaseItem($clause, $qty) {//print_r($qty);die();
        if ($product = $this->getProductByID($clause['product_id'])) {
            if ($pi = $this->getPurchasedItem($clause)) {
                $quantity_balance = $pi->quantity_balance+$qty;
                return $this->db->update('purchase_items', array('quantity_balance' => $quantity_balance), array('id' => $pi->id));
            } else {
                $unit = $this->getUnitByID($product->unit);
                $clause['product_unit_id'] = $product->unit;
                $clause['product_unit_code'] = $unit->code;
                $clause['product_code'] = $product->code;
                $clause['product_name'] = $product->name;
                $clause['purchase_id'] = $clause['transfer_id'] = $clause['item_tax'] = NULL;
                $clause['net_unit_cost'] = $clause['real_unit_cost'] = $clause['unit_cost'] = $product->cost;
                $clause['quantity_balance'] = $clause['quantity'] = $clause['unit_quantity'] = $clause['quantity_received'] = $qty;
                $clause['subtotal'] = ($product->cost * $qty);
                if (isset($product->tax_rate) && $product->tax_rate != 0) {
                    $tax_details = $this->getTaxRateByID($product->tax_rate);
                    $ctax = $this->calculateTax($product, $tax_details, $product->cost);
                    $item_tax = $clause['item_tax'] = $ctax['amount'];
                    $tax = $clause['tax'] = $ctax['tax'];
                    $clause['tax_rate_id'] = $tax_details->id;
                    if ($product->tax_method != 1) {
                        $clause['net_unit_cost'] = $product->cost - $item_tax;
                        $clause['unit_cost'] = $product->cost;
                    } else {
                        $clause['net_unit_cost'] = $product->cost;
                        $clause['unit_cost'] = $product->cost + $item_tax;
                    }
                    $pr_item_tax = $this->formatDecimal($item_tax * $clause['unit_quantity'], 4);
                    if ($this->Settings->indian_gst && $gst_data = $this->gst->calculteIndianGST($pr_item_tax, ($this->Settings->state == $supplier_details->state), $tax_details)) {
                        $clause['gst'] = $gst_data['gst'];
                        $clause['cgst'] = $gst_data['cgst'];
                        $clause['sgst'] = $gst_data['sgst'];
                        $clause['igst'] = $gst_data['igst'];
                    }
                    $clause['subtotal'] = (($clause['net_unit_cost'] * $clause['unit_quantity']) + $pr_item_tax);
                }
                $clause['status'] = 'received';
                $clause['date'] = date('Y-m-d');
                $clause['option_id'] = !empty($clause['option_id']) && is_numeric($clause['option_id']) ? $clause['option_id'] : NULL;
                return $this->db->insert('purchase_items', $clause);
            }
        }
        return FALSE;
    }
 public function getAllInvoiceItems($sale_id, $return_id = NULL)
    {
        $this->db->select('sale_items.*, tax_rates.code as tax_code, tax_rates.name as tax_name, tax_rates.rate as tax_rate, products.image, products.details as details, product_variants.name as variant, products.hsn_code as hsn_code, products.second_name as second_name')
            ->join('products', 'products.id=sale_items.product_id', 'left')
            ->join('product_variants', 'product_variants.id=sale_items.option_id', 'left')
            ->join('tax_rates', 'tax_rates.id=sale_items.tax_rate_id', 'left')
            ->group_by('sale_items.id')
            ->order_by('id', 'asc');
        if ($sale_id && !$return_id) {
            $this->db->where('sale_id', $sale_id);
        } elseif ($return_id) {
            $this->db->where('sale_id', $return_id);
        }
        $q = $this->db->get('sale_items');
        if ($q->num_rows() > 0) {
            foreach (($q->result()) as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return FALSE;
    }

    public function update_award_points($total, $customer, $user = NULL, $scope = null)
    {
        if (!empty($this->Settings->each_spent) && $total >= $this->Settings->each_spent) {
            $company = $this->getCompanyByID($customer);
            $points = floor(($total / $this->Settings->each_spent) * $this->Settings->ca_point);
            $total_points = $scope ? $company->award_points - $points : $company->award_points + $points;
            $this->db->update('companies', array('award_points' => $total_points), array('id' => $customer));
        }
        if ($user && !empty($this->Settings->each_sale) && !$this->Customer && $total >= $this->Settings->each_sale) {
            $staff = $this->getUser($user);
            $points = floor(($total / $this->Settings->each_sale) * $this->Settings->sa_point);
            $total_points = $scope ? $staff->award_points - $points : $staff->award_points + $points;
            $this->db->update('users', array('award_points' => $total_points), array('id' => $user));
        }
        return true;
    }
 public function getPurchasedItem($clause) {
        $orderby = ($this->Settings->accounting_method == 1) ? 'asc' : 'desc';
        $this->db->order_by('date', $orderby);
        $this->db->order_by('purchase_id', $orderby);
        if (!isset($clause['option_id']) || empty($clause['option_id'])) {
            $this->db->group_start()->where('option_id', NULL)->or_where('option_id', 0)->group_end();
        }
        $q = $this->db->get_where('purchase_items', $clause);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    } 
    
     public function getSearch($search,$date,$credit,$warehouse_id)
    { $response = array();
    if(!empty($search) && !empty($date)){
        	$this->db->select('*');
        	$this->db->from('sales');
        	$this->db->order_by("id", "desc");
        	
     		$this->db->like('date',$date,'both');
     		 $this->db->like('customer', $search,'both');
       		//$this->db->like('customer',$search);
 if($credit =="true"){
            $paid = "paid";
             $this->db->where('payment_status !=',$paid);
        }
$query = $this->db->get();
        
        return $query->result();
    }
    if(!empty($search)&& empty($date))
    {
    	/* $this->db->select('*');
        $this->db->from('sales');
      $this->db->where(array('customer' => $search));
      //  $this->db->or_like(array('date' => $date, 'reference_no' => $search,'customer' => $search, 'biller' => $search,'grand_total' => $search, 'sale_status' => $search, 'payment_status' => $search,'paid' => $search));
        $query = $this->db->get();
        return $query->result();*/
         $this->db->select('*');
    $this->db->from('sales');   
      $this->db->order_by("id", "desc");
    $this->db->like('customer', $search,'both');
     $this->db->where(array('biller_id' => $warehouse_id));
      if($credit =="true"){
            $paid = "paid";
             $this->db->where('payment_status !=',$paid);
        }
   // $this->db->like('title', 'match', 'both'); 
   // return $this->db->get()->result();
   $query = $this->db->get();
        foreach($query->result() as $row){
        $prouduct = $this->db->get_where('sale_items',array('sale_id'=>$row->id))->result_array();
        	$payment_by =$this->db->get_where('payments',array('sale_id'=>$row->id))->result_array();
    		
    		if(!empty($payment_by)){
    		   // print_r($payment_by);die();
    		   if(count($payment_by) > 1) {
    		       
    		       $paid_by = $this->db->get_where('payments',array('sale_id'=>$row->id))->row()->paid_by;
    		   }
    		   else{
    		        $paid_by = $this->db->get_where('payments',array('sale_id'=>$row->id))->row()->paid_by;
    		        
    		   }
    		}
    			 $products = array();
               	 foreach($prouduct as $rows){
               	
               	 
               	  $prod = array(
                         			'sale_item_id'			=> $rows['id'],
						'sale_id'			=> $rows['sale_id'],
						'product_id'			=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'				=> $rows['item_tax'],
						'tax_rate'			=> $rows['tax_rate_id'],
				// 		'tax'				=> $rows['tax'],
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=> $rows['real_unit_price'],
						'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
						'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $products[]= $prod;
                          if(!empty($rows['sale_id'])){
                          $url = 'http://printsa.cignestrade.com/welcome/'.$rows['sale_id'].'';
                          }
                          else{
                          $url='';
                          }
                          }
                         $customer_id= $row->customer_id;
                         $biller_id= $row->biller_id;
                         $warehouse_id=$row->warehouse_id;
                           $company=$this->db->get_where('companies', array('id' => $customer_id))->row()->company;
                          $vat=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->vat_no;
                          $address=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->address;
                          $city=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->city;
                          $state=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->state;
                          $postal_code=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->postal_code;
                          $country=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->country;
                          $phone=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->phone;
                          $email=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->email;
                           $biller = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->name;
                            $biller_company = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->company;
                            $biller_vat = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->vat_no;
                            $biller_address=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->address;
                         $biller_city=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->city;
                         $biller_state=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->state;
                         $biller_postal_code=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->postal_code;
                         $biller_country=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->country;
                         $biller_phone=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->phone;
                          $biller_email=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->email;
                           
                           $biller_warehouse_id = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->warehouse_id;
                           
                           if($warehouse_id == $biller_warehouse_id ){
                            $first_name = $this->db->get_where('users', array('warehouse_id' => $warehouse_id))->row()->first_name;
                             $last_name = $this->db->get_where('users', array('warehouse_id' =>$warehouse_id))->row()->last_name;
                             $sale = $first_name." ".$last_name;
                           }
                           else{
                                 $sale ='Admin';
                           }
        $data = array(
                        			'id' 				=> $row->id,
						'date'				=> $row->date,
						'reference_no'			=> $row->reference_no,
						'sale_associate' =>$sale,
						//'reference_no'			=> $row->reference_no,
						'dummy_reference'=>$row->dummy_reference,
						'customer_id'			=> $row->customer_id,
						'customer'			=> $row->customer,
						'company'		=> $biller_company,
						'vat'			=> $vat,
						'vat_number'    =>$biller_vat,
						'address'		=> $address,
						'city'			=> $city,
						'state'			=> $state,
						'postal_code'	=> $postal_code,
						'country'		=> $country,
						'phone'			=> $phone,
						'email'			=> $email,
						'biller_id'			=> $row->biller_id,
						'biller'			=> $biller,
						'biller_address'		=> $biller_address,
						'biller_city'			=> $biller_city,
						'biller_state'			=> $biller_state,
						'biller_postal_code'	=> $biller_postal_code,
						'biller_country'		=> $biller_country,
						'biller_phone'			=> $biller_phone,
						'biller_email'			=> $biller_email,
						'paid_by'=>!empty($paid_by)?$paid_by:'',
						'warehouse_id'			=> $row->warehouse_id,
						'note'				=> $row->note,
						'staff_note'			=> $row->staff_note,
						'total'				=> $row->total,
						'product_discount'		=> $row->product_discount,
						'order_discount_id'		=> $row->order_discount_id,
						'total_discount'		=> $row->total_discount,
						'order_discount'		=> $row->order_discount,
						'product_tax'			=> $row->product_tax,
						'order_tax_id'			=> $row->order_tax_id,
						'order_tax'			=> $row->order_tax,
						'total_tax'			=> $row->total_tax,
						'shipping'			=> $row->shipping,
						'grand_total'			=> $row->grand_total,
						'sale_status'			=> $row->sale_status,
						'payment_status'		=> $row->payment_status,
						'payment_term'			=> $row->payment_term,
						'due_date'			=> $row->due_date,
						'created_by'			=> $row->created_by,
						'updated_by'			=> $row->updated_by,
						'updated_at'			=> $row->updated_at,
						'total_items'			=> $row->total_items,
						'pos'				=> $row->pos,
						'paid'				=> $row->paid,
						'return_id'			=> $row->return_id,
						'delete_id'			=> $row->delete_id,
						'surcharge'			=> $row->surcharge,
						'attachment'			=> $row->attachment,
						'return_sale_ref'		=> $row->return_sale_ref,
						'sale_id'			=> $row->sale_id,
						'return_sale_total'		=> $row->return_sale_total,
						'rounding'			=> $row->rounding,
						'suspend_note'			=> $row->suspend_note,
						'api'				=> $row->api,
						'shop'				=> $row->shop,
						'address_id'			=> $row->address_id,
						'reserve_id'			=> $row->reserve_id,
						'hash'				=> $row->hash,
						'manual_payment'		=> $row->manual_payment,
						'cgst'				=> $row->cgst,
						'sgst'				=> $row->sgst,
						'igst'				=> $row->igst,
                       				'product'			=> $products,
                       				'url'				=> $url,
                    );
                $response[] = $data;
        }
        return  $response;
    }
   if(empty($search) && !empty($date))
   {
   	/* $this->db->select('*');
        $this->db->from('sales');
      $this->db->where(array('date' => $date));
      //  $this->db->or_like(array('date' => $date, 'reference_no' => $search,'customer' => $search, 'biller' => $search,'grand_total' => $search, 'sale_status' => $search, 'payment_status' => $search,'paid' => $search));
        $query = $this->db->get();
        return $query->result();*/
         $this->db->select('*'); 
           $this->db->order_by("id", "desc");
    $this->db->from('sales');   
    $this->db->like('date', $date);
       $this->db->where(array('biller_id' => $warehouse_id));
        if($credit =="true"){
            $paid = "paid";
             $this->db->where('payment_status !=',$paid);
        }
    //return $this->db->get()->result();
    $query = $this->db->get();
        foreach($query->result() as $row){
        $prouduct = $this->db->get_where('sale_items',array('sale_id'=>$row->id))->result_array();
        	$payment_by =$this->db->get_where('payments',array('sale_id'=>$row->id))->result_array();
    		
    		if(!empty($payment_by)){
    		   // print_r($payment_by);die();
    		   if(count($payment_by) > 1) {
    		       
    		       $paid_by = $this->db->get_where('payments',array('sale_id'=>$row->id))->row()->paid_by;
    		   }
    		   else{
    		        $paid_by = $this->db->get_where('payments',array('sale_id'=>$row->id))->row()->paid_by;
    		        
    		   }
    		}
    			 $products = array();
               	 foreach($prouduct as $rows){
               	
               	 
               	  $prod = array(
                         			'sale_item_id'			=> $rows['id'],
						'sale_id'			=> $rows['sale_id'],
						'product_id'			=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'				=> $rows['item_tax'],
						'tax_rate'			=> $rows['tax_rate_id'],
				// 		'tax'				=> $rows['tax'],
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=> $rows['real_unit_price'],
						'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
						'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $products[]= $prod;
                          if(!empty($rows['sale_id'])){
                          $url = 'http://printsa.cignestrade.com/welcome/'.$rows['sale_id'].'';
                          }
                          else{
                          $url='';
                          }
                          }
                         $customer_id= $row->customer_id;
                         $biller_id= $row->biller_id;
                         $warehouse_id=$row->warehouse_id;
                           $company=$this->db->get_where('companies', array('id' => $customer_id))->row()->company;
                          $vat=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->vat_no;
                          $address=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->address;
                          $city=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->city;
                          $state=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->state;
                          $postal_code=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->postal_code;
                          $country=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->country;
                          $phone=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->phone;
                          $email=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->email;
                           $biller = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->name;
                            $biller_company = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->company;
                            $biller_vat = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->vat_no;
                            $biller_address=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->address;
                         $biller_city=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->city;
                         $biller_state=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->state;
                         $biller_postal_code=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->postal_code;
                         $biller_country=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->country;
                         $biller_phone=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->phone;
                          $biller_email=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->email;
                           
                           
                            $biller_warehouse_id = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->warehouse_id;
                           
                           if($warehouse_id == $biller_warehouse_id ){
                            $first_name = $this->db->get_where('users', array('warehouse_id' => $warehouse_id))->row()->first_name;
                             $last_name = $this->db->get_where('users', array('warehouse_id' =>$warehouse_id))->row()->last_name;
                             $sale = $first_name." ".$last_name;
                           }
                           else{
                                 $sale ='Admin';
                           }
                             
                             
        $data = array(
                        			'id' 				=> $row->id,
						'date'				=> $row->date,
						'reference_no'			=> $row->reference_no,
						'sale_associate' =>$sale,
						//'reference_no'			=> $row->reference_no,
						'dummy_reference'=>$row->dummy_reference,
						'customer_id'			=> $row->customer_id,
						'customer'			=> $row->customer,
						'company'		=> $biller_company,
						'vat'			=> $vat,
						'vat_number'    =>$biller_vat,
						'address'		=> $address,
						'city'			=> $city,
						'state'			=> $state,
						'postal_code'	=> $postal_code,
						'country'		=> $country,
						'phone'			=> $phone,
						'email'			=> $email,
						'biller_id'			=> $row->biller_id,
						'biller'			=> $biller,
						'biller_address'		=> $biller_address,
						'biller_city'			=> $biller_city,
						'biller_state'			=> $biller_state,
						'biller_postal_code'	=> $biller_postal_code,
						'biller_country'		=> $biller_country,
						'biller_phone'			=> $biller_phone,
						'biller_email'			=> $biller_email,
						'paid_by'=>!empty($paid_by)?$paid_by:'',
						'warehouse_id'			=> $row->warehouse_id,
						'note'				=> $row->note,
						'staff_note'			=> $row->staff_note,
						'total'				=> $row->total,
						'product_discount'		=> $row->product_discount,
						'order_discount_id'		=> $row->order_discount_id,
						'total_discount'		=> $row->total_discount,
						'order_discount'		=> $row->order_discount,
						'product_tax'			=> $row->product_tax,
						'order_tax_id'			=> $row->order_tax_id,
						'order_tax'			=> $row->order_tax,
						'total_tax'			=> $row->total_tax,
						'shipping'			=> $row->shipping,
						'grand_total'			=> $row->grand_total,
						'sale_status'			=> $row->sale_status,
						'payment_status'		=> $row->payment_status,
						'payment_term'			=> $row->payment_term,
						'due_date'			=> $row->due_date,
						'created_by'			=> $row->created_by,
						'updated_by'			=> $row->updated_by,
						'updated_at'			=> $row->updated_at,
						'total_items'			=> $row->total_items,
						'pos'				=> $row->pos,
						'paid'				=> $row->paid,
						'return_id'			=> $row->return_id,
						'delete_id'			=> $row->delete_id,
						'surcharge'			=> $row->surcharge,
						'attachment'			=> $row->attachment,
						'return_sale_ref'		=> $row->return_sale_ref,
						'sale_id'			=> $row->sale_id,
						'return_sale_total'		=> $row->return_sale_total,
						'rounding'			=> $row->rounding,
						'suspend_note'			=> $row->suspend_note,
						'api'				=> $row->api,
						'shop'				=> $row->shop,
						'address_id'			=> $row->address_id,
						'reserve_id'			=> $row->reserve_id,
						'hash'				=> $row->hash,
						'manual_payment'		=> $row->manual_payment,
						'cgst'				=> $row->cgst,
						'sgst'				=> $row->sgst,
						'igst'				=> $row->igst,
                       				'product'			=> $products,
                       				'url'				=> $url,
                    );
                $response[] = $data;
        }
        return  $response;
    }
    
    if(empty($search) && empty($date)){//print_r($warehouse_id);die();
     $this->db->select('*');
     $this->db->order_by("id", "desc");
      $this->db->where('biller_id', $warehouse_id);
        $this->db->from('sales');
        if($credit =="true"){
            $paid = "paid";
             $this->db->where('payment_status !=',$paid);
        }
         // $this->db->get_where('sales',array('warehouse_id'=>$warehouse_id))->result_array();
      //  $this->db->or_like(array('date' => $date, 'reference_no' => $search,'customer' => $search, 'biller' => $search,'grand_total' => $search, 'sale_status' => $search, 'payment_status' => $search,'paid' => $search));
        $query = $this->db->get();
    $this->db->save_queries = TRUE;
$str = $this->db->last_query();
echo $str;
        foreach($query->result() as $row){
        $prouduct = $this->db->get_where('sale_items',array('sale_id'=>$row->id))->result_array();
        $payment_by =$this->db->get_where('payments',array('sale_id'=>$row->id))->result_array();
    		
    		if(!empty($payment_by)){
    		   // print_r($payment_by);die();
    		   if(count($payment_by) > 1) {
    		       
    		       $paid_by = $this->db->get_where('payments',array('sale_id'=>$row->id))->row()->paid_by;
    		   }
    		   else{
    		        $paid_by = $this->db->get_where('payments',array('sale_id'=>$row->id))->row()->paid_by;
    		        
    		   }
    		}
    			 $products = array();
               	 foreach($prouduct as $rows){
               	
               	 
               	  $prod = array(
                         			'sale_item_id'			=> $rows['id'],
						'sale_id'			=> $rows['sale_id'],
						'product_id'			=> $rows['product_id'],
						'code'				=> $rows['product_code'],
						'name'				=> $rows['product_name'],
						'net_unit_price'		=> $rows['net_unit_price'],
						'price'				=> $rows['unit_price'],
						'quantity'			=> $rows['quantity'],
						'warehouse_id'			=> $rows['warehouse_id'],
						'tax'				=> $rows['item_tax'],
						'tax_rate'			=> $rows['tax_rate_id'],
				// 		'tax'				=> $rows['tax'],
						'discount'			=> $rows['discount'],
						'item_discount'			=> $rows['item_discount'],
						'subtotal'			=> $rows['subtotal'],
						'serial_no'			=> $rows['serial_no'],
						'option_id'			=> $rows['option_id'],
						'type'				=> $rows['product_type'],
						'real_unit_price'		=> $rows['real_unit_price'],
						'sale_unit'			=> $rows['product_unit_id'] ?$rows['product_unit_id'] : 25,
						'product_unit_code'		=> $rows['product_unit_code'] ?$rows['product_unit_code'] : 25,
						'unit_quantity'			=> $rows['unit_quantity'],
						'comment'			=> $rows['comment'],
						'gst'				=> $rows['gst'],
						'cgst'				=> $rows['cgst'],
						'sgst'				=> $rows['sgst'],
						'igst'				=> $rows['igst'],
                          
                          );
                          $products[]= $prod;
                          if(!empty($rows['sale_id'])){
                          $url = 'http://printsa.cignestrade.com/welcome/'.$rows['sale_id'].'';
                          }
                          else{
                          $url='';
                          }
                          }
                         //print_r($row->customer_id);die();
                         $customer_id= $row->customer_id;
                         $biller_id= $row->biller_id;
                         $warehouse_id=$row->warehouse_id;
                           $company=$this->db->get_where('companies', array('id' => $customer_id))->row()->company;
                          $vat=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->vat_no;
                          $address=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->address;
                          $city=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->city;
                          $state=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->state;
                          $postal_code=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->postal_code;
                          $country=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->country;
                          $phone=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->phone;
                          $email=$this->db->get_where('companies', array('id' =>  $customer_id))->row()->email;
                           $biller = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->name;
                            $biller_company = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->company;
                            $biller_vat = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->vat_no;
                            $biller_address=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->address;
                         $biller_city=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->city;
                         $biller_state=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->state;
                         $biller_postal_code=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->postal_code;
                         $biller_country=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->country;
                         $biller_phone=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->phone;
                          $biller_email=$this->db->get_where('companies', array('id' =>  $biller_id))->row()->email;
                           
                            $biller_warehouse_id = $this->db->get_where('companies', array('id' =>  $biller_id))->row()->warehouse_id;
                           
                           if($warehouse_id == $biller_warehouse_id ){
                            $first_name = $this->db->get_where('users', array('warehouse_id' => $warehouse_id))->row()->first_name;
                             $last_name = $this->db->get_where('users', array('warehouse_id' =>$warehouse_id))->row()->last_name;
                             $sale = $first_name." ".$last_name;
                           }
                           else{
                                 $sale ='Admin';
                           }
                          
        $data = array(
                        			'saleid' 				=> $row->id,
						'date'				=> $row->date,
						'reference_no'			=> $row->reference_no,
						'sale_associate' =>$sale,
						//'reference_no'			=> $row->reference_no,
						'dummy_reference'=>$row->dummy_reference,
						'customer_id'			=> $row->customer_id,
						'customer'			=> $row->customer,
						'company'		=> $biller_company,
						'vat'			=> $vat,
						'vat_number'    =>$biller_vat,
						'address'		=> $address,
						'city'			=> $city,
						'state'			=> $state,
						'postal_code'	=> $postal_code,
						'country'		=> $country,
						'phone'			=> $phone,
						'email'			=> $email,
						'biller_id'			=> $row->biller_id,
						'biller'			=> $biller,
						'biller_address'		=> $biller_address,
						'biller_city'			=> $biller_city,
						'biller_state'			=> $biller_state,
						'biller_postal_code'	=> $biller_postal_code,
						'biller_country'		=> $biller_country,
						'biller_phone'			=> $biller_phone,
						'biller_email'			=> $biller_email,
						'paid_by'=>!empty($paid_by)?$paid_by:'',
						'warehouse_id'			=> $row->warehouse_id,
						'note'				=> $row->note,
						'staff_note'			=> $row->staff_note,
						'total'				=> $row->total,
						'product_discount'		=> $row->product_discount,
						'order_discount_id'		=> $row->order_discount_id,
						'total_discount'		=> $row->total_discount,
						'order_discount'		=> $row->order_discount,
						'product_tax'			=> $row->product_tax,
						'order_tax_id'			=> $row->order_tax_id,
						'order_tax'			=> $row->order_tax,
						'total_tax'			=> $row->total_tax,
						'shipping'			=> $row->shipping,
						'grand_total'			=> $row->grand_total,
						'sale_status'			=> $row->sale_status,
						'payment_status'		=> $row->payment_status,
						'payment_term'			=> $row->payment_term,
						'due_date'			=> $row->due_date,
						'created_by'			=> $row->created_by,
						'updated_by'			=> $row->updated_by,
						'updated_at'			=> $row->updated_at,
						'total_items'			=> $row->total_items,
						'pos'				=> $row->pos,
						'paid'				=> $row->paid,
						'return_id'			=> $row->return_id,
						'delete_id'			=> $row->delete_id,
						'surcharge'			=> $row->surcharge,
						'attachment'			=> $row->attachment,
						'return_sale_ref'		=> $row->return_sale_ref,
						'sale_id'			=> $row->sale_id,
						'return_sale_total'		=> $row->return_sale_total,
						'rounding'			=> $row->rounding,
						'suspend_note'			=> $row->suspend_note,
						'api'				=> $row->api,
						'shop'				=> $row->shop,
						'address_id'			=> $row->address_id,
						'reserve_id'			=> $row->reserve_id,
						'hash'				=> $row->hash,
						'manual_payment'		=> $row->manual_payment,
						'cgst'				=> $row->cgst,
						'sgst'				=> $row->sgst,
						'igst'				=> $row->igst,
                       				'product'			=> $products,
                       				'url'				=> $url,
                    );
                $response[] = $data;
        }
        return  $response;
    }
    
}
public function paymentAgainstCustomer($id,$amount,$paid_by,$created_by)
    {//echo"1";die();
       if ($id && $amount) 
			{//echo"2";die();
				$date 	= date('Y-m-d H:i:s');
				$this->db->order_by("id", "asc"); 
				$this->db
                        ->select('*')
                        ->from('sales')
                        ->where('customer_id',$id)
                        ->where("(payment_status='pending' OR payment_status='due')", NULL, FALSE);
                        $sale = $this->db->get();
                        //print_r($sale->result());die();
                foreach($sale->result() as $row)
				{
					if($amount !=0)
					{//echo"3";die();
						$paid 			=$row->paid ? $row->paid:'0';
						$grandtotal 	= $row->grand_total;//print_r($payment_status);
						if($grandtotal == $amount)
						{//echo"4";die();
						    $balance 					= $grandtotal - $paid;
							$payment_status 			= 'Paid';
							$sale_status 				= 'completed';
							$paid 						= $paid +  $balance;
							$amount						= $amount - $balance;
							$payment['reference_no'] 	= $this->getReference('pay');
							$warehouse_id 				= $this->db->get_where('sales',array('id'=>$row->id))->row()->warehouse_id;
							$transt =array
							(
								'type'             		=> 'income',
								'account'          		=> '5',
								'category'         		=> '8',
								'date'              	=> $date,
								'amount'            	=> $balance,
								'note'              	=> '',
								'description'       	=> 'Sale',
								'acc_type'          	=> '18',
								'deposit_withdrawal' 	=> 'deposit',
								'sale_id' 				=> $row->id,
								'warehouse_id'			=> $warehouse_id
                             );
                            $paymentt = array
							(
								'date' 			=> $date,
								'reference_no' 	=> $payment['reference_no'],
								'amount' 		=> $balance,
								'paid_by' 		=> $paid_by,
								'cheque_no' 	=> '',
								'cc_no' 		=> '',
								'cc_holder' 	=> '',
								'cc_month' 		=> '',
								'cc_year' 		=> '',
								'cc_type' 		=> '',
								'created_by' 	=> $created_by,
								'note' 			=> '',
								'type' 			=> 'received',
								 'sale_id' 		=> $row->id
							);//print_r($payment);die();
							$dat = array
							(
								'paid'			=>$paid,
								'sale_status'	=> $sale_status,
								'payment_status'=> $payment_status
                            );
                           	if(($this->db->update('sales', $dat, array('id' => $row->id))) )
							{
							   if ($this->db->insert('payments', $paymentt)){
							       $this->db->insert('transaction', $transt);
                         
								$this->updateReference('pay');
							
							   }
                            }
                        } 
                       
                        if($amount > $grandtotal)
						{//echo"5";die();
						//print_r($paid);die();
							$payment_status 			= 'paid';
							$sale_status 				= 'completed';
							$balance 					= $grandtotal - $paid;
							$paid 						= $paid +  $balance;
							$amount						= $amount - $balance;
							$payment['reference_no'] 	= $this->getReference('pay');
							$warehouse_id 				= $this->db->get_where('sales',array('id'=>$row->id))->row()->warehouse_id;
							$da_p =array
							(
								 'paid'				=> $paid,
								 'sale_status'		=> $sale_status,
								 'payment_status'	=> $payment_status
                            );
							$trans_p =array
							(
								'type'             	=> 'income',
								'account'          	=> '5',
								'category'         	=> '8',
								'date'              => $date,
								'amount'            => $balance,
								'note'              => '',
								'description'       => 'Sale',
								'acc_type'          =>  '18',
								'deposit_withdrawal'=> 'deposit',
								'sale_id' 			=> $row->id,
								'warehouse_id'		=> $warehouse_id
                            );
							$payments_p = array
							(
								'date' 			=> $date,
								'reference_no' 	=> $payment['reference_no'],
								'amount' 		=> $balance,
								'paid_by' 		=> $paid_by,
								'cheque_no' 	=> '',
								'cc_no' 		=> '',
								'cc_holder' 	=> '',
								'cc_month' 		=> '',
								'cc_year' 		=> '',
								'cc_type' 		=> '',
								'created_by' 	=> $created_by,
								'note' 			=> '',
								'type' 			=> 'received',
								 'sale_id' 		=> $row->id
                       
							);
							//print_r($row->id);die();
                        // $this->sma->print_arrays($payments_p, $trans, $da);die();
							if(($this->db->update('sales', $da_p, array('id' => $row->id))) )
							{
							   if ($this->db->insert('payments', $payments_p)){
							       $this->db->insert('transaction', $trans_p);
                         
								$this->updateReference('pay');
							
							   }
                            }
                        } 
                        if($amount < $grandtotal)
						{//echo"6";die();
							//print_r($paid);die();
							$balance = $grandtotal;
							if($amount == $balance)
							{//echo"6a";die();
								$payment_status 		= 'Paid';
								$sale_status 			= 'completed';
								$paid 					= $paid + $amount;
								$amount					=  0;
								$balance                =   $grandtotal - $paid;
								$payment['reference_no']= $this->getReference('pay');
								$warehouse_id 			= $this->db->get_where('sales',array('id'=>$row->id))->row()->warehouse_id;
								$das =array
								(
									 'paid'				=> $paid,
									 'sale_status'		=> $sale_status,
									 'payment_status'	=> 'Paid'
								);
								$transs =array
								(
									'type'             	=> 'income',
									'account'          	=> '5',
									'category'         	=> '8',
									'date'              => $date,
									'amount'            => $balance,
									'note'              => '',
									'description'       => 'Sale',
									'acc_type'          => '18',
									'deposit_withdrawal'=> 'deposit',
									'sale_id' 			=> $row->id,
									'warehouse_id'		=> $warehouse_id
								);
								$payments = array
								(
									'date' 			=> $date,
									'reference_no' 	=> $payment['reference_no'],
									'amount' 		=> $balance,
									'paid_by' 		=> $paid_by,
									'cheque_no' 	=> '',
									'cc_no' 		=> '',
									'cc_holder' 	=> '',
									'cc_month' 		=> '',
									'cc_year' 		=> '',
									'cc_type' 		=> '',
									'created_by' 	=> $created_by,
									'note' 			=> '',
									'type' 			=> 'received',
									'sale_id' 		=> $row->id
								);
								if(($this->db->update('sales', $das, array('id' => $row->id))) )
							{
							   if ($this->db->insert('payments', $payments)){
							       $this->db->insert('transaction', $transs);
                         
								$this->updateReference('pay');
							
							   }
                            }
							} 
							if($amount < $balance)
							{//echo"7";die();
								$payment_status 			= 'Paid';
								$sale_status 				= 'completed';
								$paid 						= $paid + $amount;
								$amount						=  0;
								$balance                =   $grandtotal - $paid;
								$payment['reference_no'] 	= $this->getReference('pay');
								$warehouse_id 				= $this->db->get_where('sales',array('id'=>$row->id))->row()->warehouse_id;
								$daq =array
								(
								 'paid'				=> $paid,
								 'sale_status'		=> $sale_status,
								 'payment_status'	=> 'due'
								);
								$transq =array
								(
									'type'             	=> 'income',
									'account'          	=> '5',
									'category'         	=> '8',
									'date'              => $date,
									'amount'            => $balance,
									'note'              => '',
									'description'       => 'Sale',
									'acc_type'          => '18',
									'deposit_withdrawal'=> 'deposit',
									'sale_id' 			=> $row->id,
									'warehouse_id'		=> $warehouse_id
                                );
								$paymentq = array
								(
									'date' 			=> $date,
									'reference_no' 	=> $payment['reference_no'],
									'amount' 		=> $balance,
									'paid_by' 		=> $paid_by,
									'cheque_no' 	=> '',
									'cc_no' 		=> '',
									'cc_holder' 	=> '',
									'cc_month' 		=> '',
									'cc_year' 		=> '',
									'cc_type' 		=> '',
									'created_by' 	=> $created_by,
									'note' 			=> '',
									'type' 			=> 'received',
									'sale_id' 		=> $row->id
                       
								);  
									if(($this->db->update('sales', $daq, array('id' => $row->id))) )
							{
							   if ($this->db->insert('payments', $paymentq)){
							       $this->db->insert('transaction', $transq);
                         
								$this->updateReference('pay');
							
							   }
                            }
							} 
							if($amount > $balance)
							{//echo"8";die();
								$payment_status = 'Paid';
								$sale_status = 'completed';
								$balance                =   $grandtotal - $paid;
								$paid = $paid +  $balance;
								$amount= $amount -  $balance ;
								$payment['reference_no'] = $this->getReference('pay');
								$warehouse_id 				= $this->db->get_where('sales',array('id'=>$row->id))->row()->warehouse_id;
								$dar =array
								(
									'paid'=>$paid,
									'sale_status'=> $sale_status,
									'payment_status'=> 'Paid'
								);
								$transr =array
								(
									'type'             	=>'income',
									'account'          	=>'5',
									'category'         	=>'8',
									'date'              =>$date,
									'amount'            =>$balance,
									'note'              => '',
									'description'       => 'Sale',
									'acc_type'          =>  '18',
									'deposit_withdrawal'=> 'deposit',
									'sale_id' 			=> $row->id,
									'warehouse_id'		=>$warehouse_id
								);
								$paymentr = array
								(
									'date' 			=> $date,
									'reference_no' 	=> $payment['reference_no'],
									'amount' 		=> $balance,
									'paid_by' 		=> $paid_by,
									'cheque_no' 	=> '',
									'cc_no' 		=> '',
									'cc_holder' 	=> '',
									'cc_month' 		=> '',
									'cc_year' 		=> '',
									'cc_type' 		=> '',
									'created_by' 	=> $created_by,
									'note' 			=> '',
									'type' 			=> 'received',
									'sale_id' 		=> $row->id
                       
								);
								if(($this->db->update('sales', $dar, array('id' => $row->id))) )
							{
							   if ($this->db->insert('payments', $paymentr)){
							       $this->db->insert('transaction', $transr);
                         
								$this->updateReference('pay');
							
							   }
                            }
							} 
                   
                        }
                         
                    }
                       
                }//die();
            
            return true;
        }
        return false;
    }


}

?>
