<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Auth\Middleware\Authenticate;
use Auth;
use App\CategoryMaster;
use App\Product;
use App\UnitMeasurement;
use App\GradeMaster;
use App\CustomerProduct;
use App\Customer;
use App\ProductUnit;
use App\ProductGrade;
use App\MaterialRequisition;
use App\MRproduct;
use App\NotificationType;
use App\Notification;
use App\NotificationStatus;
use App\ProductNotification;
use App\MRapprovalproduct;
use App\Pallet;
use App\Common;
use App\DamageEntry;
use App\DamageProduct;
/**
* 
*/
class DamageOrderController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }
    
	public function approveIndex()
	{		
		$requests = DamageEntry::where('status','=','REQ')->orderBy('entry_date')->get();
		return view('damage_orders/index',compact('requests'));
	}

	public function approveEdit($id)
	{
		$dmg_entry = DamageEntry::find($id);
		$dmg_products = DamageProduct::where('damage_entery_id','=',$id)->get();
		return view('damage_orders/product_lists', compact('dmg_entry','dmg_products'));
	}

	public function approveDamageOrder($id,Request $request)
	{
		if($request->get('action_btn') == "Cancel")
		{
			DamageEntry::find($id)->update(['status' => 'REJ','approved_date' => date('Y-m-d')]);
		}
		if($request->get('action_btn') == "Approve")
		{
			DamageEntry::find($id)->update(['status' => 'APR','approved_date' => date('Y-m-d')]);
			
		}
		
		return redirect()->route('approve.damage.orders');
	}

	public function approvedIndex(Request $request)
	{
		if($request->get('date')) {
			$date = explode('-', $request->get('date'));
			$to = date('Y-m-d',strtotime($date[1]));
			$from = date('Y-m-d',strtotime($date[0]));	
		} else {
			$from = date('Y-m-01');
			$to = date('Y-m-t');
		}
		
		$damage_orders = DamageEntry::where('entry_date','>=',$from)->where('entry_date','<=',$to)
				   ->whereIn('status',['REJ','APR'])->orderBy('entry_date')->get();

		return view('damage_orders/approved_orders',compact('damage_orders'));
	}

	public function showApprovedDamageOrder($id)
	{
		$dmg_entry = DamageEntry::find($id);
		$dmg_products = DamageProduct::where('damage_entery_id','=',$id)->get();
		return view('damage_orders/show_products', compact('dmg_entry','dmg_products'));
	}

	public function showProduct(Request $request)
	{
		$cat_id = $request->get('option');
		$customer = Auth::User()->customer_id;
		$customerType = Auth::User()->customer->customer_type_id;

		if($customerType == 3)
		{
		$cus_prd = CustomerProduct::where('customer_id','=',$customer)->pluck('product_id')->toArray();
		$product = Product::whereIN('id',$cus_prd)->where('category_id','=',$cat_id)
									->where('is_active' ,'=' ,'Y')->get();
		}else{
			$product = Product::where('category_id','=',$cat_id)
									->where('is_active' ,'=' ,'Y')->get();
		}
		

		return $product;
	}

	public function showUnit(Request $request)
	{
		$prod_id = $request->get('option');
		$unit = ProductUnit::join('unit_of_measurement','unit_of_measurement.id','=','product_unit.unit_id')
				->selectRaw('unit_of_measurement.unit,unit_of_measurement.id')
				->where('product_unit.product_id','=',$prod_id)
				->get();
		$grade = ProductGrade::join('grade_master','grade_master.id','=','product_grade.grade_id')
				->selectRaw('grade_master.grade,grade_master.id')
				->where('product_grade.product_id','=',$prod_id)
				->get();
		$data = array($unit,$grade);

		return $data;
	}

	public function showGrade(Request $request)
	{
		$product_id = $request->get('prd');
		

		$grade = ProductGrade::join('grade_master','grade_master.id','=','product_grade.grade_id')
					->selectRaw('grade_master.grade,grade_master.id')
					->where('product_grade.product_id','=',$product_id)
					->get();

		return $grade;
	}

	public function requestSubmit(Request $request)
	{
		if (isset($_POST['submit'])) {
			MaterialRequisition::where('id','=',$request->get('x'))
					->update(['status' => 'REQ','approved_date' => date('Y-m-d H:i:s'), 'approved_by' => Auth::user()->id]);
		}

		if (isset($_POST['draft'])) {
			MaterialRequisition::where('id','=',$request->get('x'))
					->update(['status' => 'DRT','approved_date' => date('Y-m-d H:i:s'), 'approved_by' => Auth::user()->id]);
		}

		return redirect()->route('material_request.list');
	}

	public function deleteProduct(Request $request)
	{	
		$data = $request->get('option');
		$s = MRproduct::where('id','=',$request->get('option'))
					->delete();
		
		return $s;
	}

	public function editProduct($id)
	{	
		$mr = MRproduct::find($id);

		///products
		$customerType = $mr->materialRequest->customer->customer_type_id;

		if($customerType == 3)
		{
		$cus_prd = CustomerProduct::where('customer_id','=',$customer)->pluck('product_id')->toArray();
		$product = Product::whereIN('id',$cus_prd)
							->where('is_active' ,'=' ,'Y')->get();
		}else{
			$product = Product::where('is_active' ,'=' ,'Y')->get();
		}
		/////////////////////////

		$p_unit = ProductUnit::where('product_id','=',$mr->product_id)->pluck('unit_id')->toArray();
		$unit = UnitMeasurement::whereIN('id',$p_unit)->get();
		$p_grade = ProductGrade::where('product_id','=',$mr->product_id)->pluck('grade_id')->toArray();
		$grade = GradeMaster::whereIN('id',$p_grade)->get();
		$x = $mr->material_requisition_id;
		$products = MRproduct::where('material_requisition_id','=',$x)->orderBy('id','DESC')->get();

		$data = array($mr,$x,$product,$unit,$grade,$products);
		
		return $data;

		// return view('material_request/edit_product',compact('mr','x','product','unit','grade','products'));
	}

	public function updateProduct(Request $request)
	{	
		$update = MRproduct::where('id','=',$request->get('mr_id'))
					->update([
							'material_requisition_id' => $request->get('x'),
							'product_id' => $request->get('product'),
							'unit_id' => $request->get('unit'),
							'grade_id' => $request->get('grade'),
							'qty' => $request->get('qty')]);
		$x = $request->get('x');
		
		return redirect()->action('MaterialRequestController@index',['id'=>$x]);
	}

	public function viewEdit($id)
	{	
		$material_request = MaterialRequisition::find($id);
		///products
		$customerType = $material_request->customer->customer_type_id;
		
		if($customerType == 3)
		{
		$cus_prd = CustomerProduct::where('customer_id','=',$customer)->pluck('product_id')->toArray();
		$prd = Product::whereIN('id',$cus_prd)
							->where('is_active' ,'=' ,'Y')->get();
		}else{
			$prd = Product::where('is_active' ,'=' ,'Y')->get();
		}
		/////////////////////////
		$products = MRproduct::where('material_requisition_id','=',$id)->orderBy('id','DESC')->get();
		$category = CategoryMaster::all();
		$customer = Auth::User()->customer_id;
		$last_entries = MaterialRequisition::where('customer_id','=',$customer)
							->where('id','!=',$id)
							->orderBy('id','DESC')->take(5)->get();

		$cus = Customer::find($customer);
        $n_type =  NotificationType::where('customer_type_id','=',$cus->customer_type_id)
            ->pluck('notification_id')->toArray();
        $n_status = NotificationStatus::where('customer_id','=',$customer)
        			->where('status','=','READ')->pluck('notification_id')->toArray();

        $nfn = Notification::whereIN('id',$n_type)
        			->whereNotIN('id',$n_status)
                    ->where('valid_from','<=',date('Y-m-d'))
                    ->where('valid_to','>=',date('Y-m-d'))->get();

  	
        $n_type_count = count($nfn);

		//////////////////////
		
		return view('material_request/edit',compact('material_request','products','mr','category','last_entries','n_type_count','nfn','prd'));
	}


	public function addLastEntries($id)
	{	
		$exp = explode("-", $id);
		$mr_id = $exp[0];
		$current_id = $exp[1];

		if($current_id == 0){

			$entered_by = Auth::User()->id;
			$customer = Auth::User()->customer_id;
			$count = MaterialRequisition::where('customer_id','=',$customer)->count();
			$req_no = $count+1;

			$insert = MaterialRequisition::create([
							'request_no' => 'MR'.'|'.$customer.'|'.$req_no,
							'entered_by' => $entered_by,
							'customer_id' => $customer,
							'request_date' => date('Y-m-d'),
							'status' => 'REQ'
						]);
			$exist_values = MRproduct::where('material_requisition_id','=',$mr_id)->get();

			foreach($exist_values as $exist){
				$pr_insert = MRproduct::create([
							'material_requisition_id' => $insert->id,
							'product_id' => $exist->product_id,
							'unit_id' => $exist->unit_id,
							'grade_id' => $exist->grade_id,
							'qty' => $exist->qty
						]);
			}
			
			$x = $insert->id;

			
		}
		else{
			$to_add = MRproduct::where('material_requisition_id','=',$mr_id)->get();
			$current = MRproduct::where('material_requisition_id','=',$current_id)->get();
			$x = $current_id;
			

			foreach ($to_add as $value) {
				$flag = 0;
				foreach($current as $curr){
					if($curr->product_id == $value->product_id && $curr->unit_id == $value->unit_id && $curr->grade_id == $value->grade_id){

						$update = MRproduct::where('id','=',$curr->id)
									->update(['qty' => $curr->qty + $value->qty]);

						$flag = 1;
					}
				}

				if($flag == 0){
					$create = MRproduct::create([
															'material_requisition_id' => $current_id,
															'product_id' => $value->product_id,
															'unit_id' => $value->unit_id,
															'grade_id' => $value->grade_id,
															'qty' => $value->qty
														]);
				}
			}	

		}
		return redirect()->action('MaterialRequestController@index',['id'=>$x]);

	}

	public function addNotificationStatus()
	{
		$customer = Auth::User()->customer_id;
		$cus = Customer::find($customer);
        
        $n_type =  NotificationType::where('customer_type_id','=',$cus->customer_type_id)
            ->pluck('notification_id')->toArray();
        $n_status = NotificationStatus::where('customer_id','=',$customer)
        			->where('status','=','READ')->pluck('notification_id')->toArray();
        $nfn = Notification::whereIN('id',$n_type)
        			->whereNotIN('id',$n_status)
                    ->where('valid_from','<=',date('Y-m-d'))
                    ->where('valid_to','>=',date('Y-m-d'))->get();

        foreach($nfn as $value){
        	$check = NotificationStatus::where('notification_id','=',$value->id)
        									->where('customer_id','=',$customer)->count();
        	if($check == 0){
        		NotificationStatus::create([
        									'notification_id' => $value->id,
        									'customer_id' => $customer,
        									'status' => 'READ']);
        	} 
        }

        return $customer;    
	}

	public function viewApprovedProduct($id)
	{	
		$m_r = MaterialRequisition::find($id);
		$products = MRapprovalproduct::where('material_requisition_id','=',$id)->orderBy('id','DESC')->get();
		return view('material_request/viewApproved',compact('products','m_r'));
	}			

	public function deleteMR(Request $request)
	{
		$id = $request->get('option');

		$mrobj = MaterialRequisition::find($id);
		if($mrobj->status == 'APR'){
			MRapprovalproduct::where('material_requisition_id','=', $id)->delete();
		}
		MRproduct::where('material_requisition_id','=', $id)->delete();
		$mrobj->delete();
	}


	public function received(Request $request)
	{	

		MaterialRequisition::where('id','=',$request->get('id'))
							->update([
										'recieved_date' => date('Y-m-d'),
										'status' => 'REC',
										'remarks' => $request->get('remarks')
									]);
		return redirect()->route('material_request.list');
	}

	public function ctnperPallet(Request $request)
	{
		$grade_id = $request->get('grade');
		$product_id = $request->get('product');
		$pallet = Pallet::where('product_id','=',$product_id);
		
		if(is_null($grade_id)) {
			$pallet->whereNull('grade_id');
		} else {
			$pallet->where('grade_id','=',$grade_id);
		}

		$pallet = $pallet->first();
		return ($pallet)? $pallet : 'false';
		
		return $pallet;
	}

	public function insertRequest(Request $request)
	{
		$entered_by = Auth::User()->id;
		if($request->get('customers') == 0){
			$customer = Auth::User()->customer_id;
		}else{
			$customer = $request->get('customers');
		}

		$count = MaterialRequisition::where('customer_id','=',$customer)->count();
		$req_no = $count+1;
		if($request->get('x') == 0){
			$insert = MaterialRequisition::create([
							'request_no' => 'MR'.'|'.$customer.'|'.$req_no,
							'entered_by' => $entered_by,
							'customer_id' => $customer,
							'request_date' => date('Y-m-d'),
							'status' => 'REQ'
						]);

			$pr_insert = MRproduct::create([
							'material_requisition_id' => $insert->id,
							'product_id' => $request->get('product'),
							'unit_id' => $request->get('unit'),
							'grade_id' => $request->get('grade'),
							'qty' => $request->get('qty')
						]);
			$req_id = $insert->id;
			$x = $insert->id;
			$insert = MaterialRequisition::where('id','=',$x)->first();
		}
		else{
			$x = $request->get('x');
			$edit_pro =$request->get('edit_pro');
			if($edit_pro != null)
			{
			 $pr_insert=MRproduct::where('id','=',$request->get('mr_id'))
					->update([
							'material_requisition_id' => $request->get('x'),
							'product_id' => $request->get('product'),
							'unit_id' => $request->get('unit'),
							'grade_id' => $request->get('grade'),
							'qty' => $request->get('qty')]);

				$data = array($x,$pr_insert,$edit_pro);
				return $data ;
			}
		
			$z = MRproduct::where('material_requisition_id','=',$x)
							->where('product_id','=',$request->get('product'))
							->where('unit_id','=',$request->get('unit'))
							->where('grade_id','=',$request->get('grade'))->count();
			if($z > 0){
				return 0;
			}

			$insert = MaterialRequisition::where('id','=',$request->get('x'))->first();

			$pr_insert = MRproduct::create([
							'material_requisition_id' => $request->get('x'),
							'product_id' => $request->get('product'),
							'unit_id' => $request->get('unit'),
							'grade_id' => $request->get('grade'),
							'qty' => $request->get('qty')
						]);
			$req_id = $request->get('x');
		}

		$edit_pro = null;
		$data = array($x,$pr_insert,$edit_pro,$insert);

		return $data ;
		
	}


}