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

class Lot_Process extends CI_Controller {

    var $main_menu_name = "lot_process";
	var $sub_menu_name = "lot_process";

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

		$this->load->model('Lot_Process_Model');
		$this->load->model('Warehouse_Model');
		$this->load->model('Common_Model');
		$this->load->model('User_Model');
		$this->load->model('Purchases_Model');
		$this->load->model('Transfer_Model');
		$this->load->model('Product_Damage_Model');
		$this->load->model('Sales_Return_Model');
		$this->load->model('Marketing_Delivery_Model');		
	}
	
	//Sales list page load
	public function index()
	{		
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
        $this->load->view('lot/list_lot_order',$data);
	}	
	
	public function lot_loaded()
	{		
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = "lot_loaded";
        $this->load->view('lot/list_lot_loaded_orde',$data);
	}	
	
	
	public function manage()
	{	
		$lot_order_id =  $this->uri->segment(3);	
		$this->load->model('Customer_Model');		
		if ($lot_order_id==0)
		{			
		$data['warehouse_list']=$this->Warehouse_Model->get_all_warehouse();
		$data['sales_rep_list']=$this->User_Model->get_all_sales_user_reps();
		$data['customer_list']  = $this->Customer_Model->get_all_customers();
		$data['type']='A';
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='manage';
		$this->load->view('lot/lot_manage',$data); 		
		}		
	}	
	
	public function get_product_suggestion()
	{		
		$term=$this->input->get('term');
		$product=$this->Lot_Process_Model->get_product_suggestion($term);
		$in_type=$this->input->get('t');		
		$json=array();
		foreach ($product as $row)
		{
			//$warehouse_id = $this->session->userdata('ss_warehouse_id');
			$warehouse_id = '';
		//stock check 	
		$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($warehouse_id,$row['product_id']);
		//echo "transferd:".$transferd_qty."\n";
		$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($warehouse_id,$row['product_id']);
		//echo "recieved:".$transfer_reseve_qty."\n";
		$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($warehouse_id,$row['product_id']);
		//echo "purchased:".$purchased_qty."\n";
		$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($warehouse_id,$row['product_id']);				
		//echo "damaged:".$product_damaged_qty."\n";
		$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($warehouse_id,$row['product_id']);					
		//echo "sales return:".$sales_return_qty."\n";
		$issue_qty=$this->Marketing_Delivery_Model->get_all_delivery_product_item($warehouse_id,$row['product_id']);	
		//echo "issue:".$issue_qty."\n";
		$return_qty=$this->Marketing_Delivery_Model->get_all_return_product_item($warehouse_id,$row['product_id']);
		//echo "return_qty".$return_qty."\n";
		//echo "\n";
	
		$qty =	$purchased_qty-$issue_qty+$return_qty-$product_damaged_qty+$transfer_reseve_qty-$transferd_qty;			
			
			
		//	
			
			
			
		 $product_id=$row['product_id'];
		 $product_code =$row['product_code'];
		 $product_name=$row['product_name'];
		 $product_oem_part_number=$row['product_oem_part_number'];
		 $product_part_no=$row['product_part_no'];
		 $product_cost=$row['product_cost']; 
		 $product_price=$row['product_price'];
		 $wholesale_price=$row['wholesale_price']; 
		 $credit_salling_price=$row['credit_salling_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
		 if($product_part_no) $selling_R_price.=", Part No: $product_part_no";
		 if($product_oem_part_number) $selling_R_price.=", OEM Part No: $product_oem_part_number";		
		 $json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $row['product_price'],
					'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'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].") / $selling_R_price"." / IN SROCK : ".$qty ,
					'qty'=> $qty,
                    );		
		array_push($json,$json_itm);						
		}		
		echo json_encode($json);	
	}
	
	
	public function lot_order_details()
	{
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='';		
		$order_id =  $this->uri->segment(3);		
		$data['sm_or_det']=$this->Lot_Process_Model->get_lot_order_master_details($order_id);
		$data['lot_order_items_details']=$this->Lot_Process_Model->get_lot_order_item_details($order_id);		
		$data['SMPID']=$order_id;
		$this->load->view('lot/lot_order_details',$data);	
	}
	
	
	public function sales_rep_issue_details_print()
	{
		$this->load->model('Customer_Model');	
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='';		
		$order_id =  $this->uri->segment(3);		
		$data['sm_or_det']=$this->Lot_Process_Model->get_lot_order_master_details($order_id);
		//print_r($data['sm_or_det']['customer_id']);
		$data['customer_info'] = $this->Customer_Model->get_customer_info($data['sm_or_det']['customer_id']);
		//print_r($data['customer_info']);
		$data['lot_order_items_details']=$this->Lot_Process_Model->get_lot_order_item_details($order_id);		
		$data['SMPID']=$order_id;
		$this->load->view('lot/sales_rep_issue_details_print',$data);
	}
	
	function bill()
	{
		$this->load->model('Customer_Model');	
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='';
		$order_id =  $this->uri->segment(3);		
		$data['sm_or_det']=$this->Lot_Process_Model->get_lot_order_master_details($order_id);
		//print_r($data['sm_or_det']['customer_id']);
		$data['customer_info'] = $this->Customer_Model->get_customer_info($data['sm_or_det']['customer_id']);
		//print_r($data['customer_info']);
		$data['lot_order_items_details']=$this->Lot_Process_Model->get_lot_order_item_details($order_id);		
		$data['SMPID']=$order_id;
		$this->load->view('lot/billkwageekak',$data);
	}
	
	
	
	public function list_lot_order_list()
	{
	$this->load->model('Customer_Model');
	$data=array();	
	$sales_rep_issue=$this->Lot_Process_Model->get_lot_order_master_list();	
	foreach ( $sales_rep_issue as $row)
	{
		$lot_master_id=$row['lot_master_id'];
		$customer_details= $this->Customer_Model->get_customer_info($row['customer_id']);	
		$pay_st = '<span class="label label-danger">Error</span>';		
		if($row['status']==1)
		{
			$pay_st = '<span class="label label-success">Completed</span>';	
			$action='<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().'lot_process/lot_order_details/'.$lot_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Details</a></li>							
                            </ul></div>';			
		}
		else
		{
			if($row['status']==0)
			{
			$pay_st = '<span class="label label-warning">Pending</span>';	
			$action='<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().'lot_process/lot_order_details/'.$lot_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Details</a></li>
							<li><a href="'.base_url().'lot_process/manage/'.$lot_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Edit</a></li>
							<li><a href="'.base_url().'lot_process/sales_rep_return/'.$lot_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Return</a></li>							
                            </ul></div>';
			}
			else
			{			
			$pay_st = '<span class="label label-danger">Error</span>';
			}			
		}		
		$nestedData=array();		
		//print_r($sales_rep_issue_id);
		$nestedData[]=$row['lot_order_date'];
		$nestedData[]=$row['lot_ref_no'];
		$nestedData[]=$row['user_first_name'];
		$nestedData[]=$customer_details['cus_name'];
		$nestedData[]=$row['route_name'];
		$nestedData[]=$row['total_amount'];
		$nestedData[]=$pay_st;
		$nestedData[]=$action;	
		$data[]=$nestedData;
	}	
	
	
	$json_data = array(
	"data"=>$data
	);
	
	echo json_encode($json_data);
	
		
	}
	
	function save_lot_order()
	{	
	
		$this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|trim|xss_clean');
		$this->form_validation->set_rules('sales_rep_id', 'Salse Rep', 'required|trim|xss_clean');		
		$this->form_validation->set_rules('route_id', 'Route', 'required|trim|xss_clean');
		$this->form_validation->set_rules('sales_rep_issue_datetime', 'Date','required|trim|xss_clean');
        if ($this->form_validation->run() == FALSE)
        {
           echo json_encode(array('id'=>0,'error'=>1,'disMsg'=>validation_errors()));
        }
        else
        {			    
		$warehouse_id=$this->input->post('warehouse_id');
		$sales_rep_id=$this->input->post('sales_rep_id');
		$route_id=$this->input->post('route_id');	
		$temp_date=$this->input->post('sales_rep_issue_datetime');
		$add_sales_excess_price=$this->input->post('item_price_p_1');
		$add_sales_discount_price=$this->input->post('discount_1');
		$sales_rep_issue_date=date('Y-m-d', strtotime($temp_date));
		$added_date_time =date('Y-m-d H:i:s');
		$last_modified_date_time=date('Y-m-d H:i:s');
		$total_amount=$this->input->post('sale_total');
		$route_id=$this->input->post('route_id');
		$customer_id=$this->input->post('customer_id');
		$status="ORDER_GENETARE";		
		$ref_code=$this->Common_Model->gen_ref_number('lot_master_id','lot_order_master','COB');
		$data=array(		
			'lot_ref_no'=>$ref_code,			
		 	'route_id'=>$route_id,
			'wharehouse_id'=>$warehouse_id,
			'order_rep_id'=>$sales_rep_id,
			'lot_order_date'=>$sales_rep_issue_date,
			'added_date_time'=>$added_date_time,
			'total_amount'=>$total_amount,
			'status'=>$status,
			'customer_id' =>	$customer_id,
			'entered_user_id'=>$this->session->userdata('ss_user_id')			
			);
			$_insert=$this->Lot_Process_Model->insert_update_master_table($data,'');
			$lastid=$this->db->insert_id();				
			//insert user activity
			$this->Common_Model->add_user_activitie("Added lot Order, (lot Order:$ref_code)");
			$disMsg='lot successfully added';				
			$row=$this->input->post('row');
			$rowCount=$this->input->post('rowCount');
			$data_items =array();			
			for($i=1; $i<=$rowCount; $i++){				
				if(isset($row[$i]['product_id'][0]))
				{					
				$after_discount_price=$row[$i]['unit_price'][0]+$row[$i]['item_price_p'][0]-$row[$i]['discount_val'][0];					
				$data_item=array(					
					'lot_order_master_id'=>$lastid,
					'product_id'=>$row[$i]['product_id'][0],
					'order_qty'=>$row[$i]['qty'][0],
					'product_price'=>$row[$i]['unit_price'][0],
					'product_cost'=>$row[$i]['item_cost'][0],				
					'add_sales_excess_price'=>$row[$i]['item_price_p'][0],
					'add_sales_discount_price'=>$row[$i]['discount_val'][0],
					'after_discount_added_price'=>$after_discount_price,
					'total_price'=>$after_discount_price*$row[$i]['qty'][0],
					'total_cost'=>$row[$i]['item_cost'][0]*$row[$i]['qty'][0],	
					'issue_qty'=>$row[$i]['qty'][0],				
				);
				$this->Lot_Process_Model->insert_update_item_table($data_item,'');
				$itemid=$this->db->insert_id();				
				}
			}			
		}		
		if($lastid)
		{
			$disMsg='Order Successfully Saved';
		}
		else
		{
			$disMsg='Error!, Not saved . Please contact System Administrator';
		}		
		$this->session->set_flashdata('message', 'lot Order Successfully added!');		
		echo json_encode(array('id'=>$lastid,'error'=>0,'disMsg'=>$disMsg));		
	}
	
	
	
	public function list_lot_order_loaeded_list()
	{
	
	$data=array();	
	$sales_rep_issue=$this->Lot_Process_Model->get_lot_order_master_loaded_list();	
	foreach ( $sales_rep_issue as $row)
	{
		$lot_master_id=$row['lot_master_id'];		
		$pay_st = '<span class="label label-danger">Error</span>';		
		if($row['status']==1)
		{
			$pay_st = '<span class="label label-success">Completed</span>';	
			$action='<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().'lot_process/lot_order_details/'.$lot_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Details</a></li>							
                            </ul></div>';			
		}
		else
		{
			if($row['status']==0)
			{
			$pay_st = '<span class="label label-warning">Pending</span>';	
			$action='<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().'lot_process/lot_order_details/'.$lot_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Details</a></li>
							<li><a href="'.base_url().'lot_process/manage/'.$lot_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Edit</a></li>
							<li><a href="'.base_url().'lot_process/sales_rep_return/'.$lot_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Return</a></li>							
                            </ul></div>';
			}
			else
			{			
			$pay_st = '<span class="label label-danger">Error</span>';
			}			
		}		
		$nestedData=array();		
		//print_r($sales_rep_issue_id);
		$nestedData[]=$row['lot_order_date'];
		$nestedData[]=$row['lot_ref_no'];
		$nestedData[]=$row['user_first_name'];
		$nestedData[]=$row['cus_name'];
		$nestedData[]=$row['route_name'];
		$nestedData[]=$row['total_amount'];
		$nestedData[]=$pay_st;
		$nestedData[]=$action;	
		$data[]=$nestedData;
	}	
	
	
	$json_data = array(
	"data"=>$data
	);
	
	echo json_encode($json_data);
	
		
	}
	
	
	
}