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


class Pos extends CI_Controller {

	var $main_menu_name = "hw";
	var $sub_menu_name = "";

	public function __construct()
	{
		parent::__construct();
		$this->load->model('pos_model');
		$this->load->model('Pos_Model');
		$this->load->model('customer_model');
		$this->load->model('common_model');
		$this->load->model('sales_model');
		$this->load->model('Warehouse_Model');
		$this->load->model('Store_Notes_Model');
		$this->load->model('Stock_Counter_Model');
		$this->load->model('Product_Discount_Model');
		$this->load->model('Free_Issue_Process_Model');
		date_default_timezone_set("Asia/Colombo");
	}

	public function index()
	{
		$data['category_by_id_1'] = $this->pos_model->get_product_by_cat_id(1);
		$data['category'] 		  = $this->pos_model->get_all_category();
		$data['sub_category'] 	  = $this->pos_model->get_sub_category_by_cat_id(1);
		$data['get_customer']     = $this->pos_model->get_customer();
		$data['get_warehouse']    = $this->pos_model->get_warehouse();
		$this->load->view('pos/pos',$data);
	}
	
	function hw_list(){
			
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'list';
        $this->load->view('invoice/hw_list',$data);
	
	}
	
	 function list_sales()
	{		
	$requestData= $_REQUEST;	
	$start=$this->input->get('start');
	$length=$this->input->get('length');
	$search=$this->input->get('search');	
	$direct_sale=$this->input->get('direct_sale');	
	$data = array();	
	$totalData = 10000;//$this->pos_model->get_all_sales("","",$search,$direct_sale);
	$sales = $this->pos_model->get_all_sales($start,$length,$search,$direct_sale);
	$totalFiltered = $totalData; 	
	foreach ($sales as $row){
		$nestedData=array(); 
		$sale_id=$row['sale_id'];
		$total_paid_amount=0;
		$total_paid_amount=$this->pos_model->get_total_paid_by_sale_id($sale_id);		
		/*
		return start
		*/
		    $return_tot= 0;
			$total_return        = 0;
			$total_return_pymnt  = 0;
            $return_sales_details       = $this->pos_model->get_return_sale_info_sale_id($sale_id);
            foreach ($return_sales_details as $row2) {
                $total_return             += $row2->sl_rtn_total;
                $total_return_pymnt       += $this->pos_model->get_total_return_paid_by_sale_id($row2->sl_rtn_id);
            }
		/*
		return end
		*/	
		$to_be_paid=$row['sale_total']-$total_return+$total_return_pymnt;
		$nestedData[] =$row['sale_datetime'];
		$nestedData[] = $row['sale_reference_no']." / ".$row['card_ref_number'];
		$nestedData[] = $row['cus_name'];
		$nestedData[] = $row['sale_total'];
		$nestedData[] = $total_return;		
		$nestedData[] = $to_be_paid;
		$nestedData[] = $total_paid_amount;		
		$invoice_balance=$total_paid_amount-$total_return_pymnt;
		$nestedData[] = $to_be_paid-$invoice_balance;	
		if (empty($total_paid_amount)) {
		  $pay_st = '<span class="label label-warning">Pending</span>';
		}else{
		  if ($total_paid_amount >= $to_be_paid) {
			$pay_st = '<span class="label label-success">Paid</span>';
		  }else{
			$pay_st = '<span class="label label-info">Partial</span>';
		  }
		}
		$nestedData[]=$pay_st;		
		$actionTxtDisble='';
		$actionTxtEnable='';
		$actionTxtUpdate='';
		$actionTxtDelete='';
		$url=base_url("sales/sale_details?sale_id=$sale_id");
		$actionTxtUpdate='<a onClick="fbs_click('.$row['sale_id'].')" data-toggle="modal" href="#" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="clip-zoom-in-2"></i></a> &nbsp;';
		$actionTxtViewDetails='<a href="'.base_url().'pos/view/'.$sale_id.'" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-file-text-o"></i></a> &nbsp;';
		$actionTxtClearInvoice = '<a style="cursor:pointer" onClick ="clear_sale(' . $sale_id . ',' . $row['warehouse_id'] . ')"><i class="fa fa-eraser"></i></i><span style="margin-left:2px">Cancel Invoice</span></a>';
		$sale_return_action='';
		if($this->session->userdata('ss_group_id')==1){
		   $sale_return_action='<li><a href="'.base_url().'sales_return/sales_return_add_hw/'.$sale_id.'"><i class="fa fa-file-text-o"></i> Return Sale</a></li>'; 
		}else{
		    $actionTxtClearInvoice='';
		}
		
		if ($total_return>0) 
		 {
			$nestedData[] = '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="'.base_url().'pos/view/'.$sale_id.'"><i class="fa fa-file-text-o"></i> Sale Details</a></li>
                            
                            <li><a onClick="fbs_click('.$row['sale_id'].')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-print"></i> Print Sale</a></li>
							</ul></div>'; 
		 }else //<li><a href="'.base_url().'sales_return/sales_return_add_hw/'.$sale_id.'"><i class="fa fa-file-text-o"></i> Return Sale</a></li>
		 {
			$nestedData[] = '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="'.base_url().'pos/view/'.$sale_id.'"><i class="fa fa-file-text-o"></i> Sale Details</a></li>
                            '.$sale_return_action.'
                            <li>'.$actionTxtClearInvoice.'</li>
                            </ul></div>'; 
		 }	
		 /*
		 
		 <li><a onClick="fbs_click('.$row['sale_id'].')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-print"></i> Print Sale</a></li>
							 <li><a href="'.base_url().'sales_return/sales_return_add/'.$sale_id.'"><i class="fa fa-angle-double-left"></i></i> Return Sale</a></li>
		 
		 */
		$data[] = $nestedData;
	}

	$json_data = array(
			//"draw"            => intval( $requestData['draw'] ),  
			"recordsTotal"    => intval( $totalData ),  
			"recordsFiltered" => intval( $totalFiltered ),
			"data"            => $data 
			);

	echo json_encode($json_data); 
	}
	

public function vk(){
	$this->load->view("pos/vk");
	}

