<?php

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

require APPPATH . '/libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;

class Example extends REST_Controller 
{

    public function __construct() 
    {
        parent::__construct();
        $this->load->library('session');
        $this->Settings = $this->get_setting();
         $this->pos_settings = $this->getSetting();
        $this->load->model('user');
        // $this->load->model('site');
        $this->load->library('ion_auth');
        $this->hash_method = $this->config->item('hash_method', 'ion_auth');
        $this->store_salt = $this->config->item('store_salt', 'ion_auth');
         $this->salt_length = $this->config->item('salt_length', 'ion_auth');
        $this->join = $this->config->item('join', 'ion_auth');
    }
   

/*****************************************LOGIN********************************/
   public function login_post() 
    {
        $email      = $this->post('email');//print_r($email);die();
        $password   = $this->post('password');
        $salt = NULL;
        $query    = $this->db->get_where('users', array('username' => $email));
        $user       = $query->row();//print_r($user->id);die();
       if(($user->id) =='1'){
        
           $this->response([
           'url' =>'http://sa.cignestrade.com/admin',
                    'status' => FALSE,
                    'message' => 'provide email and password.'
                    ], REST_Controller::HTTP_OK);
       }
       else{
        if(!empty($user))
        {
        	$pass   = $this->hash_password_db($user->id, $password);
        	
        }
        else
        {
         	$this->response([
                    'status' => FALSE,
                    'message' => 'Username wrong .'
                    ], REST_Controller::HTTP_OK);
        }
        
     	if(!empty($email) && !empty($pass))
        {
            $login = $this->user->getloginRows($email,$pass);
            if(!empty($login))
            {
            	if ($register = $this->user->registerData($login['id']))
             	{
	            $register_data = array('register_id' => $register->id, 'cash_in_hand' => $register->cash_in_hand, 'register_open_time' => $register->date);
	            $this->session->set_userdata($register_data);
           
            	}
          	else
          	{
          		$register_data = array('register_id' => 0, 'cash_in_hand' => 0, 'register_open_time' => 0);
            		$this->session->set_userdata($register_data);
          	}
            	$data = array(
            	
		            	'identity' 		=> $login['username'],
		            	'username'		=> $login['username'],
		            	'email'			=> $login['email'],
		            	'user_id'		=> $login['id'],
		            	'old_last_login'	=> $login['last_login'],
		            	'last_ip'		=> $login['last_ip_address'],
		            	'avatar'		=> $login['avatar'],
		            	'gender'		=> $login['gender'],
				'group_id'		=> $login['group_id'],
		            	'warehouse_id'		=> $login['warehouse_id'],
				'view_right'		=> $login['view_right'],
				'edit_right'		=> $login['edit_right'],
				'allow_discount'	=> $login['allow_discount'],
				'biller_id'		=> $login['biller_id'],
				'company_id'		=> $login['company_id'],
				'show_cost'		=> $login['show_cost'],
				'show_price'		=> $login['show_price'],
				
            	
            	);
            	$first_name = $this->db->get_where('users', array('warehouse_id' =>$login['warehouse_id']))->row()->first_name;
                $last_name = $this->db->get_where('users', array('warehouse_id' =>$login['warehouse_id']))->row()->last_name;
                $sale = $first_name." ".$last_name;
            	 $biller_details 	= $this->getCompanyByID($login['biller_id']);
            	  $biller_details->sale_associate = $sale;
            	  	 $biller_details->arabic_biller_company =$biller_details->cf1;
            	  	 	 $biller_details->arabic_biller_address =$biller_details->cf2;
            	  	 	  $biller_details->arabic_biller_city =$biller_details->cf3;
            	  	 	   $biller_details->arabic_biller_state =$biller_details->cf4;
            	  	 	    $biller_details->arabic_biller_country =$biller_details->cf5;
            	 $id = $biller_details->id;
            	 
               
            $last_reference_number =$this->user->getLastReference($id);//print_r($last_reference_number);die();
            $last_dummy_reference =  $this->user->getDummyReference($id);  //print_r($last_dummy_reference);die();
            $last_reference =  $this->user->getReference('so');
            	 $log = "http://alassi.cignestradeez.com/assets/uploads/logos/";
            	 $biller_details->log = "http://offline.cignestradeez.com/assets/uploads/logos/".$biller_details->logo."";
            	 //print_r($login);die();
            	$this->session->set_userdata($data);
            	if($last_reference_number != "no sales"){
            	    if($last_dummy_reference == NULL){
            	        $last_dummy_reference = "SALE/POS0000/$id";
            	    }
                $this->response([
                    'array' => $login,
                    'biller'=>$biller_details,
                    'last_reference_number'=>$last_reference_number,
                    'last_dummy_reference'=> $last_dummy_reference,
                    'session'=>$this->session->userdata(),
                    'status' => TRUE,
                    'message' => 'User login successful.'
                    ], REST_Controller::HTTP_OK);
            	}
            	else{
            	    $last_reference_number = "SALE/POS0000/$id";
            	    if($last_dummy_reference == NULL){
            	        $last_dummy_reference = "SALE/POS0000/$id";
            	    }
            	    $this->response([
                    'array' => $login,
                    'biller'=>$biller_details,
                    'last_reference_number'=>$last_reference_number,
                    'last_dummy_reference'=> $last_dummy_reference,
                    'session'=>$this->session->userdata(),
                    'status' => TRUE,
                    'message' => 'User login successful.'
                    ], REST_Controller::HTTP_OK);
            	}
            }
            else
            {
                
                $this->response([
                    'status' => FALSE,
                    'message' => 'Wrong email or password .'
                    ], REST_Controller::HTTP_OK);
            }
        }
        else
        {
          
           $this->response([
                    'status' => FALSE,
                    'message' => 'provide email and password.'
                    ], REST_Controller::HTTP_OK);
        }
        }
    }
    

    public function logout_post()
    {
    $identity = $this->post('username');
        $this->session->unset_userdata(array($identity => '', 'id' => '', 'user_id' => ''));
	session_destroy();
            	// $this->session->set_userdata($login->id);
                $this->response([
                    
                    'status' => TRUE,
                    'message' => 'User logout successful.'
                    ], REST_Controller::HTTP_OK);
            
           
    }
    
    
    public function map_post()
    {
        $user_id= $this->post('userid');
        $longitude= $this->post('longitude');
        $lattitude= $this->post('lattitude');
        $date = $date = date('Y-m-d H:i:s');
        $data = array (
        'date'=>$date,
        'userid' =>$user_id,
        'longitude'=>$longitude,
        'lattitude'=>$lattitude
        );
        $map = $this->user->mapPost($data);
        If($map){
        $this->response([
        'status'=>TRUE,
        'message'=>'location insert successfully'
        ],REST_Controller::HTTP_OK);
        }
        else{
        $this->response([
        'status'=>FALSE,
        'message'=>'location insert not successfully'
        ],REST_Controller::HTTP_OK);
        }
    }
    
    
    
    
     public function session_post()
      {//print_r($this->session->userdata());die();
      $id = $this->post('id');
    $user_id = $this->post('user_id');
    if(!empty($user_id)){
   if($user_id ==  $id)
        {
        	
            $this->response( ['user_id' =>  $user_id, 
            'session' =>$this->session->userdata(), 'message' => 'already logged in.','status' => TRUE], REST_Controller::HTTP_OK);
        }
        
        else
        {
          
            $this->response([
                'status' => FALSE,
                'message' => 'No user were logged in.'
            ], REST_Controller::HTTP_OK);
        }
        }
        else
        {
          
            $this->response([
                'status' => FALSE,
                'message' => 'No user were logged in.'
            ], REST_Controller::HTTP_OK);
        }
    }
    
