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

class Sample_Process extends CI_Controller {

    var $main_menu_name = "sample_process";
	var $sub_menu_name = "sample_process";

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

		$this->load->model('Sample_Process_Model');
		$this->load->model('Warehouse_Model');
		$this->load->model('Common_Model');
		$this->load->model('User_Model');
		$this->load->model('Purchases_Model');		
	}
	
	//Sales list page load
	public function index()
	{		
		//$data['sales_rep_issues']=$this->Sales_Rep_Issue_Model->get_all_sales_rep_issue();
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
        $this->load->view('sample/list_sample_order',$data);
	}	
	
	
	public function manage()
	{	
		$sample_order_id =  $this->uri->segment(3);	
					
		if ($sample_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['type']='A';
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='manage';
		$this->load->view('sample/sample_manage',$data); 		
		}		
	}	
	
	public function get_product_suggestion()
	{		
		$term=$this->input->get('term');
		$data['product']=$this->Sample_Process_Model->get_product_suggestion($term);
		$in_type=$this->input->get('t');		
		$json=array();
		foreach ($data['product'] as $row)
		{
		 $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"
                    );		
		array_push($json,$json_itm);						
		}		
		echo json_encode($json);	
	}
	
	
	public function sample_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->Sample_Process_Model->get_sample_order_master_details($order_id);
		$data['sample_order_items_details']=$this->Sample_Process_Model->get_sample_order_item_details($order_id);		
		$data['SMPID']=$order_id;
		$this->load->view('sample/sample_order_details',$data);	
	}
	
	
	public function sales_rep_issue_details_print()
	{
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='';
		$sale_rep_issue_id=$this->input->get('sale_rep_issue_id');
		$rep_id=$this->Sales_Rep_Issue_Model->get_sales_detail_by_sales_rep_issue_id($sale_rep_issue_id);
		$whare_id=$this->Sales_Rep_Issue_Model->get_sales_detail_by_sales_rep_issue_id($sale_rep_issue_id);
		$rep_id=$this->Sales_Rep_Issue_Model->get_sales_detail_by_sales_rep_issue_id($sale_rep_issue_id);
		
		$sales_rep_id=$rep_id['sales_rep_id'];
		$id=$whare_id['wharehouse_id'];
		
		$data['SRID']=$sale_rep_issue_id;
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='';
		$data['wharehose_details']=$this->Warehouse_Model->get_warehouse_info($id);
		$data['sales_rep_details']=$this->User_Model->get_rep_first_and_second_name_by_id($sales_rep_id);
		$data['sales_rep_issue_details']=$this->Sales_Rep_Issue_Model->get_sales_detail_by_sales_rep_issue_id($sale_rep_issue_id);
		$data['sales_rep_issue_items_details']=$this->Sales_Rep_Issue_Model-> get_sale_rep_issue_item_list_by_sale_id($sale_rep_issue_id);	
		 
		 $this->load->view('models/sales_rep_issue_details_print',$data);
	}
	
	
	
	public function list_sample_order_list()
	{	
	
	$data=array();	
	$sales_rep_issue=$this->Sample_Process_Model->get_sample_order_master_list();	
	foreach ( $sales_rep_issue as $row)
	{
		$sample_master_id=$row['sample_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().'sales_rep_issue2/sales_rep_issue_details/'.$sample_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Details</a></li>							
                            </ul></div>';			
		}
		else
		{
			if($row['status']==1)
			{
			$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().'sales_rep_issue2/sales_rep_issue_details/'.$sample_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Details</a></li>
							<li><a href="'.base_url().'sales_rep_issue2/manage/'.$sample_master_id.'"><i class="fa fa-file-text-o"></i> Sale Rep Issue Edit</a></li>
							<li><a href="'.base_url().'sales_rep_issue2/sales_rep_return/'.$sample_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['sample_order_date'];
		$nestedData[]=$row['sample_ref_no'];
		$nestedData[]=$row['user_first_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_sample_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');
		$status="ORDER_GENETARE";		
		$ref_code=$this->Common_Model->gen_ref_number('sample_master_id','sample_order_master','SMP');
		$data=array(		
			'sample_ref_no'=>$ref_code,			
		 	'route_id'=>$route_id,
			'wharehouse_id'=>$warehouse_id,
			'order_rep_id'=>$sales_rep_id,
			'sample_order_date'=>$sales_rep_issue_date,
			'added_date_time'=>$added_date_time,
			'total_amount'=>$total_amount,
			'status'=>$status,			
			'entered_user_id'=>$this->session->userdata('ss_user_id')			
			);
			$_insert=$this->Sample_Process_Model->insert_update_master_table($data,'');
			$lastid=$this->db->insert_id();				
			//insert user activity
			$this->Common_Model->add_user_activitie("Added Sample Order, (Sample Order:$ref_code)");
			$disMsg='Sample 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(					
					'sample_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->Sample_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', 'Sample Order Successfully added!');		
		echo json_encode(array('id'=>$lastid,'error'=>0,'disMsg'=>$disMsg));		
	}
	
	
	
}