	public function ajaxcategorydata($category_id='')
	{
		$category_id = $this->input->get('category_id');

		$out_cat = '';
		$out_sub = '';
		$d = $this->pos_model->get_product_by_cat_id($category_id);
		$s = $this->pos_model->get_sub_category_by_cat_id($category_id);
		if (!empty($d)) {

			foreach ($d as $key => $prod) {
				$out_cat.="<button data-container='body' class='btn-prni btn-default product pos-tip' title='".$prod->product_name."' product_cost='".$prod->product_cost."'  value='".$prod->product_code."' type='button' id='product-".$prod->product_id."' style='font-weight:bold; font-size:12px; height:120px; min-width:150px'> 
				<div class='row' style='height:100%'>													  
					<div class='col-xs-7' style='height:100%'>
						<img class='img-rounded' style='height:113px;' width='90px' alt='".$prod->product_name."' src='".asset_url()."uploads/thumbs/".$prod->product_thumb."'>
					</div>

<div class='col-xs-5' style='height:100%'>".substr($prod->product_name, 0, 20)."<br>".$prod->product_price."
				</div>
				</div>
				</button>";	
				
				
			/*--------------
				OLD CAT BUTTON
			--------------*/
			/*
			$out_cat.="<button data-container='body' class='btn-prni btn-default product pos-tip' title='".$prod->product_name."'  value='".$prod->product_code."' type='button' id='product-".$prod->product_id."'><img class='img-rounded' style='width:60px;height:60px;' alt='".$prod->product_name."' src='".asset_url()."uploads/thumbs/".$prod->product_thumb."'><span>".$prod->product_name."</span></button>;"
			*/
			/*--------------
			OLD CAT BUTTON END
				-----------*/
			}
			if (!empty($s)) {
				foreach ($s as $key => $sub_cat) {
					$out_sub.="<button id='subcategory-".$sub_cat->sub_cat_id."' type='button' value='".$sub_cat->sub_cat_id."' class='btn-prni subcategory' ><img src='".asset_url()."uploads/no-image.jpg' style='width:60px;height:60px;' class='img-rounded img-thumbnail'/><span>".$sub_cat->sub_cat_name."</span></button>";
					
					/*-------------
						OLD SUB CAT BUTTON
						--------------------*/	
						/*
						$out_sub.="<button id='subcategory-".$sub_cat->sub_cat_id."' type='button' value='".$sub_cat->sub_cat_id."' class='btn-prni subcategory' ><img src='".asset_url()."uploads/no-image.jpg' style='width:60px;height:60px;' class='img-rounded img-thumbnail'/><span>".$sub_cat->sub_cat_name."</span></button>";
						*/
					/*---------------
					OLD SUB CAT BUTTON END
						*/
				}

				$jproduct = array(
					"products" =>$out_cat,
					"subcategories"=>$out_sub,
					"tcp"=>count($key));
				$ret = json_encode($jproduct);
				echo $ret;
			} else {
				$jproduct = array(
					"products" =>$out_cat,
					"subcategories"=>"",
					"tcp"=>count($key));
				$ret = json_encode($jproduct);
				echo $ret;
			}		
		}else{
			$jproduct = array(
				"products" =>"<div></div>",
				"subcategories"=>"",
				"tcp"=>0);
			$ret = json_encode($jproduct);
			echo $ret;
		}
	}