     public function reference_post()
    {
    $field = $this->post('field');
    $val = $this->user->getReference($field);
      if(!empty($val))
        {
            
            $this->response($val, REST_Controller::HTTP_OK);
        }
        else
        {
          
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
    
    public function search_post()
    {
    	$search= $this->post('search');
    	$date = $this->post('date');
    	$credit =$this->post('is_credit');
    	$warehouse_id =$this->post('biller_id');
    	$val = $this->user->getSearch($search,$date,$credit,$warehouse_id);
      	if(!empty($val))
        {
            
            $this->response($val, REST_Controller::HTTP_OK);
        }
        else
        {
          
            $this->response([
                'status' => FALSE,
                'message' => 'No data were found.'
            ], REST_Controller::HTTP_OK);
        }
    }
    
    
/**************************************LIST OF USERS****************************/    
    
   public function user_get($id = 0) 
   {
        
        $users = $this->user->getuser($id);

        if(!empty($users))
        {
            
            $this->response($users, REST_Controller::HTTP_OK);
        }
        else
        {
          
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_OK);
        }
    }

/*****************************LIST OF PRODUCT**********************************/
    
    public function productview_post() 
    {
    	$id = $this->post('warehouse_id');
       $products = $this->user->getproduct($id);
       if(!empty($products))
       {
            $this->response($products, REST_Controller::HTTP_OK);
       }
       else
       {
            $this->response([
                'status' => FALSE,
                'message' => 'No product were found.'
            ], REST_Controller::HTTP_OK);
       }
    }
    
/****************************LIST OF BRAND*************************************/

    public function brandview_get($id = 0) 
    {
        $brands = $this->user->getbrand($id);
        if(!empty($brands))
        {
            $this->response($brands, REST_Controller::HTTP_OK);
        }
        else
        {
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }

/**************************LIST OF CUSTOMER GROUP******************************/    
    
    public function customergroup_get($id = 0) 
    {
        $group = $this->user->getgroup($id);
        if(!empty($group))
        {
            //set the response and exit
            $this->response($group, REST_Controller::HTTP_OK);
        }
        else
        {
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
 public function reportrview_post() 
    {
        $id = $this->post('id');
        $companies = $this->user->getReport($id);//print_r($companies);
        if(!empty($companies))
        {
            $this->response($companies, REST_Controller::HTTP_OK);
        }
        else
        {
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_OK);
        }
    }


/********************** Register*************************************/

 public function registeropen_get() 
    {
        
        $groups = $this->user->getregisterpos();
        if(!empty($groups))
        {
             $this->response($groups, REST_Controller::HTTP_OK);
        }
        else
        {
             $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
 

/**********************LIST OF PRICE GROUP*************************************/

 public function pricegroup_get($id = 0) 
    {
        
        $groups = $this->user->getpricegroup($id);
        if(!empty($groups))
        {
             $this->response($groups, REST_Controller::HTTP_OK);
        }
        else
        {
             $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
    
/*************************LIST OF CATEGORIES*********************************************/

    public function categoriesview_get($id = 0) 
    {
        
        $categorie = $this->user->getcategories($id);
        if(!empty($categorie))
        {
            $this->response($categorie, REST_Controller::HTTP_OK);
        }
        else
        {
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
    
/********************************LIST OF CUSTOMER******************************/
    
    public function companiesview_post($id = 0) 
    {
        $id      = $this->post('warehouse');
        $companies = $this->user->getcompaines($id);
        if(!empty($companies))
        {
        //print_r($companies[0]['id']);die();
        //print_r(sizeof($companies));die();
      
              $this->response($companies, REST_Controller::HTTP_OK);
        }
        else
        {
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
     public function companiescreditview_post() 
    {
         $id      = $this->post('id');
         $paid=$grandtotal=$gran=$pid=0;
         $tot_credit =0;
        $companies = $this->user->getcompaines($id);
        if(!empty($companies))
        {
           $credit = $this->db->get_where('sales', array('customer_id' =>$id))->result_array();//print_r($credit);die();
           $paid=$grandtotal=$gran=$pid=0;
         $tot_credit =0;
         if($credit){
            foreach($credit as $row){
                if($row['payment_status'] != "paid"){
                $paid += $row['paid'];
                $grandtotal += $row['grand_total'];
                $pid +=$paid;
                $tot_credit = $grandtotal  - $paid;//print_r($row['paid']);
                $tat_com = $this->user->formatDecimal($tot_credit);
                 $companies['credit_balance']= "$tat_com";
                }
            }//die();
        }
        else{
            $companies['credit_balance']= "0"; 
        }
           // print_r($companies);die();
            $this->response($companies, REST_Controller::HTTP_OK);
        }
        else
        {
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
    
    public function billerview_get($id = 0) 
    {
        
        $companies = $this->user->getbiller($id);//print_r($companies);
        if(!empty($companies))
        {
            $this->response($companies, REST_Controller::HTTP_OK);
        }
        else
        {
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_OK);
        }
    }


/******************************UPDATE CUSTOMER DETAILS*************************/

    public function companiesupdate_post() 
    {
        $userData       = array();
        $id                             = $this->post('id');
        $userData['name']               = $this->post('name');
        $userData['company']            = $this->post('company');
        $userData['vat_no']             = $this->post('vat_no');
        $userData['customer_group_name']= $this->post('customer_group_name');
        $userData['address']            = $this->post('address');
        $userData['city']               = $this->post('city');
        $userData['state']              = $this->post('state');
        $userData['price_group_name']   = $this->post('price_group_name');
        $userData['postal_code']        = $this->post('postal_code');
        $userData['country']            = $this->post('country');
        $update = $this->user->putcompaines($userData, $id);

            if($update)
            {
                $this->response([
                    'status' => TRUE,
                    'message' => 'User has been updated successfully.'
                ], REST_Controller::HTTP_OK);
            }
            else
            {
                //set the response and exit
                $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
            }
    }
   
/************************************CUSTOMER ADD******************************/
    
    public function addcustomer_post() 
    {
        $userData               = array();
        //$id = '30';//$this->post('id');
        $userData['group_id']               = $this->post('group_id');
        $userData['group_name']             = $this->post('group_name');
        $userData['customer_group_id']      = $this->post('customer_group_id');
        $userData['customer_group_name']    = $this->post('customer_group_name');
        $userData['name']                   = $this->post('company');
        $userData['company']                = $this->post('company');
        $userData['phone']                  = $this->post('phone');
        $userData['email']                  = $this->post('email');
        $userData['vat_no']                 = $this->post('vat_no');
        $userData['address']                = $this->post('address');
        $userData['city']                   = $this->post('city');
        $userData['state']                  = $this->post('state');
        $userData['price_group_name']       = $this->post('price_group_name');
        $userData['postal_code']            = $this->post('postal_code');
        $userData['country']                = $this->post('country');
        $userData['warehouse_id']                = $this->post('warehouse_id');
        $update = $this->user->addcompaines($userData);

        if($update)
        {
            //set the response and exit
            $this->response
            ([
                'status' => TRUE,
                'message' => 'User has been updated successfully.'
             ], REST_Controller::HTTP_OK);
        }
        else
        {
            //set the response and exit
             $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
        }
    }
    
/****************************************LIST OF TOTAL SALES*******************/   
    
    public function viewreceipt_post() 
    {
    $start = $this->post('start');
    $end =$this->post('end');
      $view = $this->user->getview($start,$end);
      if(!empty($view))
      {
            //set the response and exit
            $this->response($view, REST_Controller::HTTP_OK);
      }
      else
      {
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No data were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
      }
      
    }
    
    
     public function viewreceipts_post() 
    {
    $start = $this->post('start');
    $end =$this->post('end');
    $id =$this->post('id');
      $view = $this->user->getviews($start,$end,$id);
      if(!empty($view))
      {
            //set the response and exit
            $this->response($view, REST_Controller::HTTP_OK);
      }
      else
      {
            //set the response and exit
            $this->response([
                'status' => TRUE,
                'message' => 'No data were found.'
            ], REST_Controller::HTTP_OK);
      }
      
    }
    
      public function saleview_post() 
    {
    $s_id = $this->post('sale_id');
    $views = $this->user->getsaleview($s_id);
      if(!empty($views))
      {
            //set the response and exit
            $this->response($views, REST_Controller::HTTP_OK);
      }
      else
      {
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No data were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
      }
      
    }

/*******************************LIST PAYMENTS**********************************/

    public function paymentsview_post($id = 0) 
    {
    	$id = $this->post('id');
        $payments = $this->user->paymentview($id);
        if(!empty($payments))
        {
            $this->response($payments, REST_Controller::HTTP_OK);
        }
        else
        {
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No payments were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
    
/*******************************LIST OF SUSPEND SALE***************************/

    public function suspendView_post() 
    {
        
        $id = $this->post('user_id'); //print_r($id);die();
        //$id = $this->post('biller_id'); 
        $companies = $this->user->getsuspend($id);//print_r($companies);die();
        
      //check if the user data exists
        if(!empty($companies))
        {
            //set the response and exit
            $this->response($companies, REST_Controller::HTTP_OK);
        }
        else
        {
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_OK);
        }
        
    }
    
/******************************SUSPEND SALES***********************************/

    public function suspend_post()
   {
     $userData = array();
     $items=array();
     //$items['id'] ='';// $this->post('id');
     $items['suspend_id'] = '1';//$this->post('suspend_id');
     $items['product_id'] = '73';//$this->post('product_id');
     $items['product_code'] = '45799464';//$this->post('product_code');
     $items['product_name'] ='test';// $this->post('product_name');
     $items['net_unit_price'] ='110.0000';// $this->post('net_unit_price');
     $items['unit_price'] = '115.5000';//$this->post('unit_price');
     $items['quantity'] = '5';//$this->post('quantity');
     $items['warehouse_id'] ='4';// $this->post('warehouse_id');
     $items['item_tax'] = '5.5000';//$this->post('item_tax');
     $items['tax_rate_id'] ='1';// $this->post('tax_rate_id');
     $items['product_type'] ='standard';// $this->post('product_type');
     $items['real_unit_price'] ='33';// $this->post('real_unit_price');
     $items['product_unit_id'] = '33';//$this->post('product_unit_id');
     $items['product_unit_code'] ='33';// $this->post('product_unit_code');
     $items['unit_quantity'] ='33';// $this->post('unit_quantity');

     $userData['id'] = $this->post('id');
     $userData['date'] = $this->post('date');
     $userData['customer_id'] = $this->post('customer_id');
     $userData['customer'] = $this->post('customer');
     $userData['count'] = $this->post('count');
     $userData['order_discount_id'] = $this->post('order_discount_id');
     $userData['order_tax_id'] = $this->post('order_tax_id');
     $userData['total'] = $this->post('total');
     $userData['biller_id'] = $this->post('biller_id');
     $userData['warehouse_id'] = $this->post('warehouse_id');
     $userData['created_by'] = $this->post('created_by');
     $userData['suspend_note'] = $this->post('suspend_note');
     $userData['shipping'] = $this->post('shipping');



       $insert = $this->user->getinsert($userData,$items);

       //check if the user data inserted
       if($insert){
           //set the response and exit
           $this->response([
               'status' => TRUE,
               'message' => 'User has been added successfully.'
           ], REST_Controller::HTTP_OK);
       }else{
           //set the response and exit
           $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
       }
   }
   

/*****************************LIST OF TAX RATES********************************/
   
    public function taxrates_get($id = 0) 
    {
        $taxrates = $this->user->gettaxrates($id);
        if(!empty($taxrates))
        {
            //set the response and exit
            $this->response($taxrates, REST_Controller::HTTP_OK);
        }
        else
        {
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }

/****************************LIST UNITS ***************************************/

     public function units_get($id = 0) 
     {
        $units = $this->user->getunits($id);
        if(!empty($units))
        {
            //set the response and exit
            $this->response($units, REST_Controller::HTTP_OK);
        }
        else
        {
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
    
/**************************LIST OF WAREHOUSES**********************************/    
    
     public function warehouse_get($id = 0) {
        //returns all rows if the id parameter doesn't exist,
        //otherwise single row will be returned
       
        $warehouse = $this->user->getwarehouse($id);

        //check if the user data exists
        if(!empty($warehouse)){
            //set the response and exit
            $this->response($warehouse, REST_Controller::HTTP_OK);
        }else{
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No user were found.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
    }
 
 /********************************PASSWORD CHECK*******************************/
 
public function hash_password($password, $salt = false, $use_sha1_override = FALSE)
    {
        if (empty($password)) 
        {
            return FALSE;
        }

        //bcrypt
      /*  if ($use_sha1_override === FALSE && $this->hash_method == 'bcrypt') 
        {
            return $this->bcrypt->hash($password);
        }
*/

        if ($this->store_salt && $salt) 
        {
            return sha1($password . $salt);
        } else 
        {
            $salt = $this->salt();
            return $salt . substr(sha1($salt . $password), 0, -$this->salt_length);
        }
    }

    public function hash_password_db($id, $password, $use_sha1_override = FALSE)
    {
        if (empty($id) || empty($password)) 
        {
            return FALSE;
        }

        $this->trigger_events('extra_where');
        $query = $this->db->select('password, salt')
            ->where('id', $id)
            ->limit(1)
            ->get('users');

        $hash_password_db = $query->row();
      //  print_r($hash_password_db);die();
       if ($query->num_rows() !== 1) {
            return FALSE;
        }

        // bcrypt
         if ($use_sha1_override === FALSE && $this->hash_method == 'bcrypt') {
            if ($this->bcrypt->verify($password, $hash_password_db->password)) {
                $passw =$this->bcrypt->verify($password, $hash_password_db->password);
                return $passw;
            }

            return FALSE;
        }

        // sha1
           if ($this->store_salt) {
            $db_password = sha1($password . $hash_password_db->salt);
        } else {
            $salt = substr($hash_password_db->password, 0, $this->salt_length);

            $db_password = $salt . substr(sha1($salt . $password), 0, -$this->salt_length);
        }

        if ($db_password == $hash_password_db->password) {
            return $db_password;
        } else {
            return FALSE;
        }
        return $hash_password_db->password;
    }
    

    public function hash_code($password)
    {
        return $this->hash_password($password, FALSE, TRUE);
    }


    public function salt()
    {
        return substr(md5(uniqid(rand(), true)), 0, $this->salt_length);
    }
    
    
    public function trigger_events($events)
    {
        if (is_array($events) && !empty($events)) 
        {
            foreach ($events as $event) 
            {
                $this->trigger_events($event);
            }
        } 
        else 
        {
            if (isset($this->_ion_hooks->$events) && !empty($this->_ion_hooks->$events)) 
            {
                foreach ($this->_ion_hooks->$events as $name => $hook) 
                {
                    $this->_call_hook($events, $name);
                }
            }
        }
    }

/**************************************PARITIAL PAYMENT ***********************/
    public function addpayments_post($id = NULL)
    {
    
        $id = $this->post('sale_id');
	$date = date('Y-m-d H:i:s');
        $sale = $this->user->getInvoiceByID($id);//print_r($sale);die();
        $customer_id = $sale->customer_id;
            $payment = array(
                'date'         => $date,
                'sale_id'      => $id,
                'reference_no' => $this->getReference('pay'),
                'amount'       => $this->post('amount_paid'),
                'paid_by'      => $this->post('paid_by'),
                'cheque_no'    => $this->post('cheque_no'),
                'cc_no'        => $this->post('paid_by') == 'gift_card' ? $this->post('gift_card_no') : $this->post('pcc_no'),
                'cc_holder'    => $this->post('pcc_holder'),
                'cc_month'     => $this->post('pcc_month'),
                'cc_year'      => $this->post('pcc_year'),
                'cc_type'      => $this->post('pcc_type'),
                'cc_cvv2'      => $this->post('pcc_ccv'),
                'note'         => $this->post('note'),
                'created_by'   => $this->post('user_id'),
                'type'         => 'Received',
            );

            
        $msg = $this->user->addPayment($payment, $customer_id);
         if(!empty($msg))
            {
                $this->response([
                    
                    'status' => TRUE,
                    'message' => 'payment Done successfully.'
                    ], REST_Controller::HTTP_OK);
            }
            else
            {
                //set the response and exit
                $this->response("something went wrong.", REST_Controller::HTTP_BAD_REQUEST);
            }    
    }
    
   
   public function editpayment_post($id = null)
    {
          	$id 		= $this->post('id');
          	$sale_id 	= $this->post('sale_id');
		$payment 	= $this->user->getPaymentByID($id);
		$sale 		= $this->user->getInvoiceByID($sale_id);
                $customer_id 	= $sale->customer_id;
               // $amount 	= ($this->post('amount_paid'))-($payment->amount);
                $date 		= date('Y-m-d H:i:s');
            if(!empty($id)){
             $payment = array(
                'date'         => $date,
                'sale_id'      => $sale_id,
                'reference_no' => $this->getReference('pay'),
                'amount'       => $this->post('amount_paid'),
                'paid_by'      => $this->post('paid_by'),
                'cheque_no'    => $this->post('cheque_no'),
                'cc_no'        => $this->post('paid_by') == 'gift_card' ? $this->post('gift_card_no') : $this->post('pcc_no'),
                'cc_holder'    => $this->post('pcc_holder'),
                'cc_month'     => $this->post('pcc_month'),
                'cc_year'      => $this->post('pcc_year'),
                'cc_type'      => $this->post('pcc_type'),
                'cc_cvv2'      => $this->post('pcc_ccv'),
                'note'         => $this->post('note'),
                'created_by'   => $this->post('user_id'),
                'type'         => 'Received',
            );
            }
            else
            {
             $payment = array(
                'date'         => $date,
                'sale_id'      => $sale_id,
                'reference_no' => $this->getReference('pay'),
                'amount'       => $this->post('amount_paid'),
                'paid_by'      => $this->post('paid_by'),
                'cheque_no'    => $this->post('cheque_no'),
                'cc_no'        => $this->post('paid_by') == 'gift_card' ? $this->post('gift_card_no') : $this->post('pcc_no'),
                'cc_holder'    => $this->post('pcc_holder'),
                'cc_month'     => $this->post('pcc_month'),
                'cc_year'      => $this->post('pcc_year'),
                'cc_type'      => $this->post('pcc_type'),
                //'cc_cvv2'      => $this->post('pcc_ccv'),
                'note'         => $this->post('note'),
                'created_by'   => $this->post('user_id'),
                'type'         => 'Received',
            );
}
          $msg = $this->user->updatePayment($id, $payment, $customer_id);
         if(!empty($msg))
            {
                $this->response([
                    
                    'status' => TRUE,
                    'message' => 'payment Done successfully.'
                    ], REST_Controller::HTTP_OK);
            }
            else
            {
                //set the response and exit
                $this->response("something went wrong.", REST_Controller::HTTP_BAD_REQUEST);
            }    
    } 
/*****************************GET REFERENCE NUMBER*****************************/
   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 . '/POS' : '';
                    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;
    }
     


/*******************SYSTEM SETTINGS********************************************/
    public function get_setting() 
    {
        $q = $this->db->get('settings');
        if ($q->num_rows() > 0) 
        {
            return $q->row();
        }
        return FALSE;
    }
/**********************FORMATDECIMAL******************/

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 calculateDiscount($discount = NULL, $amount) {
        if ($discount && $this->Settings->product_discount) {
            $dpos = strpos($discount, '%');
            if ($dpos !== false) {
                $pds = explode("%", $discount);
                return $this->formatDecimal(((($this->formatDecimal($amount)) * (Float) ($pds[0])) / 100), 4);
            } else {
                return $this->formatDecimal($discount, 4);
            }
        }
        return 0;
    }
   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;
    }
    
    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 getUnitByID($id) {
        $q = $this->db->get_where("units", 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;
    }
     public function roundNumber($number, $toref = null)
    {
        switch ($toref) {
            case 1:
                $rn = round($number * 20) / 20;
                break;
            case 2:
                $rn = round($number * 2) / 2;
                break;
            case 3:
                $rn = round($number);
                break;
            case 4:
                $rn = ceil($number);
                break;
            default:
                $rn = $number;
        }
        return $rn;
    }
    public function formatMoney($number, $symnol = NULL)
    {
        $symbol = $symnol ? $symnol : $this->Settings->symbol;
        if ($this->Settings->sac) {
            return ((($this->Settings->display_symbol == 1 || $symbol) && $this->Settings->display_symbol != 2) ? $symbol : '') .
            $this->formatSAC($this->formatDecimal($number)) .
            ($this->Settings->display_symbol == 2 ? $symbol : '');
        }
        $decimals = $this->Settings->decimals;
        $ts = $this->Settings->thousands_sep == '0' ? ' ' : $this->Settings->thousands_sep;
        $ds = $this->Settings->decimals_sep;
        return ((($this->Settings->display_symbol == 1 || $symbol && $number != 0) && $this->Settings->display_symbol != 2) ? $symbol : '') .
        number_format($number, $decimals, $ds, $ts) .
        ($this->Settings->display_symbol == 2 && $number != 0 ? $symbol : '');
    }
     public function makecomma($input)
    {
        if (strlen($input) <= 2) {return $input;}
        $length = substr($input, 0, strlen($input) - 2);
        $formatted_input = $this->makecomma($length) . "," . substr($input, -2);
        return $formatted_input;
    }
    public function formatSAC($num)
    {
        $pos = strpos((string) $num, ".");
        if ($pos === false) {$decimalpart = "00";} else {
            $decimalpart = substr($num, $pos + 1, 2);
            $num = substr($num, 0, $pos);}

        if (strlen($num) > 3 & strlen($num) <= 12) {
            $last3digits = substr($num, -3);
            $numexceptlastdigits = substr($num, 0, -3);
            $formatted = $this->makecomma($numexceptlastdigits);
            $stringtoreturn = $formatted . "," . $last3digits . "." . $decimalpart;
        } elseif (strlen($num) <= 3) {
            $stringtoreturn = $num . "." . $decimalpart;
        } elseif (strlen($num) > 12) {
            $stringtoreturn = number_format($num, 2);
        }

        if (substr($stringtoreturn, 0, 2) == "-,") {$stringtoreturn = "-" . substr($stringtoreturn, 2);}

        return $stringtoreturn;
    }
    
    
  /************************Gift Card********************************/  
    
    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;
    }

/************************************FULL PAYMENT**************************/

	public function full_post($sid = NULL)
    {
    	//print_r( $this->session->userdata());die();
    	$sid 			        = $this->post('suspend_id');//print_r($sid);die();
        $did                    = $this->post('delete_id') ? $this->post('delete_id') : NULL;
        $suspend 		        = $this->post('suspend') ? TRUE : FALSE;
        $date 			        = date('Y-m-d H:i:s');
    	$warehouse_id 		    = $this->post('warehouse');
    	$biller_id 		        = $this->post('biller_id');
    	$customer_id 		    = $this->post('customer_id');
        $total_items 		    = $this->post('total_items');
        $sale_status 		    = 'completed';
        $payment_status 	    = 'due';
        $payment_term 		    = 0;
        $due_date 		        = date('Y-m-d', strtotime('+' . $payment_term . ' days'));
        $shipping 		        = $this->post('shipping') ? $this->post('shipping') : 0;
        $customer_details 	    = $this->getCompanyByID($customer_id);
        $customer 		        = $customer_details->company   ? $customer_details->company : $customer_details->name;
        $biller_details 	    = $this->getCompanyByID($biller_id);
        $biller 		        = $biller_details->company  ? $biller_details->name : $biller_details->name;
        $note 			        = $this->clear_tags($this->post('pos_note'));
        $staff_note 		    = $this->clear_tags($this->post('staff_note'));
        $refer = $this->post('reference')? $this->post('reference'): $this->getReference('pos');
        $reference 		        =  $refer.'/'.$biller_id;
        
        $dummy_reference        =$this->post('dummy_reference');
	    $count 			        = $this->post('count') ? $this->post('count') : NULL;
        $total 			        = 0;
        $product_tax 		    = 0;
        $product_discount 	    = 0;
        $digital 		        = FALSE;
        $pro 		        	= $this->post('product');//print_r($pro);die();
       //	$arr 			= json_decode($pro)
	$total_amt=0;
	$tot_pai=0;
	foreach($pro as  $value)
	{
				
		$item_id 		= $value['product_id'];
		$item_type 		= $value['product_type'];
		$item_code 		= $value['product_code'];
		$item_name 		= $value['product_name'];
		$item_comment 		= $value['comment'];
		$item_option 		= $value['option_id'];
		$real_unit_price 	= $value['real_unit_price'];
		//$rea_price = ($value['unit_price'] * $tax_val)+(100 + $tax_val );
		///$real_unit_price 	= $this->formatDecimal($rea_price);
		$unit_price 		= $value['unit_price'];
		$item_unit_quantity 	= $value['unit_quantity'];
		$item_serial 		= $value['serial_no'];
		$item_tax_rate 		= $value['item_tax'];
		$item_discount 		= $value['item_discount'];
		$item_unit 		= $value['item_unit'];
		$item_quantity 		= $value['quantity'];
		
							
                if (isset($item_code) && isset($real_unit_price) && isset($unit_price) && isset($item_quantity)) 
		{
                    $product_details 	= $item_type != 'manual' ? $this->user->getProductByCode($item_code) : NULL;
                    // $unit_price = $real_unit_price;
                    if ($item_type == 'digital') 
                    {
                        $digital = TRUE;
                    }
                    $pr_discount 	= $this->calculateDiscount($item_discount, $unit_price);
                    $unit_price 	= $this->formatDecimal($unit_price - $pr_discount);
                    $item_net_price 	= $unit_price;
                    $pr_item_discount 	= $this->formatDecimal($pr_discount * $item_unit_quantity);
                    $product_discount 	+= $pr_item_discount;
                    $pr_item_tax 	= $item_tax = 0;
                    $tax 		= "";

                    if (isset($item_tax_rate) && $item_tax_rate != 0) 
                    {

                        $tax_details 	= $this->getTaxRateByID($item_tax_rate);
                        $ctax 		= $this->calculateTax($product_details, $tax_details, $unit_price);
                        $item_tax	= $ctax['amount'];
                        $tax 		= $ctax['tax'];
                        if (!$product_details || (!empty($product_details) && $product_details->tax_method != 1)) 
                        {
                            $item_net_price = $unit_price - $item_tax;
                        }
                        $pr_item_tax	 = $this->formatDecimal(($item_tax * $item_unit_quantity), 4);
                        
                    }

                    $product_tax 	+= $pr_item_tax;
                    $subtotal 		= (($item_net_price * $item_unit_quantity) + $pr_item_tax);
                    $unit 		= $this->site->getUnitByID($item_unit);

                    $product = array(
                        'product_id'      => $item_id,
                        'product_code'    => $item_code,
                        'product_name'    => $item_name,
                        'product_type'    => $item_type,
                        'option_id'       => $item_option,
                        'net_unit_price'  => $item_net_price,
                        'unit_price'      => $this->sma->formatDecimal($item_net_price + $item_tax),
                        'quantity'        => $item_quantity,
                        'product_unit_id' => $unit ? $unit->id : NULL,
                        'product_unit_code' => $unit ? $unit->code : NULL,
                        'unit_quantity'   => $item_unit_quantity,
                        'warehouse_id'    => $warehouse_id,
                        'item_tax'        => $pr_item_tax,
                        'tax_rate_id'     => $item_tax_rate,
                        'tax'             => $tax,
                        'discount'        => $item_discount,
                        'item_discount'   => $pr_item_discount,
                        'subtotal'        => $subtotal,
                        'serial_no'       => $item_serial,
                        'real_unit_price' => $real_unit_price,
                        'comment'         => $item_comment,
                    );

                   $prev_qty = $this->db->get_where('warehouses_products',array('product_id'=>$item_id,'warehouse_id'=>$warehouse_id))->row()->quantity;
                   $cur_qty = $prev_qty - $item_quantity;
                    $daily_products = array(
                        'product_id'      => $item_id,
                        'product_name'    => $item_name,
                        'date'            => $date,
                        'warehouse_id'      => $warehouse_id,
                        'sale_quantity'        => $item_quantity,
                        'previous_stock'=> $prev_qty,
                        'current_stock'=>$cur_qty,
                        
                        );
                          $daily_product[] = $daily_products;
                    $products[] = ($product);
                    $total += $this->formatDecimal(($item_net_price * $item_unit_quantity), 4);
                }
            }//print_r($product);die();
            
            $order_tax 		= $this->post('order_tax');
            $order_discount 	= $this->calculateDiscount($this->post('discount'), ($total + $product_tax));
            $total_discount 	= $this->formatDecimal(($order_discount + $product_discount), 4);
            $order_tax 		= $this->calculateOrderTax($order_tax, ($total + $product_tax - $order_discount));
            $total_tax 		= $this->formatDecimal(($product_tax + $order_tax), 4);
            $grand_total 	= $this->formatDecimal(($total + $total_tax + $this->formatDecimal($shipping) - $order_discount), 4);
            $rounding 		= 0;
            if ($this->pos_settings->rounding) 
            {
                $round_total 	= $this->roundNumber($grand_total, $this->pos_settings->rounding);
                $rounding 	= $this->formatMoney($round_total - $grand_total);
            }
            $data = array('date'    => $date,
                'reference_no'      => $reference,
                'dummy_reference'   =>$dummy_reference,
                'customer_id'       => $customer_id,
                'customer'          => $customer,
                'biller_id'         => $biller_id,
                'biller'            => $biller,
                'warehouse_id'      => $warehouse_id,
                'note'              => $note,
                'staff_note'        => $staff_note,
                'total'             => $total,
                'product_discount'  => $product_discount,
                'order_discount_id' => $this->post('discount'),
                'order_discount'    => $order_discount,
                'total_discount'    => $total_discount,
                'product_tax'       => $product_tax,
                'order_tax_id'      => $this->post('order_tax'),
                'order_tax'         => $order_tax,
                'total_tax'         => $total_tax,
                'shipping'          => $this->formatDecimal($shipping),
                'grand_total'       => $grand_total,
                'total_items'       => $total_items,
                'sale_status'       => $sale_status,
                'payment_status'    => $payment_status,
                'payment_term'      => $payment_term,
                'rounding'          => $rounding,
                'suspend_note'      => $this->post('suspend_note'),
                'pos'               => 1,
                'paid'              => $this->post('amount_paid'),
                'created_by'        => $this->post('created_by'),
                'hash'              => hash('sha256', microtime() . mt_rand()),
                );
            
          if (!$suspend) 
	{
		
		$total_amt 		=$this->post('amount');
		$tot_pai 		= $this->post('amount_paid');
		$balance_amount 	= $total_amt - $tot_pai;
        	//$amount = $this->formatDecimal($tot_pai > 0 ? $this->post('amount') - $tot_pai : $this->post('amount_paid'));//print_r($amount);die();
        	$amount 		= $tot_pai;
        	if ($this->post('paid_by') == 'gift_card') 
		{
            		$gc  		= $this->getGiftCardByNO($this->post('paying_gift_card_no'));
            		$amount_paying 	= $this->post('amount_paid') >= $gc->balance ? $gc->balance : $this->post('amount_paid');
            		$gc_balance 	= $gc->balance - $amount_paying;
           		 $payment[] 	= array(
                                				
                                				
                                				'date'         	=> $date,
                                				'reference_no' 	=> $this->getReference('pay'),
                                				'amount'      	=> $amount,
                                				'paid_by'      	=> $this->post('paid_by'),
								'cheque_no'  	=> $this->post('cheque_no'),
								'cc_no'        	=> $this->post('cc_no'),
								'cc_holder'    	=> $this->post('cc_holder'),
								'cc_month'     	=> $this->post('cc_month'),
								'cc_year'      	=> $this->post('cc_year'),
								'cc_type'      	=> $this->post('cc_type'),
								'cc_cvv2'      	=> $this->post('cc_cvv2'),
								'created_by'   	=> $this->post('created_by'),
								'type'         	=> 'received',
								'note'         	=> $this->post('note'),
								'pos_paid'     	=> $tot_pai,
								'pos_balance'  	=> $balance_amount,
								'gc_balance'  	=> $gc_balance,
                                );

        	} 
		else 
		{
               		$payment[] 	= array(
                               					'date'          => $date,
                             					'reference_no'  => $this->getReference('pay'),
                               					'amount'        => $amount,
                                				'paid_by'      	=> $this->post('paid_by'),
								'cheque_no'  	=> $this->post('cheque_no'),
								'cc_no'        	=> $this->post('cc_no'),
								'cc_holder'    	=> $this->post('cc_holder'),
								'cc_month'     	=> $this->post('cc_month'),
								'cc_year'      	=> $this->post('cc_year'),
								'cc_type'      	=> $this->post('cc_type'),
								'cc_cvv2'      	=> $this->post('cc_cvv2'),
								'created_by'   	=> $this->post('created_by'),
								'type'         	=> 'received',
								'note'         	=> $this->post('note'),
								'pos_paid'     	=>$tot_pai,
								'pos_balance'  	=> $balance_amount,
					);

        	}

    	}
        if (!isset($payment) || empty($payment)) 
        {
                $payment = array();
        }
	//$this->sma->print_arrays($payment, $data, $products);
        if (!empty($products) && !empty($data)) 
        {
		if ($suspend) {
				  if ($this->user->suspendSale($data, $products, $did,$daily_product)) 
				   {
			                $this->response([
			                
			               'status' => TRUE,
			               'message' => 'Sale  has been suspend successfully.'
			          	 ], REST_Controller::HTTP_OK);
			            }
			      }
			      else 
			      {
            			if ($sale = $this->user->addSale($data, $products, $payment, $sid,$daily_product)) 
				{
			                $this->response([
			                'sale_id'=>$sale,
			               'url'=>'http://printsa.cignestrade.com/welcome/'.$sale.'',
			               'status' => TRUE,
			               'message' => 'Sale has been added successfully.'
			           ], REST_Controller::HTTP_OK);
			        }
            
       			      } 
    	}
} 
	
/************************************offline PAYMENT**************************/

	public function offline_post($sid = NULL)
    {
    	//print_r( $this->session->userdata());die();
    	$sid 			= $this->post('suspend_id');//print_r($sid);die();
        $did                	= $this->post('delete_id') ? $this->post('delete_id') : NULL;
        $suspend 		= $this->post('suspend') ? TRUE : FALSE;
        $date 			= date('Y-m-d H:i:s');
        $c_date =date('Y-m-d');
	$warehouse_id 		= $this->post('warehouse');
	$biller_id 		= $this->post('biller_id');
	$customer_id 		= $this->post('customer_id');
        $total_items 		= $this->post('total_items');
        $sale_status 		= 'completed';
        $payment_status 	= 'due';
        $payment_term 		= 0;
        $due_date 		= date('Y-m-d', strtotime('+' . $payment_term . ' days'));
        $shipping 		= $this->post('shipping') ? $this->post('shipping') : 0;
        $customer_details 	= $this->getCompanyByID($customer_id);
        $customer 		= $customer_details->company   ? $customer_details->company : $customer_details->name;
        $biller_details 	= $this->getCompanyByID($biller_id);
        $biller 		= $biller_details->company  ? $biller_details->company : $biller_details->name;
        $note 			= $this->clear_tags($this->post('pos_note'));
        $staff_note 		= $this->clear_tags($this->post('staff_note'));
       $refer =  $this->getReference('so');
        $reference 		=$refer;//$this->post('dummy_reference');
        
        $dummy_reference    =$this->post('dummy_reference');
	$count 			= $this->post('count') ? $this->post('count') : NULL;
        $total 			= 0;
        $product_tax 		= 0;
        $product_discount 	= 0;
        $digital 		= FALSE;
        $pro 			= $this->post('product');//print_r($pro);die();
       //	$arr 			= json_decode($pro)
	$total_amt=0;
	$tot_pai=0;
   
    
	foreach($pro as  $value)
	{
				
		$item_id 		= $value['product_id'];
		$item_type 		= $value['product_type'];
		$item_code 		= $value['product_code'];
		$item_name 		= $value['product_name'];
		$item_comment 		= $value['comment'];
		$item_option 		= $value['option_id'];
		$real_unit_price 	= $value['real_unit_price2'];
		//$rea_price = ($value['unit_price'] * $tax_val)+(100 + $tax_val );
		///$real_unit_price 	= $this->formatDecimal($rea_price);
		$unit_price 		= $value['unit_price'];
		$item_unit_quantity 	= $value['unit_quantity'];
		$item_serial 		= $value['serial_no'];
		$item_tax_rate 		= $value['item_tax'];
		$item_discount 		= $value['item_discount'];
		$item_unit 		= $value['item_unit'];
		$item_quantity 		= $value['quantity'];
		
							
                if (isset($item_code) && isset($real_unit_price) && isset($unit_price) && isset($item_quantity)) 
		{
                    $product_details 	= $item_type != 'manual' ? $this->user->getProductByCode($item_code) : NULL;
                    // $unit_price = $real_unit_price;
                    if ($item_type == 'digital') 
                    {
                        $digital = TRUE;
                    }
                    $pr_discount 	= $this->calculateDiscount($item_discount, $unit_price);
                    $unit_price 	= $this->formatDecimal($unit_price - $pr_discount);
                    $item_net_price 	= $unit_price;
                    $pr_item_discount 	= $this->formatDecimal($pr_discount * $item_unit_quantity);
                    $product_discount 	+= $pr_item_discount;
                    $pr_item_tax 	= $item_tax = 0;
                    $tax 		= "";

                    if (isset($item_tax_rate) && $item_tax_rate != 0) 
                    {

                        $tax_details 	= $this->getTaxRateByID($item_tax_rate);
                        $ctax 		= $this->calculateTax($product_details, $tax_details, $unit_price);
                        $item_tax	= $ctax['amount'];
                        $tax 		= $ctax['tax'];
                        if (!$product_details || (!empty($product_details) && $product_details->tax_method != 1)) 
                        {
                            $item_net_price = $unit_price - $item_tax;
                        }
                        $pr_item_tax	 = $this->formatDecimal(($item_tax * $item_unit_quantity), 4);
                        
                    }

                    $product_tax 	+= $pr_item_tax;
                    $subtotal 		= (($item_net_price * $item_unit_quantity) + $pr_item_tax);
                    $unit 		= $this->site->getUnitByID($item_unit);

                    $product = array(
                        'product_id'      => $item_id,
                        'product_code'    => $item_code,
                        'product_name'    => $item_name,
                        'product_type'    => $item_type,
                        'option_id'       => $item_option,
                        'net_unit_price'  => $item_net_price,
                        'unit_price'      => $this->sma->formatDecimal($item_net_price + $item_tax),
                        'quantity'        => $item_quantity,
                        'product_unit_id' => $unit ? $unit->id : NULL,
                        'product_unit_code' => $unit ? $unit->code : NULL,
                        'unit_quantity'   => $item_unit_quantity,
                        'warehouse_id'    => $warehouse_id,
                        'item_tax'        => $pr_item_tax,
                        'tax_rate_id'     => $item_tax_rate,
                        'tax'             => $tax,
                        'discount'        => $item_discount,
                        'item_discount'   => $pr_item_discount,
                        'subtotal'        => $subtotal,
                        'serial_no'       => $item_serial,
                        'real_unit_price' => $real_unit_price,
                        'comment'         => $item_comment,
                        'product_cost' => $product_details->cost,
                    );
                  
                   
                    $products[] = ($product);
                    $total += $this->formatDecimal(($item_net_price * $item_unit_quantity), 4);
                     $daily_products = array(
                                            'sale_quantity'        => $item_quantity,
                                            'product_id' =>$item_id,
                                            'warehouse_id'=>$warehouse_id,
                                            'compare_date'=>$c_date
                                            );
                     
                    $daily_product[] =$daily_products;
            
                }
            }
            $order_tax 		= $this->post('order_tax');
            $order_discount 	= $this->calculateDiscount($this->post('discount'), ($total + $product_tax));
            $total_discount 	= $this->formatDecimal(($order_discount + $product_discount), 4);
            $order_tax 		= $this->calculateOrderTax($order_tax, ($total + $product_tax - $order_discount));
            $total_tax 		= $this->formatDecimal(($product_tax + $order_tax), 4);
            $grand_total 	= $this->formatDecimal(($total + $total_tax + $this->formatDecimal($shipping) - $order_discount), 4);
            $rounding 		= 0;
            if ($this->pos_settings->rounding) 
            {
                $round_total 	= $this->roundNumber($grand_total, $this->pos_settings->rounding);
                $rounding 	= $this->formatMoney($round_total - $grand_total);
            }
            $data = array('date'    => $date,
                'reference_no'      => $reference,
                'dummy_reference'   =>$dummy_reference,
                'customer_id'       => $customer_id,
                'customer'          => $customer,
                'biller_id'         => $biller_id,
                'biller'            => $biller,
                'warehouse_id'      => $warehouse_id,
                'note'              => $note,
                'staff_note'        => $staff_note,
                'total'             => $total,
                'product_discount'  => $product_discount,
                'order_discount_id' => $this->post('discount'),
                'order_discount'    => $order_discount,
                'total_discount'    => $total_discount,
                'product_tax'       => $product_tax,
                'order_tax_id'      => $this->post('order_tax'),
                'order_tax'         => $order_tax,
                'total_tax'         => $total_tax,
                'shipping'          => $this->formatDecimal($shipping),
                'grand_total'       => $grand_total,
                'total_items'       => $total_items,
                'sale_status'       => $sale_status,
                'payment_status'    => $payment_status,
                'payment_term'      => $payment_term,
                'rounding'          => $rounding,
                'suspend_note'      => $this->post('suspend_note'),
                'pos'               => 1,
                'paid'              => $this->post('amount_paid'),
                'created_by'        => $this->post('created_by'),
                'hash'              => hash('sha256', microtime() . mt_rand()),
                );
            
          if (!$suspend) 
	{
		
		$total_amt 		=$this->post('amount');
		$tot_pai 		= $this->post('amount_paid');
		$balance_amount 	= $total_amt - $tot_pai;
        	//$amount = $this->formatDecimal($tot_pai > 0 ? $this->post('amount') - $tot_pai : $this->post('amount_paid'));//print_r($amount);die();
        	$amount 		= $tot_pai;
        	if ($this->post('paid_by') == 'gift_card') 
		{
            		$gc  		= $this->getGiftCardByNO($this->post('paying_gift_card_no'));
            		$amount_paying 	= $this->post('amount_paid') >= $gc->balance ? $gc->balance : $this->post('amount_paid');
            		$gc_balance 	= $gc->balance - $amount_paying;
           		 $payment[] 	= array(
                                				
                                				
                                				'date'         	=> $date,
                                				'reference_no' 	=> $this->getReference('pay'),
                                				'amount'      	=> $amount,
                                				'paid_by'      	=> $this->post('paid_by'),
								'cheque_no'  	=> $this->post('cheque_no'),
								'cc_no'        	=> $this->post('cc_no'),
								'cc_holder'    	=> $this->post('cc_holder'),
								'cc_month'     	=> $this->post('cc_month'),
								'cc_year'      	=> $this->post('cc_year'),
								'cc_type'      	=> $this->post('cc_type'),
								'cc_cvv2'      	=> $this->post('cc_cvv2'),
								'created_by'   	=> $this->post('created_by'),
								'type'         	=> 'received',
								'note'         	=> $this->post('note'),
								'pos_paid'     	=> $tot_pai,
								'pos_balance'  	=> $balance_amount,
								'gc_balance'  	=> $gc_balance,
                                );

        	} 
		else 
		{
               		$payment[] 	= array(
                               					'date'          => $date,
                             					'reference_no'  => $this->getReference('pay'),
                               					'amount'        => $amount,
                                				'paid_by'      	=> $this->post('paid_by'),
								'cheque_no'  	=> $this->post('cheque_no'),
								'cc_no'        	=> $this->post('cc_no'),
								'cc_holder'    	=> $this->post('cc_holder'),
								'cc_month'     	=> $this->post('cc_month'),
								'cc_year'      	=> $this->post('cc_year'),
								'cc_type'      	=> $this->post('cc_type'),
								'cc_cvv2'      	=> $this->post('cc_cvv2'),
								'created_by'   	=> $this->post('created_by'),
								'type'         	=> 'received',
								'note'         	=> $this->post('note'),
								'pos_paid'     	=>$tot_pai,
								'pos_balance'  	=> $balance_amount,
					);

        	}

    	}
        if (!isset($payment) || empty($payment)) 
        {
                $payment = array();
        }
	//$this->sma->print_arrays($payment, $data, $products,$daily_product);
        if (!empty($products) && !empty($data)) 
        {
		if ($suspend) {
				  if ($this->user->suspendSale($data, $products, $did,$daily_product)) 
				   {
			                $this->response([
			                
			               'status' => TRUE,
			               'message' => 'Sale  has been suspend successfully.'
			          	 ], REST_Controller::HTTP_OK);
			            }
			      }
			      else 
			      {
            			if ($sale = $this->user->addSaleOffline($data, $products, $payment, $sid,$daily_product)) 
            			
				{
				          
			                $this->response([
			                'sale_id'=>$sale,
			               
			               
			               'status' => TRUE,
			               'message' => 'Sale has been added successfully.'
			           ], REST_Controller::HTTP_OK);
			        }
            
       			      } 
    	}
} 
     public function calculateOrderTax($order_tax_id = NULL, $amount) {
        if ($this->Settings->tax2 != 0 && $order_tax_id) {
            if ($order_tax_details = $this->getTaxRateByID($order_tax_id)) {
                if ($order_tax_details->type == 1) {
                    return $this->formatDecimal((($amount * $order_tax_details->rate) / 100), 4);
                } else {
                    return $this->formatDecimal($order_tax_details->rate, 4);
                }
            }
        }
        return 0;
    }
    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 clear_tags($str)
    {
        return htmlentities(
            strip_tags($str,
                '<span><div><a><br><p><b><i><u><img><blockquote><small><ul><ol><li><hr><big><pre><code><strong><em><table><tr><td><th><tbody><thead><tfoot><h3><h4><h5><h6>'
            ),
            ENT_QUOTES | ENT_XHTML | ENT_HTML5,
            'UTF-8'
        );
    }
    public function getCompanyByID($id) {
        $q = $this->db->get_where('companies', array('id' => $id), 1);
        if ($q->num_rows() > 0) {
            return $q->row();
        }
        return FALSE;
    }
     /********************payments******************************/
   public function paymentssale_post($id = 0) 
    {
        $id = $this->post('sale_id');//print_r($id);die();
       
        $payments = $this->user->paymentview($id);
        if(!empty($payments))
        {
            $this->response($payments, REST_Controller::HTTP_OK);
        }
        else
        {
            $this->response([
                'status' =>FALSE,
                'message' => 'No payments were found.'
            ], REST_Controller::HTTP_OK);
        }
        
    }
   
   /********************POS REGISTER******************************/
    
     public function registers_post($id = 0) 
    {
        $id = $this->post('user_id');
        $register = $this->user->getregister($id);
        if(!empty($register))
        {
            $this->response($register, REST_Controller::HTTP_OK);
        }
        else
        {
            $this->response([
             'status' => FALSE,
                'message' => 'No Register were open.'
            ], REST_Controller::HTTP_OK);
        }
    }

    
     public function openregister_post($id = 0) 
    {
    	$id =$this->post('user_id');
        $register = $this->user->getregister($id);
        if(empty($register))
        {
        $data = array(
                'date' => date('Y-m-d H:i:s'),
                'cash_in_hand' => $this->post('cash_in_hand'),
                'user_id'      => $this->post('user_id'),
                'status'       => 'open',
                );
        $open_register = $this->user->openRegister($data);//print_r( $open_register);die();
        if(!empty($open_register))
        {
            $this->response([
                   'status' => TRUE,
                    'message' => 'Resgister open successful.'
                    ], REST_Controller::HTTP_OK);
        }
        else
        {
            $this->response([
                'status' => FALSE,
                'message' => 'No Register were open.'
            ], REST_Controller::HTTP_NOT_FOUND);
        }
        }
         else
        {
            $this->response($register, REST_Controller::HTTP_OK);
        }
    }
    
    
    public function registerdetails_post()
    {//print_r( $this->session->userdata());die();
      
         $user_id	 	= $this->post('user_id');
        //print_r($session);die();
        $register_open_time 	= $this->post('register_open_time');
        
        $cash_in_hand 		= $this->db->get_where('pos_register',array('date'=>$register_open_time ))->row()->cash_in_hand;
        $total_cash		= $this->db->get_where('pos_register',array('date'=>$register_open_time ))->row()->total_cash;
        $ccsales 		= $this->user->getRegisterCCSales($register_open_time,$user_id);
        $cardsales 		= $this->user->getRegisterCardSales($register_open_time,$user_id);
  	    $cashsales 		= $this->user->getRegisterCashSales($register_open_time,$user_id);
        $chsales 		= $this->user->getRegisterChSales($register_open_time,$user_id);
        $gcsales 		= $this->user->getRegisterGCSales($register_open_time,$user_id);
        $pppsales 		= $this->user->getRegisterPPPSales($register_open_time,$user_id);
        $stripesales 		= $this->user->getRegisterStripeSales($register_open_time,$user_id);
        $authorizesales 	= $this->user->getRegisterAuthorizeSales($register_open_time,$user_id);
        // $totalsales 		= $this->user->getRegisterSales($register_open_time,$user_id);
        $refunds 		= $this->user->getRegisterRefunds($register_open_time,$user_id);
        $expenses 		= $this->user->getRegisterExpenses($register_open_time,$user_id);
        
        $receipt_cash 		= $this->user->getRegisterReceiptcash($register_open_time,$user_id);
        $receipt_card 		= $this->user->getRegisterReceiptcard($register_open_time,$user_id);
        
        
        $credit_tot 		= $this->user->getRegistercreditSalesTot($register_open_time,$user_id);
        $credit    = $credit_tot->total - $cardsales->paid - $cashsales->paid;
        
        if($cashsales->paid){
        $total_cash_amount 	=  $cashsales->paid + $receipt_cash->paid + $cash_in_hand + ($refunds->returned ? $refunds->returned : 0) - $expenses->total ;
        }
        else
        {
        	 $total_cash_amount 	= $cash_in_hand - ($expenses->total);//print_r($cashsales);die();
        
        }
         $register_details = array(
         		'opening_balance' 		=>  	$cash_in_hand,
         		'cash_in_hand'		=>	$total_cash_amount,				
         		'register_open_time' 	=>  	$register_open_time,
         		//'creditsales'		=>	$ccsales,
         		'cardsales'         =>$cardsales,
         		'cashsales'		=>	$cashsales,
         		'creditsales'		=>	$credit,
         		'receipt_amount_cash'		=>	$receipt_cash,
         		'receipt_amount_card'		=>	$receipt_card,
        //  	'chsales'		=>	$chsales ,
        //  	'gcsales'		=>	$gcsales, 
        //  	'pppsales'		=>	$pppsales, 
        //  	'stripesales'		=>	$stripesales,
        //  	'authorizesales'	=>	$authorizesales,
        //		'totalsales'		=> 	$totalsales,
        //  	'refunds'		=> 	$refunds,
        //  	'expenses'		=>	$expenses,
         		
         
           );
           if(!empty($register_details))
        {
            
            $this->response($register_details, REST_Controller::HTTP_OK);
        }
        else
        {
          
            $this->response([
                'status' => FALSE,
                'message' => 'No Data were found.'
            ], REST_Controller::HTTP_OK);
        }
        
    }
    public function closeregister_post($user_id = NULL)
    {
        $user_id =$this->post('user_id');
        $user_register = $user_id ? $this->user->registerData($user_id) : NULL;
        $rid = $user_register ? $user_register->id : $this->session->userdata('register_id');
        $user_id = $user_register ? $user_register->user_id : $this->session->userdata('user_id');
            
            $data = array(
                'closed_at'                => date('Y-m-d H:i:s'),
                'total_cash'               => $this->post('total_cash'),
                'total_cheques'            => $this->post('total_cheques'),
                'total_cc_slips'           => $this->post('total_cc_slips'),
                'total_cash_submitted'     => $this->post('total_cash_submitted'),
                'total_cheques_submitted'  => $this->post('total_cheques_submitted'),
                'total_cc_slips_submitted' => $this->post('total_cc_slips_submitted'),
                'note'                     => $this->post('note'),
                'status'                   => 'Close',
                'transfer_opened_bills'    => $this->post('transfer_opened_bills'),
                'closed_by'                => $this->post('user_id'),
                );
        
         $close = $this->user->closeRegister($rid, $user_id, $data);
		 if(!empty($close))
            {
                $this->response([
                    'status' => TRUE,
                    'message' => ' register close successfully.'
                    ], REST_Controller::HTTP_OK);
            }
            else
            {
                //set the response and exit
                $this->response("something went wrong", REST_Controller::HTTP_BAD_REQUEST);
            }
           
            
    }

/**************************Sale Edit******************************************************/

 public function saleedit_post($id = null)
    {
        $id = $this->post('id');//print_r($this->post('warehouse_id'));die();
        $inv = $this->user->getInvoiceByID($id);
        if ($inv->sale_status == 'returned' || $inv->return_id || $inv->return_sale_ref)  {
                $this->response([
               'status' => TRUE,
               'message' => 'Returned sale.'
           ], REST_Controller::HTTP_OK);
            }
        $reference 			= $this->post('reference_no');
	$date 				= $this->post('date');
        $warehouse_id 			= $this->post('warehouse_id');
        $dummy_refernce =   $first_name = $this->db->get_where('sales', array('id' =>  $id))->row()->dummy_reference;
          $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;
        $customer_id 			= $this->post('customer');
        $biller_id 			= $this->post('biller');
        $total_items 			= $this->post('total_items');
        $sale_status 			= $this->post('sale_status');
        $payment_status 		= $this->post('payment_status');
        $payment_term 			= $this->post('payment_term');
        $due_date 			= $payment_term ? date('Y-m-d', strtotime('+' . $payment_term . ' days', 	strtotime($date))) : null;
        $shipping 			= $this->post('shipping') ? $this->post('shipping') : 0;
        $customer_details 		= $this->getCompanyByID($customer_id);
        $customer 			= !empty($customer_details->company) && $customer_details->company != '-'  ? $customer_details->company : $customer_details->name;
        $biller_details 		= $this->getCompanyByID($biller_id);
        $biller 			= !empty($biller_details->company) && $biller_details->company != '-' ? $biller_details->company : $biller_details->name;
        $note 				= $this->clear_tags($this->post('note'));
        $staff_note 			= $this->clear_tags($this->post('staff_note'));
	$total 				= 0;
        $product_tax 			= 0;
        $product_discount 		= 0;
        $gst_data 			= 0;
        $total_cgst 			= $total_sgst = $total_igst = 0;
          $pro 			= $this->post('product');//print_r($pro);die();
       //$arr 			= json_decode($pro);
	    
	    
	     $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;
                          
	    
	    
	    
	    
	foreach($pro as  $value)
	{
				
		$item_id 		    = $value['product_id'];
		$item_type 		    = $value['product_type'];
		$item_code 		    = $value['product_code'];
		$item_name 		    = $value['product_name'];
		$item_comment 		= $value['comment'];
		$item_option 		= $value['option_id'];
		$tax_val = $this->db->get_where('tax_rates',array('id'=>$value['item_tax']))->row()->rate;
		$rea_price = ($value['unit_price'] * $tax_val)/(100 + $tax_val );
		$real_unit_price 	= $value['real_unit_price'] - $rea_price;
		$unit_price 		= $real_unit_price ;
		$item_unit_quantity 	= $value['unit_quantity'];
		$item_serial 		= $value['serial_no'];
		$item_tax_rate 		= $value['item_tax'];
		$item_discount 		= $value['item_discount'];
		$item_unit 		= $value['item_unit'];
		$item_quantity 		= $value['quantity'];
							
                if (isset($item_code) && isset($real_unit_price) && isset($unit_price) && isset($item_quantity)) 
				{
                    $product_details = $item_type != 'manual' ? $this->user->getProductByCode($item_code) : NULL;
                    // $unit_price = $real_unit_price;
                    if ($item_type == 'digital') {
                        $digital = TRUE;
                    }
                    $pr_discount = $this->calculateDiscount($item_discount, $unit_price);
                    $unit_price = $this->formatDecimal($unit_price - $pr_discount);
                    $item_net_price = $unit_price;
                    $pr_item_discount = $this->formatDecimal($pr_discount * $item_unit_quantity);
                    $product_discount += $pr_item_discount;
                    $pr_item_tax = $item_tax = 0;
                    $tax = "";

                    if (isset($item_tax_rate) && $item_tax_rate != 0) {

                        $tax_details = $this->getTaxRateByID($item_tax_rate);
                        $ctax = $this->calculateTax($product_details, $tax_details, $unit_price);
                        $item_tax = $ctax['amount'];
                        $tax = $ctax['tax'];
                        if (!$product_details || (!empty($product_details) && $product_details->tax_method != 1)) {
                            $item_net_price = $unit_price - $item_tax;
                        }
                        $pr_item_tax = $this->formatDecimal(($item_tax * $item_unit_quantity), 4);
                        
                    }

                    $product_tax += $pr_item_tax;
                    $subtotal = (($item_net_price * $item_unit_quantity) + $pr_item_tax);
                    $unit = $this->site->getUnitByID($item_unit);
                    $second_name = $this->db->get_where('products',array('id'=> $item_id))->row()->second_name;
                    $product = array(
                        'product_id'      => $item_id,
                        'product_code'    => $item_code,
                        'product_name'    => $item_name,
                        'second_name'       =>$second_name,
                        'product_type'    => $item_type,
                        'option_id'       => $item_option,
                        'net_unit_price'  => $item_net_price,
                       'unit_price' => $this->sma->formatDecimal($item_net_price + $item_tax),
                        'quantity'        => $item_quantity,
                        'product_unit_id' => $unit ? $unit->id : NULL,
                        'product_unit_code' => $unit ? $unit->code : NULL,
                        'unit_quantity' => $item_unit_quantity,
                        'warehouse_id'    => $warehouse_id,
                        'item_tax'        => $pr_item_tax,
                        'tax_rate_id'     => $item_tax_rate,
                        'tax'             => $tax,
                        'discount'        => $item_discount,
                        'item_discount'   => $pr_item_discount,
                        'subtotal'        => $this->formatDecimal($subtotal),
                        'serial_no'       => $item_serial,
                        'real_unit_price' =>  $this->formatDecimal($real_unit_price),
                        'comment'         => $item_comment,
                    );

                    $products[] = ($product);
                    $total += $this->formatDecimal(($item_net_price * $item_unit_quantity), 4);
                }
            }//print_r($product);die();
            
            $order_discount = $this->calculateDiscount($this->post('order_discount'), ($total + $product_tax));
            $total_discount = $this->formatDecimal(($order_discount + $product_discount), 4);
            $order_tax = $this->calculateOrderTax($this->post('order_tax'), ($total + $product_tax - $order_discount));
            $total_tax = $this->formatDecimal(($product_tax + $order_tax), 4);
            $grand_total = $this->formatDecimal(($total + $total_tax + $this->formatDecimal($shipping) - $order_discount), 4);
            $data = array('date'    => $date,
                
                'reference_no'      => $reference,
                'dummy_reference'=> $dummy_refernce,
                'customer_id'       => $customer_id,
                'customer'          => $customer,
                		
                'biller_id'         => $biller_id,
                'biller'            => $biller,
                	
                'warehouse_id'      => $warehouse_id,
                'note'              => $note,
                'staff_note'        => $staff_note,
                'total'             => $total,
                'product_discount'  => $product_discount,
                'order_discount_id' => $this->post('order_discount'),
                'order_discount'    => $order_discount,
                'total_discount'    => $total_discount,
                'product_tax'       => $product_tax,
                'order_tax_id'      => $this->post('order_tax_id'),
                'order_tax'         => $order_tax,
                'total_tax'         => $total_tax,
                'shipping'          => $this->formatDecimal($shipping),
                'grand_total'       => $grand_total,
                'total_items'       => $total_items,
                'sale_status'       => $sale_status,
                'payment_status'    => $payment_status,
                'payment_term'      => $payment_term,
                'due_date' 	    => $due_date,
                'updated_by' 	    => $this->post('created_by'),
                'updated_at' 	    => date('Y-m-d H:i:s'),
                );
           
       //  $this->sma->print_arrays($data, $products);
        if ($this->user->updateSale($id, $data, $products)) {
            {
                $this->response([
               'status' => TRUE,
               'message' => 'Sale  has been updated successfully.'
           ], REST_Controller::HTTP_OK);
            }
        } else{
           //set the response and exit
           $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
       }
    }


/*****************************Return Sale**************************************************/
  public function returnsale_post()
    {
            $id = $this->post('id');
            $sale = $this->user->getInvoiceByID($id);//print_r($this->post('user_id'));die();
    if ($sale->return_id)  {
                $this->response([
               'status' => FALSE,
               'message' => 'Sale already returned .'
           ], REST_Controller::HTTP_OK);
            }
	    $reference 				= $this->post('reference_no') ? $this->post('reference_no') : $this->getReference('re');
            $date 				= date('Y-m-d H:i:s');
	    $return_surcharge 			= $this->post('return_surcharge') ? $this->post('return_surcharge') : 0;
            $note 				= $this->clear_tags($this->post('note'));
            $customer_details 			= $this->getCompanyByID($sale->customer_id);
            $biller_details 			= $this->getCompanyByID($sale->biller_id);
	    $total 				= 0;
            $product_tax 			= 0;
            $product_discount 			= 0;
            $gst_data 				= 0;
            $total_cgst 			= $total_sgst = $total_igst = 0;
            $pro 				= $this->post('product');//print_r($pro);die();
       //$arr 			= json_decode($pro);
	
	foreach($pro as  $value)
	{
				
		$item_id 		= $value['product_id'];
		$item_type 		= $value['product_type'];
		$item_code 		= $value['product_code'];
		$item_name 		= $value['product_name'];
		$sale_item_id		= $value['sale_item_id'];
		$item_comment 		= $value['comment'];
		$item_option 		= $value['option_id'];
		$real_unit_price 	= $value['real_unit_price'];
		$unit_price 		= $value['unit_price'];
		$item_unit_quantity 	= $value['unit_quantity'];
		$item_serial 		= $value['serial_no'];
		$item_tax_rate 		= $value['item_tax'];
		$item_discount 		= $value['item_discount'];
		$item_unit 		= $value['item_unit'];
		$item_quantity 		= $value['quantity'];
				
		if (isset($item_code) && isset($real_unit_price) && isset($unit_price) && isset($item_quantity)) 
		{
                    $product_details = $item_type != 'manual' ? $this->user->getProductByCode($item_code) : NULL;
                    // $unit_price = $real_unit_price;
                    if ($item_type == 'digital') {
                        $digital = TRUE;
                    }
                    $pr_discount = $this->calculateDiscount($item_discount, $unit_price);
                    $unit_price = $this->formatDecimal($unit_price - $pr_discount);
                    $item_net_price = $unit_price;
                    $pr_item_discount = $this->formatDecimal($pr_discount * $item_unit_quantity);
                    $product_discount += $pr_item_discount;
                    $pr_item_tax = $item_tax = 0;
                    $tax = "";

                    if (isset($item_tax_rate) && $item_tax_rate != 0) {

                        $tax_details = $this->getTaxRateByID($item_tax_rate);
                        $ctax = $this->calculateTax($product_details, $tax_details, $unit_price);
                        $item_tax = $ctax['amount'];
                        $tax = $ctax['tax'];
                        if (!$product_details || (!empty($product_details) && $product_details->tax_method != 1)) {
                            $item_net_price = $unit_price - $item_tax;
                        }
                        $pr_item_tax = $this->formatDecimal(($item_tax * $item_unit_quantity), 4);
                        
                    }

                    $product_tax += $pr_item_tax;
                    $subtotal = (($item_net_price * $item_unit_quantity) + $pr_item_tax);
                    $unit = $this->site->getUnitByID($item_unit);
                     $second_name = $this->db->get_where('products',array('id'=> $item_id))->row()->second_name;
                    $product = array(
                        'product_id'      => $item_id,
                        'product_code'    => $item_code,
                        'product_name'    => $item_name,
                        'second_name'       =>$second_name,
                        'product_type'    => $item_type,
                        'option_id'       => $item_option,
                        'net_unit_price'  => $item_net_price,
                        'unit_price'      => $value['unit_price'],
                        'quantity'        => $item_quantity,
                        'product_unit_id' => $unit ? $unit->id : NULL,
                        'product_unit_code' => $unit ? $unit->code : NULL,
                        'unit_quantity' => $item_unit_quantity,
                        'warehouse_id'    => $sale->warehouse_id,
                        'item_tax'        => $pr_item_tax,
                        'tax_rate_id'     => $item_tax_rate,
                        'tax'             => $tax,
                        'discount'        => $item_discount,
                        'item_discount'   => $pr_item_discount,
                        'subtotal'        => $this->formatDecimal($subtotal),
                        'serial_no'       => $item_serial,
                        'real_unit_price' => $real_unit_price,
                        'comment'         => $item_comment,
                        'sale_item_id'	  => $sale_item_id,
                    );
                     $si_return[] = array(
                        'id' => $sale_item_id,
                        'sale_id' => $id,
                        'product_id' => $item_id,
                        'option_id' => $item_option,
                        'quantity' => (0-$item_quantity),
                        'warehouse_id' => $sale->warehouse_id,
                        );

                    $products[] = $product;
                    $total += $this->sma->formatDecimal(($item_net_price * $item_unit_quantity), 4);
                }
            }
            
            $order_discount = $this->calculateDiscount($this->post('discount') ? $this->post('discount') : null, ($total + $product_tax));
            $total_discount = $this->formatDecimal(($order_discount + $product_discount), 4);
            $order_tax = $this->calculateOrderTax($this->post('order_tax'), ($total + $product_tax - $order_discount));
            $total_tax = $this->formatDecimal($product_tax + $order_tax, 4);
            $grand_total = $this->formatDecimal(($total + $this->formatDecimal($return_surcharge) + $order_discount), 4);
            $data = array('date' => $date,
                'sale_id' => $id,
                'reference_no' => $sale->reference_no,
                'customer_id' => $sale->customer_id,
                'customer' => $sale->customer,
                'biller_id' => $sale->biller_id,
                'biller' => $sale->biller,
                'warehouse_id' => $sale->warehouse_id,
                'note' => $note,
                'total' =>$total,
                'product_discount' => $product_discount,
                'order_discount_id' => $this->post('discount') ? $this->post('order_discount') : null,
                'order_discount' => $order_discount,
                'total_discount' => $total_discount,
                'product_tax' => $product_tax,
                'order_tax_id' => $this->input->post('order_tax'),
                'order_tax' => $order_tax,
                'total_tax' => $total_tax,
                'surcharge' => $this->formatDecimal($return_surcharge),
                'grand_total' => $grand_total,
                'created_by' => $this->post('user_id'),
                'return_sale_ref' =>$this->getReference('re'),
                'sale_status' => 'returned',
                'pos' => $sale->pos,
                'payment_status' => $sale->payment_status == 'paid' ? 'due' : 'pending',
            );
           

            if ($this->post('amount_paid') && $this->post('amount_paid') > 0) {
                $pay_ref = $this->post('payment_reference_no') ? $this->post('payment_reference_no') : $this->getReference('pay');
                $payment = array(
                    'date' => $date,
                    'reference_no' => $pay_ref,
                    'amount' => (0-$this->post('amount_paid')),
                    'paid_by' => $this->post('paid_by'),
                    'cheque_no' => $this->post('cheque_no'),
                    'cc_no' => $this->post('pcc_no'),
                    'cc_holder' => $this->post('pcc_holder'),
                    'cc_month' => $this->post('pcc_month'),
                    'cc_year' => $this->post('pcc_year'),
                    'cc_type' => $this->post('pcc_type'),
                    'created_by' =>  $this->post('user_id'),
                    'type' => 'returned',
                );
                $data['payment_status'] = $grand_total == $this->post('amount_paid') ? 'paid' : 'partial';
            } else {
               $payment = array();
            }
             
//$this->sma->print_arrays($data, $products, $payment, $si_return);
        if ($this->user->addSales($data, $products, $payment, $si_return)) {
             {
                $this->response([
               'status' => TRUE,
               'message' => 'Sale  has been returned successfully.'
           ], REST_Controller::HTTP_OK);
            }
        } else{
           //set the response and exit
           $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
       }
    }
 
public function view_post($id = 0)
    {
        $sale_id 		= $this->post('id');
        $inv 			= $this->user->getInvoiceByID($sale_id);
        $rows 			= $this->user->getAllInvoiceItems($sale_id);
        $biller_id 		= $inv->biller_id;
        $customer_id 	= $inv->customer_id;
        $biller 		= $this->user->getCompanyByID($biller_id);
        $customer 		= $this->user->getCompanyByID($customer_id);
        $payments 		= $this->user->getInvoicePayments($sale_id);
        $pos 			= $this->user->getSetting();
        $return_sale 	= $inv->return_id ? $this->user->getInvoiceByID($inv->return_id) : NULL;
        $return_rows 	= $inv->return_id ? $this->user->getAllInvoiceItems($inv->return_id) : NULL;
        $return_payments= $return_sale ? $this->user->getInvoicePayments($return_sale->id) : NULL;
        $sid 			= $sale_id;
        //$url = base_url() . 'admin/pos/print/' . $sale_id . '';
       // $url =    file_get_contents('http://printassi.cignestrade.com/admin/pos/view/' . $sale_id . '');
        $created_by 	= $this->user->getUser($inv->created_by);
        $printer 		= $this->user->getPrinterByID($this->pos_settings->printer);
		$data = array(
		
						'sale_id' 		=> $sale_id,
						'inv' 			=> $inv,
						'rows' 			=> $rows,
						'biller_id' 	=> $biller_id,
						'customer_id' 	=> $customer_id,
						'biller' 		=> $biller,
						'customer' 		=> $customer,
						'payments' 		=> $payments,
						'pos' 			=> $pos,
						'return_sale' 	=> $return_sale,
						'return_rows' 	=> $return_rows,
						'return_payment'=> $return_payments,
						'sid' 			=> $sid,
						'created_by' 	=> $created_by,
						'printer' 		=> $printer,
						'url'		=> $url,
		
				);
				if(!empty($data))
            {
                $this->response([
                    'array' => $data,
                    'status' => TRUE,
                    'message' => 'Print .'
                    ], REST_Controller::HTTP_OK);
            }
            else
            {
                //set the response and exit
                $this->response("something went wrong.", REST_Controller::HTTP_BAD_REQUEST);
            }
				
        
    }
        public function viewCredit_post() 
    {
    $start = $this->post('start');
    $end =$this->post('end');
      $view = $this->user->getCreditView($start,$end);
      if(!empty($view))
      {
            //set the response and exit
            $this->response($view, REST_Controller::HTTP_OK);
      }
      else
      {
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No data were found.'
            ], REST_Controller::HTTP_OK);
      }
    }
    
    public function viewCredits_post() 
    {
        
    $start  =   $this->post('start');
    $end    =   $this->post('end');
    $id     =   $this->post('biller_id');//print_r($start);die();
      $view = $this->user->getCreditViews($start,$end,$id);
      if(!empty($view))
      {
            //set the response and exit
            $this->response($view, REST_Controller::HTTP_OK);
      }
      else
      {
            //set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No data were found.'
            ], REST_Controller::HTTP_OK);
      }
    }
   public function addpaymentAgainstCustomer_post($id = NULL)
    {
		$id 	= $this->post('customer_id');
		$paid_by =$this->post('paid_by');
		$created_by = $this->post('user_id');
        $amount = $this->post('amount_paid');
		$pay 	= $this->user->paymentAgainstCustomer($id,$amount,$paid_by,$created_by);
         if(!empty($pay))
            {
                $this->response([
                    
                    'status' => TRUE,
                    'message' => 'Payment Done successfully.'
                    ], REST_Controller::HTTP_OK);
            }
            else
            {
                //set the response and exit
                $this->response("something went wrong.", REST_Controller::HTTP_BAD_REQUEST);
            }    
    }

}

?>
