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

class Purchases_Return extends CI_Controller {

    var $main_menu_name = "purchases_return";
	var $sub_menu_name = "purchases_return";

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Supplier_Model');
		$this->load->model('Warehouse_Model');
		$this->load->model('Common_Model');
		$this->load->model('User_Model');
		$this->load->model('Purchases_Return_Models');
		$this->load->model('product_models');
		$this->load->model('Stock_Counter_Model');
	}
	
		public function index($e=0)
    {
      $data['error'] = $e;
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = "purchases_return";
      $this->load->view('purchase_return/purchases_return_list',$data);
    }
	
	


	 public function add_purchase_return()
    {
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'purchases_return';
		//get sale id
		$id=$this->input->get('grn_no');
		$data['sale_item_list']=array();
		$data['sale_details']= $this->Purchases_Return_Models->get_purchase_master_details($id);
		$data['total_paiment']=0;
		$data['sale_id']=$id;
        $this->load->view('purchase_return/purchase_return_add',$data);
    }
    	function return_suggestion_grn()
	{
		$page='';
		$page=$this->input->get('page');
		$id=$this->input->get('grn_id');
		$term=$this->input->get('term');
		$in_type=$this->input->get('t');
		$data['sales'] = $this->Purchases_Return_Models->get_purchase_item_details($term,$id);
		
		$json = array();
		foreach ($data['sales'] as $row)
		{			
			//set price
			$price_tmp=0;
			$product_id=$row['product_id'];
			$product_name=$row['product_mat_name'];
			$product_code=$row['product_mat_code'];
			$product_part_no=$row['product_mat_part_no'];
			$product_oem_part_number=$row['product_mat_oem_part_number'];
			$product_price=$row['unit_price'];
			$product_cost =$row['unit_price'];
			$quantity=$row['quantity'];
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			$extraName.=", Purchased Price: ".number_format($product_price, 2, '.', ',');
			if( $row['batch_ref_number']) $extraName.=", Btatch No: ". $row['batch_ref_number'];
			if( $row['batch_ref_number']) $extraName.=", Purchased Date:  ".$row['date'];			
			$return_qty_temp=0;		
			$return_qty = 0;
			$batch_stock_count=$this->Stock_Counter_Model->get_stock_balance_batch('',$row['product_id'],$row['batch_id']);
            $avb_grn_return_qty=$this->Stock_Counter_Model->get_purchased_stock_balance($row['product_id'],$row['id']);
			$qty_in_stock=$avb_grn_return_qty;
			if($batch_stock_count<$avb_grn_return_qty){
			    $qty_in_stock=$batch_stock_count;
			}
			$extraName.=", Qty in stock: ".$qty_in_stock;
			if($qty_in_stock>0)
			{
			 $json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_mat_code'] ,
					'product_name'=>$row['product_mat_name'],
					'batch_id'=> $row['batch_id'],
					'grn_item_id'=> $row['id'],
					'product_price'=> $product_price,
					'product_part_no'=> $row['batch_ref_number'],
					'item_cost'=> $product_cost,
					'qty_in_stock'=> $qty_in_stock,
					'product_oem_part_number'=> $row['batch_ref_number'],
                    'value'=> $row['product_mat_name']." (".$row['product_mat_code'].")",
                    'label'=> $row['product_mat_name']." (".$row['product_mat_code'].")$extraName"
                    );
					array_push($json,$json_itm);
										
			}
		}		
		echo json_encode($json);		
	}
	
	function save_purchase_return()
	
	{
		$rowCount=$this->input->post('rowCount');
		$sl_rtn_datetime_1=$this->input->post('sl_rtn_datetime');
		$sl_rtn_datetime=date('Y-m-d H:i:s', strtotime($sl_rtn_datetime_1));
		$user_id=$this->session->userdata('ss_user_id');
		$error='';
		$disMsg='';
		$lastid='';
		$sl_rtn_id='';
		/* payment validation start */
		$sale_pymnt_amount=$this->input->post('sale_pymnt_amount');
		$sale_id=$this->input->post('sale_id');
		$sale_pymnt_ref_no=$this->input->post('sale_pymnt_ref_no');
		$sale_pymnt_paying_by=$this->input->post('sale_pymnt_paying_by');
		$sale_pymnt_date_time=$sl_rtn_datetime;
		$sale_pymnt_date_time_send=date('Y-m-d H:i:s', strtotime($sale_pymnt_date_time));
		$sale_pymnt_cheque_no=$this->input->post('sale_pymnt_cheque_no');
		$sale_pymnt_crdt_card_no=$this->input->post('sale_pymnt_crdt_card_no');
		$sale_pymnt_crdt_card_holder_name=$this->input->post('sale_pymnt_crdt_card_holder_name');
		$sale_pymnt_crdt_card_month=$this->input->post('sale_pymnt_crdt_card_month');
		$sale_pymnt_crdt_card_year=$this->input->post('sale_pymnt_crdt_card_year');
		$sale_pymnt_crdt_card_type=$this->input->post('sale_pymnt_crdt_card_type');
		$cr_interest=$this->input->post('cr_interest');
		$cr_interest_amt=$this->input->post('cr_interest_amt');
		$in_type=$this->input->post('in_type');
		$sales_return_cost_total=$this->input->post('sales_return_cost_total');
		$sale_pymnt_note=$this->input->post('sale_pymnt_note');
		$user_id=$this->session->userdata('ss_user_id');
		$sale_pymnt_added_date_time=date("Y-m-d H:i:s");
		$sale_pymnt_id='';
        $this->load->library('form_validation'); //form validation lib
       // $this->form_validation->set_rules('sale_pymnt_amount', 'Amount', 'required');
        $sale_reference_no	= $this->Common_Model->gen_ref_number('pur_return_id','purchase_return','RGRN'); 
		if($sale_pymnt_paying_by=='Credit Card'){
			$this->form_validation->set_rules('sale_pymnt_crdt_card_type', 'Card Type', 'required');
			$this->form_validation->set_rules('sale_pymnt_crdt_card_no', 'Credit Card No', 'required');
			$this->form_validation->set_rules('sale_pymnt_crdt_card_holder_name', 'Holder Name', 'required');
			$this->form_validation->set_rules('sale_pymnt_crdt_card_month', 'Month', 'required');
			$this->form_validation->set_rules('sale_pymnt_crdt_card_year', 'Year', 'required');
		}
		if($sale_pymnt_paying_by=='Cheque'){
			$this->form_validation->set_rules('sale_pymnt_cheque_no', 'Cheque No', 'required');
		}
		$this->form_validation->set_rules('sale_id', 'System Error', 'required');
		if($sale_pymnt_amount){
		$tmp=number_format($sale_pymnt_amount, 2, '.','');
		}else{
			$tmp=0;
		}
		if(!$error){
			$data=array(
				'pur_r_ref_no'=>$sale_reference_no,
				'grn_id'=>$this->input->post('sale_id'),
				'supplier_id'=>$this->input->post('customer_id'),
				'warehouse_id'=>$this->input->post('warehouse_id'),
				'pur_return_date_time'=>$sl_rtn_datetime,
				'discount_deduction'=>$this->input->post('sl_rtn_inv_discount'),
				'total_net_amount'=>$this->input->post('sales_return_cost_total'),
				'system_date_time'=>date('Y-m-d H:i:s'),
				'total_discount_deduction'=>$this->input->post('sl_rtn_inv_discount_amount'),
				'pur_r_remarks'=>$this->input->post('sl_rtn_note'),
				'user_id'=>$user_id,
				'ref_no'=>$in_type,
				'total_gross_amount'=>$this->input->post('sales_return_cost_total'),
			);
	 	    $lastid=$this->Purchases_Return_Models->save_purchase_return($data);
			$sl_rtn_id=$lastid;
			$disMsg='Sale return successfully added';
			//insert sale item data
			$row=$this->input->post('row');
			$rowCount=$this->input->post('rowCount');
			$data_item=array();
			for($i=1; $i<=$rowCount; $i++){
				if(isset($row[$i]['product_id'][0]))
				{
				$data_item=array(
					'pur_return_id'=>$sl_rtn_id,
					'product_id'=>$row[$i]['product_id'][0],
					'quantity'=>$row[$i]['qty'][0],
					'discount'=>$row[$i]['discount'][0],
					'unit_price'=>$row[$i]['unit_price'][0]+$row[$i]['item_price_p'][0],
					'discount_val'=>$row[$i]['discount_val'][0], 
					'gross_total'=>$row[$i]['gross_total'][0],
					'batch_id'=>$row[$i]['batch_id'][0],
					'grn_item_id'=>$row[$i]['grn_item_id'][0],
				);
				$slrtnitmid=$this->Purchases_Return_Models->save_purchase_return_item($data_item);
				}
			}
		}else {
			$error=true;
		}
		echo json_encode(array('sale_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg,));
	}	
	
		public function purchase_return_details()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = '';
		$sl_rtn_id=$this->uri->segment('3');
		$data['sale_rtn_item_list']= $this->Purchases_Return_Models->get_purchase_return_item_list($sl_rtn_id);
		$data['sale_rtn_details']= $this->Purchases_Return_Models->get_purchase_return_master_details($sl_rtn_id);
		$data['total_paid_amount']=0;
		$data['sl_rtn_id']=$sl_rtn_id;
        $this->load->view('purchase_return/purchase_return_details',$data);
	}
	
	

    public function get_list_purchases_return($value='')
    {
            $values = $this->Purchases_Return_Models->get_purchase_master_list();
            $data = array();
            $pay_st;
            if (!empty($values)) {
                foreach ($values as $purchases) {
                
                if (empty($purchases->total_net_amount)) {
                  $pay_st = '<span class="label label-warning">Pending</span>';
                }else{
                  if ($purchases->total_net_amount >= $purchases->total_net_amount) {
                    $pay_st = '<span class="label label-success">Paid</span>';
                  }else{
                    $pay_st = '<span class="label label-info">Partial</span>';
                  }
                }
                $row = array();
                    $row[] = $purchases->pur_return_date_time;
                    $row[] = $purchases->pur_r_ref_no;
                    $row[] = $purchases->supp_company_name;
					$row[] = $purchases->ref_no;
                    $row[] = number_format($purchases->total_net_amount,2,'.',',');
                    $row[] = number_format($purchases->total_net_amount,2,'.',',');
                    $row[] = number_format($purchases->total_net_amount - $purchases->total_net_amount,2,'.',',');
                    $row[] = "";//$pay_st;
                    $row[] = '<div class="text-center"><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('purchases_return/add_purchase_return?grn_no='.$purchases->pur_return_id).'"><i class="fa fa-undo"></i> GRN Return</a></li>-->
                    <li><a href="'.base_url('purchases_return/purchase_return_details/'.$purchases->pur_return_id).'"><i class="fa fa-file-text-o"></i> GRN Return Details</a></li>
                    </ul></div>
                    </div>';
                    $data[] = $row;
                }
                $output = array('data' =>$data);
                echo json_encode($output);
            }else{
                $output = array('data' =>'');
                echo json_encode($output);
            }
       }
       
       public function purchese_return_suggesstions_list()
    {
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'purchese_return_suggesstions_list';
        $this->load->view('purchase_return/purchese_return_suggesstions_list',$data);
    }
    
     public function get_list_batch_product_suggesstion($value = '')
    {
        $this->load->model('Marketing_Delivery_Model');
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->Purchases_Return_Models->getProducts($start, $length, $search_key_val);
        $value_count    = $this->Purchases_Return_Models->getProducts('', '', $search_key_val);
        if ($search_key_val) {
            $values_c  = $this->Purchases_Return_Models->getProducts('', '', $search_key_val);
            $totalData = 100; //count($values_c);    
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $open = "";$close = "";
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                
                $batch_stock_count=$this->Stock_Counter_Model->get_stock_balance_batch('',$products->product_id,$products->batch_id);
                $avb_grn_return_qty=$this->Stock_Counter_Model->get_purchased_stock_balance($products->product_id,$products->id);
                if($batch_stock_count<$avb_grn_return_qty){$avb_grn_return_qty=$batch_stock_count;}
                $k='';
                $retVal              = (empty($products->sub_cat_name)) ? "--:--" : $products->sub_cat_name;
                $row                 = array();
                $ss_warehouse_id =  "";//$this->session->userdata('ss_warehouse_id');
                $qty=$products->quantity;
                $row[]               = $open.$products->product_mat_code.$close;
                $row[]               = $open.$products->product_mat_name.$close;
                $row[]  = $products->batch_ref_number; 
                $row[]  = $products->name;
                $row[]  = $batch_stock_count;
                $row[]  = $products->reference_no;
                $row[]  = $products->date;
                $row[] = $products->unit_price;
                //$row[]  = $open.$products->retail_price.$close;
                $row[]  = $products->quantity;
                $row[]  = $avb_grn_return_qty;
                $actdes = '';
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs ' . $k . ' dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="' . base_url('purchases_return/add_purchase_return?grn_no=') .$products->grn_master_id . '"><i class="fa fa-file-text-o"></i> GRN Return</a></li>
                            ';
                $row[]  = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	














	
	

	
	
	
	
	
	
	
}