	public function ajaxproducts($category_id='',$subcategory_id='',$per_page='')
	{
		$nm = '';
		$category_id 	= $this->input->get('category_id');
		$subcategory_id = $this->input->get('subcategory_id');

		$n = $this->pos_model->get_product_by_cat_sub_id($category_id,$subcategory_id);
		if (!empty($n)) {

			foreach ($n as $key => $pro) {
				$nm.="<button data-container='body' class='btn-prni btn-default product pos-tip' title='".$pro->product_name."'  product_cost='".$prod->product_cost."'  value='".$pro->product_code."' type='button' id='product-".$pro->product_id."' style='font-weight:bold; font-size:12px; height:120px; min-width:150px'> 
				
<div class='row  col-xs-12' style='height:100%'>													  

<div class='col-xs-8' style='height:100%;'><img class='img-rounded' style='height:113px; width:90px; margin-left:-16px;' alt='".$pro->product_name."' src='".asset_url()."uploads/thumbs/".$pro->product_thumb."'></div>

<div class='col-xs-4' style='height:100%; text-align:left; margin-left:0px;'>".$pro->product_name."<br>".$pro->product_price."</div>
				</div>
				</button>";
				/*----------
					OLD SUB CLICK RESULT GEN
										----------*/
					/*
					$nm.="<button data-container='body' class='btn-prni btn-default product pos-tip' title='' value='".$pro->product_code."' type='button' id='product-".$pro->product_id."'><img class='img-rounded' style='width:60px;height:60px;' alt='".$pro->product_name."' src='".asset_url()."uploads/thumbs/".$pro->product_thumb."'><span>".$pro->product_name."</span></button>";
					*/
					/*
					END OLD SUB CLICK RESULT GEN
					*/
										
			}
			echo $nm;

		} else {
			echo "<div></div>";
		}
		
	}

	public function getProductDataByCode()
	{
        $emp_array=array();

		$product_code = $this->input->get('code');
		$customer_id  = $this->input->get('customer_id');
		$warehouse_id = $this->input->get('warehouse_id');

        $get_product_all_by_id  = $this->pos_model->get_product_by_code($product_code,$customer_id,$warehouse_id);
          if (!empty($get_product_all_by_id)) {
            $empar=array();
            foreach ($get_product_all_by_id as $key => $value) {
              $r      = $get_product_all_by_id[$key];
              $lb = $get_product_all_by_id[$key]->product_name;
              $label  = array("id"=>mt_rand(10,10000),"item_id"=>$get_product_all_by_id[$key]->product_id,"label"=>$get_product_all_by_id[$key]->product_code.' | '.$get_product_all_by_id[$key]->product_name,"qty"=>1,'row' =>$r,'value'=>$get_product_all_by_id[$key]->product_name);
              array_push($empar,$label);
            }
              echo json_encode($empar);

          } else {

            echo '[{"id":0,"label":"No matching result found! Product might be out of stock in the selected warehouse.","value":"hg"}]';
          }

	}
	
	function suggetions()
    {
        $term    = $this->input->get('term');
        $product = $this->Pos_Model->product_suggetions($term);
        $in_type = $this->input->get('t');
        $json    = array();
        $product_count=count($product);
        if($product_count==0){
            $original_product_code = substr($term, 0, 7);
            $barcode_product_qty = substr($term, 7, 5);
            $product_qty_in_kg=$barcode_product_qty/1000;
             $product_qty=round($product_qty_in_kg,4);
            $product = $this->Pos_Model->product_suggetions_waight_items($original_product_code);
        }else{
            $product_qty=1;
        }
        
        foreach ($product as $row) {
            $warehouse_id            = ""; // $this->session->userdata('ss_warehouse_id');
            //stock check   
            $qty = $this->Stock_Counter_Model->get_stock_balance($warehouse_id,$row['product_id']);
            $product_id              = $row['product_id'];
            $product_code            = $row['product_code'];
            $product_name            = $row['product_name'];
            $product_cost            = $row['product_cost'];
            $cash_price              = $row['retail_cash'];
            $wholesale_price         = $row['retail_wholesale'];
            $credit_salling_price    = $row['retail_credit'];
            $pt = "retail_cash,retail_credit,retail_wholesale";
            if ($in_type == 1) {
                $product_price = $cash_price;
                $pt = "retail_cash";
            }
            if ($in_type == 2) {
                $product_price = $credit_salling_price;
                $pt = "retail_credit";
            }
            if ($in_type == 3) {
                $product_price = $wholesale_price;
                $pt = "retail_wholesale";
            }
            $discount=$this->Product_Discount_Model-> get_relevent_discount_for_pos($product_id,$in_type,$product_price);
            $sendParameters  = "$product_id,$product_name,$product_code,$product_price";
            $selling_R_price = " Selling Price: " . number_format($product_price, 2, '.', ',') . ' Cost Price:' . number_format($product_cost, 2, '.', ','); //RETAIL PRICE
            $selling_W_price = " Selling Price(Wholesale): " . number_format($wholesale_price, 2, '.', ','); //WHOLESALE PRICE
            $selling_C_price = " Selling Price(Credit): " . number_format($credit_salling_price, 2, '.', ','); //CREDIT PRICE
            
            $bdata = $this->Pos_Model->bdata($row['product_id'],$pt);
            $batch_data=array();
            foreach($bdata as $brow){
                $batch_stock= $this->Stock_Counter_Model->get_stock_balance_batch('',$product_id,$brow['batch_id']);
                if($batch_stock>$qty){
                    $batch_stock=$qty;
                }
                $nested_data=array(
                    'batch_id'          => $brow['batch_id'],
                    'batch_ref_number'  => $brow['batch_ref_number'],
                    'product_price'     => $brow['product_price'],
                    'product_cost'      => $brow['product_cost'],
                    'batch_qty'      =>   round($batch_stock,3)
                    );
                    if($batch_stock>0){
                        $batch_data[]= $nested_data;
                   }
            }
            $json_itm = array(
                //'id' => $row['product_id'],
                'product_id' => $row['product_id'],
                'product_code' => $row['product_code'],
                'product_name' => $row['product_name'],
                'product_cost' => $row['product_cost'],
                //'product_part_no' => $row['product_part_no'],
                //'item_cost' => $row['product_cost'],
                //'product_oem_part_number' => $row['product_oem_part_number'],
                'value' => $row['product_name'] . " (" . $row['product_code'] . ")". " / IN SROCK : " . $qty . " / Batches :" . count($batch_data),
                //'label' => $row['product_name'] . " (" . $row['product_code'] . ") / $selling_R_price" . " / IN SROCK : " . $qty . " / " . $row['batch_ref_number'],
                //'qty' => $qty,
                'qty'   => $product_qty,
                'wh'    => $row['warehouse_id'],
                'ao'    => $row['ao'],
                'bc'    => count($batch_data),
                'bdata' => $batch_data,
                'discount'=>$discount
            );
            array_push($json, $json_itm);
        }
        header('Content-Type: application/json');
        echo json_encode($json);
    }
	

	public function pos_submit()
	{
		if(is_logged_in()){
		}else {
			redirect(base_url(),'refresh');
			exit();
		}
		
		$this->load->library('form_validation');
		$this->form_validation->set_rules('uniq_id', 'Bill is unique', 'is_unique[hw_sales.unique_no]');
		 if ($this->form_validation->run() == FALSE)
        {
           echo json_encode(array(
               'sale_id' => 0,
				'sale_ref' => $this->input->post('uniq_id'),
				'error' => '1',
				'disMsg' => 'this bill already added. please use reprint if you havent received bill print',
				'duplicate' => 1
               ));
        }
        else
        {
		$customer_id 		= $this->input->post('poscustomer');
		$poswarehouse 		= $this->input->post('poswarehouse');
		$discount 			= $this->input->post('discount');
		$pos_discount_input = $this->input->post('pos_discount_input1');
		$pay_amount 		= $this->input->post('pay_amount');//$this->input->post('pay_amount');
		$grand_total 		= $this->input->post('grand_total');		
		$paid_by 			= $this->input->post('paid_by');
		$cc_name 			= $this->input->post('cc_name');
		$cc_no 				= $this->input->post('cc_no');
		$pcc_holder 		= $this->input->post('pcc_holder');
		$pcc_type 			= $this->input->post('pcc_type');
		$payment_note 		= $this->input->post('payment_note');
		$shipping 			= $this->input->post('posshipping');
		$sale_date 			= date("Y-m-d H:i:s");
		$price_type		=$this->input->post('price_type');
        //$query   			= $this->pos_model->get_new_next_ref_no($price_type);
        //$result  			= $query->row();
        //$sale_ref			= sprintf("%05d", $result->count+1);
        
        $sale_ref=$this->session->userdata('ss_cashier_float_id').strtotime("now");
        
        
        
        $pr_id 				= $this->input->post('product_id');
        $bid 		= $this->input->post('bid');
        $product_name 		= $this->input->post('product_name');
        $net_price 			= $this->input->post('net_price');
        $ssubtotal 			= $this->input->post('ssubtotal');
        $quantity 			= $this->input->post('quantity');
		$product_cost 		= $this->input->post('cost');
		$discount_val 		= $this->input->post('discount_val');
		$sale_pymnt_balane_amount = $this->input->post('balance_amount');
		$discount_i = $this->input->post('discount_i');		
		$total_item_discount_value = $this->input->post('total_item_discount');	
		$total_cost_val		= $this->input->post('total_cost_val');		
	    $is_phone_bill		=$this->input->post('is_phone_bill');
	    $address_input		=$this->input->post('shipping_address');
	    $cash_cus_name		=$this->input->post('cash_cus_name');
		$invoice_type	=$this->input->post('invoice_type');
		$price_type		=$this->input->post('price_type');
		$sale_pymnt_given_amount	= $this->input->post('cash_en');
		$cc_charges 		= $this->input->post('cc_charges');
		$broker_id 		= $this->input->post('broker_id');
		
		if($price_type=="retail_cash") $sale_ref = "CS".$sale_ref;
		else if($price_type=="retail_credit") $sale_ref = "CR".$sale_ref;
		else if($price_type=="retail_wholesale") $sale_ref = "WH".$sale_ref;
		
		if($sale_pymnt_given_amount > 0){}else $sale_pymnt_given_amount = 0;
		
		if($sale_pymnt_given_amount >= $grand_total ){
			$pay_amount = $grand_total;
		}
		else{
			$pay_amount	=	$sale_pymnt_given_amount;
			}		
				
		$data = array(
	        'sale_reference_no'           => $sale_ref,
	        'warehouse_id'                => $poswarehouse,
	        'customer_id'                 => $customer_id,
			'sale_datetime'               => $sale_date,
	        'sale_note'                   => $payment_note,
	        'sale_inv_total'		      => $grand_total-$total_item_discount_value-$shipping,			
			'sale_total'                  => $grand_total,
			'cost_total'      			  => $total_cost_val,
	        'sale_inv_discount'           => $pos_discount_input,
	        'sale_inv_discount_amount'    => $discount,
	        'paid_by'                     => $paid_by,
			'sale_datetime_created'       => $sale_date,
			'delivery_charge'      		  => $shipping,		
			//'is_phone_bill'      		  => $is_phone_bill,	
			'sale_shipping'      		  => $address_input,	
			'cash_cus_name'      		  => $cash_cus_name,
			'invoice_type'				=> $invoice_type,
			'price_type'				=> $price_type,
			'cr_interest'				  => 2,
			'cr_interest_amt'				  =>$cc_charges,
			'sale_given_amount' => $sale_pymnt_given_amount,
			'user_id'	=> $this->session->userdata('ss_user_id'),
			'broker_id'				  =>$broker_id,
			'float_id'	=> $this->session->userdata('ss_cashier_float_id'),
			'unique_no'	=> $this->input->post('uniq_id')
	    );	
		$sale_id  = $this->pos_model->save_sale_header($data);
		if($sale_id){
			/**
			 * save sale items
			 */
			for ($i=0; $i < count($pr_id); $i++) {			
			     $data2 = array(
         			'sale_id'   	=> $sale_id,
					'product_id' 	=> $pr_id[$i],
					'batch_id'      => $bid[$i],
         			'quantity'		=> $quantity[$i],
         			'unit_price'    => $net_price[$i],
					'item_cost'		=> $product_cost[$i],
					'gross_total'   => $ssubtotal[$i]-$discount_val[$i],
					'discount'		=> $discount_i[$i],
					'discount_val'	=>$discount_val[$i],
					'total_item_cost'	=>$product_cost[$i]*$quantity[$i],
				 );				
				$this->pos_model->sale_items_in($data2);
			}
			/**
			 * Payments
			 */
			if($pay_amount>0){
				$data = array(
					 'sale_id'                            => $sale_id,
					 'sale_pymnt_paying_by'               => $paid_by,
					 'sale_pymnt_amount'                  => $pay_amount,
					 'sale_pymnt_date_time'               => $sale_date,
					 'sale_pymnt_added_date_time'         => $sale_date,
					 'sale_pymnt_crdt_card_no'            => $cc_no,
					 'sale_pymnt_crdt_card_holder_name'   => $pcc_holder,
					 'sale_pymnt_crdt_card_type'          => $pcc_type,
					 'sale_payment_type'                  => "hw_sale",
					 'float_id'	=> $this->session->userdata('ss_cashier_float_id'),
				  );
		    $t = $this->pos_model->sales_payment($data);	
		    $sale_free_product=$this->Free_Issue_Process_Model->sale_free_product_list($sale_id);
		    $total_free_issue=0;
		    foreach($sale_free_product as $row){
		        $total_qty=$this->Free_Issue_Process_Model->get_total_sale_product_qty($row['product_id'],$sale_id,$row['batch_id']);
		        $return_result=$this->Free_Issue_Process_Model->get_relevent_free_issue_block($row['product_id'],$total_qty);
		        if($return_result){
		            $data_free_product = array(
         			'sale_id'   	=> $sale_id,
					'product_id' 	=> $row['product_id'],
					'batch_id'      => $row['batch_id'],
         			'quantity'		=> $return_result['free_qty'],
         			'unit_price'    => 0,
					'item_cost'		=> $return_result['product_cost'],
					'gross_total'   => 0,
					'discount'		=> 0,
					'discount_val'	=>0,
					'total_item_cost'	=>$return_result['product_cost']*$return_result['free_qty'],
					'is_free_issue'	=>1,
					'free_issue_id' 	=> $return_result['fr_p_id'],
				 );	
				 $total_free_issue=+$return_result['product_cost']*$return_result['free_qty'];
				$this->pos_model->sale_items_in($data_free_product);
		        }
		    }
		    if($total_free_issue!=0){
		            $pos_data=array('cost_total'=>$total_cost_val+$total_free_issue);
		        	$this->pos_model->update_hw_sale($pos_data,$sale_id);
		    }
			}
			else{$t=0;}
			/**
			 * Store Notes
			 */
			if($this->input->post('stnn1')){
				//$this->common_model->update_stn($this->input->post('stnn1_wh'),$this->input->post('stnn1'), $sale_id);
				$deliveryList = $this->input->post('deliveryList');
				for($c = 0; $c < count($deliveryList); $c++){
					for ($i=0; $i < count($pr_id); $i++) {
						if($deliveryList[$c] === $pr_id[$i]){
							$stn_data = array(
								'stn_no'		=> $this->input->post('stnn1'),
								//'stn_code'		=> $this->input->post('stnn1_code'),
								//'sale_id'   	=> $sale_id,
								'product_id' 	=> $pr_id[$i],
								'quantity'		=> $quantity[$i],
								'stn_wh_id'		=> $this->input->post('stnn1_wh'),
							);
							//$this->common_model->save_stn_items($stn_data);
						}else
						continue;
					}					
				}
			}
			if($this->input->post('stnn2')){
				//$this->common_model->update_stn($this->input->post('stnn2_wh'),$this->input->post('stnn2'), $sale_id);
				$deliveryList = $this->input->post('deliveryList2');
				for($c = 0; $c < count($deliveryList); $c++){
					for ($i=0; $i < count($pr_id); $i++) {
						if($deliveryList[$c] === $pr_id[$i]){
							$stn_data = array(
								'stn_no'		=> $this->input->post('stnn2'),
								//'stn_code'		=> $this->input->post('stnn1_code'),
								//'sale_id'   	=> $sale_id,
								'product_id' 	=> $pr_id[$i],
								'quantity'		=> $quantity[$i],
								'stn_wh_id'		=> $this->input->post('stnn2_wh'),
							);
							//$this->common_model->save_stn_items($stn_data);
						}else
						continue;
					}					
				}
			}
			if($this->input->post('stnn3')){
				//$this->common_model->update_stn($this->input->post('stnn3_wh'),$this->input->post('stnn3'), $sale_id);
				$deliveryList = $this->input->post('deliveryList3');
				for($c = 0; $c < count($deliveryList); $c++){
					for ($i=0; $i < count($pr_id); $i++) {
						if($deliveryList[$c] === $pr_id[$i]){
							$stn_data = array(
								'stn_no'		=> $this->input->post('stnn3'),
								//'stn_code'		=> $this->input->post('stnn1_code'),
								//'sale_id'   	=> $sale_id,
								'product_id' 	=> $pr_id[$i],
								'quantity'		=> $quantity[$i],
								'stn_wh_id'		=> $this->input->post('stnn3_wh'),
							);
							//$this->common_model->save_stn_items($stn_data);
						}else
						continue;
					}					
				}
			}			
				
			echo json_encode(array(
				'sale_id' => $sale_id,
				'sale_ref' => $sale_ref,
				'error' => '0',
				'disMsg' => '',
				'duplicate' => 0
			));		    
		}
        }
	}
	
	
public function view_bill(){
	$data['category_by_id_1'] = $this->pos_model->get_product_by_cat_id(1);
		$data['category'] 		  = $this->pos_model->get_all_category();
		$data['sub_category'] 	  = $this->pos_model->get_sub_category_by_cat_id(1);
		$data['get_customer']     = $this->pos_model->get_customer();
		$data['get_warehouse']    = $this->pos_model->get_warehouse();
		$this->load->view('pos/pos-bill',$data);
		//$this->load->view('pos/view_bill');
	}
function get_customers()
{
	$srh_customer_id = $this->input->get('srh_customer_id');
	$customers       = $this->pos_model->get_customers($srh_customer_id);
	echo json_encode($customers);
}
public function sale_print(){
	
	
				$data['sale_id']    = $this->input->get('sale_id');
				$data['pay_amount']    = $this->input->get('pay_amount');
				$data['paid_by']    = $this->input->get('paid_by');
				$data['balance_amount']    = $this->input->get('balance_amount');
				
				$this->load->view('pos_print_nav',$data);
				
	
	}

	function view()
	{
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = '';
        $sale_id                = $this->uri->segment('3');
        $data['sale_item_list'] = $this->pos_model->get_sale_item_list_by_sale_id($sale_id);
        if ($data['sale_item_list']) {
            $data['sale_details']       = $this->pos_model->get_sale_info($sale_id);
            $data['total_paid_amount']  = $this->pos_model->get_total_paid_by_sale_id($sale_id);
            $data['customer_details']   = $this->customer_model->get_customer_info($data['sale_details']['customer_id']);
            $data['warehouse_details']  = $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
            $data['sale_payments_list'] = $this->pos_model->get_sale_payments_by_sale_id($sale_id);
            $old_payment_tot            = 0;
            $retured_payment_tot        = 0;
            $retured_payment_msg_this   = '';
            $old_payments_dis_msg_this  = '';
            $return_sales_details       = $this->pos_model->get_return_sale_info_sale_id($sale_id);
            foreach ($return_sales_details as $row) {
                $this_balance_pament      = 0;
                $this_trn_amt             = $row->sl_rtn_total;
                $retured_payment_tot      = $retured_payment_tot + $this_trn_amt;
                $retured_payment_msg_this = $retured_payment_msg_this . ' -' . $this_trn_amt . ' ,';
            }
            $old_payment_tot              = $old_payment_tot - $retured_payment_tot;
            $data['old_payments']         = $old_payment_tot;
            $data['old_payments_dis_msg'] = "Return Total Amount ($old_payments_dis_msg_this $retured_payment_msg_this)";
            $data['sale_id']              = $sale_id;
            $this->load->view('invoice/hw_sales_details', $data);
        } else
            show_404();
    }	 
    
    function sale_details()
	{
		$sale_type = 0;
		$sale_id=$this->input->get('sale_id');
		$sale_type = $this->input->get('type');		
		$data['sale_details']= $this->pos_model->get_sale_info($sale_id);
		$data['sale_type'] = $sale_type;
		//get sale item list
		$data['sale_item_list']= $this->pos_model->get_sale_item_list_by_sale_id($sale_id);		
		$data['customer_details']= $this->customer_model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
		$data['sale_payments_list']= $this->pos_model->get_sale_payments_by_sale_id($sale_id);		
	if($this->session->userdata("ss_user_id") == 1){
	    //$data['stn_list']=$this->Store_Notes_Model->get_sore_notes_by_sale_id($sale_id);
	   // $this->load->view('models/view_bill_model_with_stn',$data);
	   $this->load->view('models/view_bill_model',$data);
	}else
        $this->load->view('models/view_bill_model',$data);
	}
	
	
	function sale_details_stn()
	{
		$sale_type = 0;
		$sale_id=$this->input->get('sale_id');
		$sale_type = $this->input->get('type');
		$stn = $this->input->get('stn');
		$data['sale_details']= $this->pos_model->get_sale_info($sale_id);
		$data['sale_type'] = $sale_type;
		//get sale item list
		$data['sale_item_list']= $this->pos_model->get_sale_item_list_by_sale_id($sale_id);		
		$data['customer_details']= $this->customer_model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
		$data['sale_payments_list']= $this->pos_model->get_sale_payments_by_sale_id($sale_id);		
	//	if($data['sale_details']['customer_id'] != 1)
	//	$data['total_sales']= 	$this->pos_model->get_all_sales_for_view($data['sale_details']['warehouse_id'],$data['sale_details']['customer_id']);
	//	if($data['sale_details']['customer_id'] != 1)
	//	$data['total_return'] = $this->pos_model->get_all_sales_return_for_view($data['sale_details']['warehouse_id'],'','',$data['sale_details']['customer_id']);		
	//	$data['total_payments'] = $this->pos_model->getPaymentsForView($data['sale_details']['warehouse_id'],'','','sale','Return_Cash','',$data['sale_details']['customer_id']);		
		//get old payments amounts
	
	
	//	$old_payment_tot=$old_payment_tot-$retured_payment_tot;		
	//	$data['old_payments']=$old_payment_tot;
	//	$data['old_payments_dis_msg']="Return Total Amount ($old_payments_dis_msg_this $retured_payment_msg_this)";		
	//	$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();		
	//	$paid_amount_=$this->Sales_Model->get_total_paid_amount_($sale_id);
	//	$data['paid_amount_'] = $paid_amount_;	
	
	    $data['stn_list']=array();//$this->Store_Notes_Model->get_sore_notes_by_sale_id($sale_id);
        if($stn)
            $this->load->view('models/view_bill_model_with_stn',$data);
        else
            $this->load->view('models/view_bill_model_without_stn',$data);
	}
	
	function sale_details_stn_duplicate()
	{
		$sale_type = 0;
		$sale_id=$this->input->get('sale_id');
		$sale_type = $this->input->get('type');
		$stn = $this->input->get('stn');
		$data['sale_details']= $this->pos_model->get_sale_info($sale_id);
		$data['sale_type'] = $sale_type;
		//get sale item list
		$data['sale_item_list']= $this->pos_model->get_sale_item_list_by_sale_id($sale_id);		
		$data['customer_details']= $this->customer_model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
		$data['sale_payments_list']= $this->pos_model->get_sale_payments_by_sale_id($sale_id);		
	//	if($data['sale_details']['customer_id'] != 1)
	//	$data['total_sales']= 	$this->pos_model->get_all_sales_for_view($data['sale_details']['warehouse_id'],$data['sale_details']['customer_id']);
	//	if($data['sale_details']['customer_id'] != 1)
	//	$data['total_return'] = $this->pos_model->get_all_sales_return_for_view($data['sale_details']['warehouse_id'],'','',$data['sale_details']['customer_id']);		
	//	$data['total_payments'] = $this->pos_model->getPaymentsForView($data['sale_details']['warehouse_id'],'','','sale','Return_Cash','',$data['sale_details']['customer_id']);		
		//get old payments amounts
	
	
	//	$old_payment_tot=$old_payment_tot-$retured_payment_tot;		
	//	$data['old_payments']=$old_payment_tot;
	//	$data['old_payments_dis_msg']="Return Total Amount ($old_payments_dis_msg_this $retured_payment_msg_this)";		
	//	$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();		
	//	$paid_amount_=$this->Sales_Model->get_total_paid_amount_($sale_id);
	//	$data['paid_amount_'] = $paid_amount_;	
	    $data['is_dublicated']=1;
	    $data['stn_list']=array();//$this->Store_Notes_Model->get_sore_notes_by_sale_id($sale_id);
        if($stn)
            $this->load->view('models/view_bill_model_with_stn',$data);
        else
            $this->load->view('models/view_bill_model_without_stn',$data);
	}
	
	
	function sale_details_stn_reprint()
	{
	    $last_sale_id=$this->pos_model->get_last_sale_id();	
	    if($last_sale_id>0){
		$sale_type = 0;
		$sale_id=$last_sale_id;
		$sale_type = $this->input->get('type');
		$stn = $this->input->get('stn');
		$data['sale_details']= $this->pos_model->get_sale_info($sale_id);
		$data['sale_type'] = $sale_type;
		//get sale item list
		$data['sale_item_list']= $this->pos_model->get_sale_item_list_by_sale_id($sale_id);		
		$data['customer_details']= $this->customer_model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
		$data['sale_payments_list']= $this->pos_model->get_sale_payments_by_sale_id($sale_id);	
	    $data['stn_list']=array();//$this->Store_Notes_Model->get_sore_notes_by_sale_id($sale_id);
	    $data['is_dublicated']=1;
        if($stn)
            $this->load->view('models/view_bill_model_with_stn',$data);
        else
            $this->load->view('models/view_bill_model_without_stn',$data);
            
            
	    }else{
	       echo "No DATA"; 
	    }
	}
	
	function clear_sale()
    {
        $sale_id      = $this->input->post('sale_id');
        $warehouse_id = $this->input->post('warehouse_id');
        $result       = $this->pos_model->clear_sale($sale_id, $warehouse_id);
        return $result;
    }
}