<?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\NotificationType;
use App\Notification;
use App\NotificationStatus;
use App\ProductNotification;
use App\MaterialRequisitionSea;
use App\Common;
use App\MRseaproduct;
use App\MRseaproductschedule;
use App\MRseacomment;
use App\MRseaapprovalproduct;
use App\Pallet;
use App\MRseaapprovedproductschedule;
/**
* 
*/
class MaterialRequestSeaController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function backENDUPDATION()
    {
    	
    }
    
	public function viewList()
	{	
		$customer = Auth::User()->customer_id;

		//delete on refresh or back without save or draf t
		$pre_mr = MaterialRequisitionSea::where('entered_by','=',Auth::user()->id)
					->where('status','=','PRE')->pluck('id')->toArray();
		MRseaproduct::whereIn('material_requisition_sea_id',$pre_mr)->delete();
		MRseaproductschedule::whereIn('material_requisition_sea_id',$pre_mr)->delete();
		MaterialRequisitionSea::where('entered_by','=',Auth::user()->id)
					->where('status','=','PRE')->delete();

					
		$list = MaterialRequisitionSea::where('customer_id','=',$customer)
					->whereIN('status',['REQ','DRT','APR','DRQ'])
					->whereNull('contract_sea_id')
					->where('location_id','=',Auth::User()->location_id)
					->get();
					
		$x = 0;
		return view('material_request_sea/list',compact('list','x'));
	}

	public function index($id, $copy_id = NULL)
	{		
		$x = $id;
		$customer = Auth::User()->customer_id;
		$category = CategoryMaster::all();

		///products
		$customerType = Auth::User()->customer->customer_type_id;
		if($customerType == 3)
		{
		$cus_prd = CustomerProduct::where('customer_id','=',$customer)->pluck('product_id')->toArray();
		$prd = Product::whereIN('id',$cus_prd)
				      ->get();
		}else{
			$prd = Product::all();
		}

		/////Notification//////

		$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);

		//////////////////////

		if($id == 0){
			if(date('Y-m-d') > '2020-01-10') {
				$count = MaterialRequisitionSea::where('customer_id','=',$customer)
								->where('request_date','>','2020-01-10')
								->where('status','!=','PRE')->count();
				$count = ($count == 0)? 100 : (100 + $count);
				$req_no = 'MR'.'|'.$customer.'|'.($count+1);
				
			} else {
				$count = MaterialRequisitionSea::where('customer_id','=',$customer)->where('status','!=','PRE')->count();
				$req_no = 'MR'.'|'.$customer.'|'.($count+1);
			}
			
			$last_entries = MaterialRequisitionSea::where('customer_id','=',$customer)
							->orderBy('id','DESC')->take(5)->get();
		}
		else{
			$m_r = MaterialRequisitionSea::find($id);
			$req_no = $m_r->request_no;
			$products = MRseaproduct::where('material_requisition_sea_id','=',$id)->orderBy('id','DESC')->get();
			$last_entries = MaterialRequisitionSea::where('customer_id','=',$customer)
							->where('id','!=',$id)
							->orderBy('id','DESC')->take(5)->get();

		}

		$month = date("01-M-Y");
		for($i = 1; $i <=12; $i++) {
			$months[] = date("01-M-Y", strtotime($month."+".$i." month"));
		}
		$mr_sea = MaterialRequisitionSea::find($id);
		$mr_sea_cmts = MRseacomment::where('material_requisition_sea_id','=',$id)->get();

		//save and copy option only
		if($copy_id) {
			$copy_prd = MRseaproduct::find($copy_id);
			$p_unit = ProductUnit::where('product_id','=',$copy_prd->product_id)->pluck('unit_id')->toArray();
			$unit = UnitMeasurement::whereIN('id',$p_unit)->get();
			$p_grade = ProductGrade::where('product_id','=',$copy_prd->product_id)->pluck('grade_id')->toArray();
			$grade = GradeMaster::whereIN('id',$p_grade)->get();
			

		} else {
			$copy_prd = null;
			$p_unit = ProductUnit::where('product_id','=',0)->pluck('unit_id')->toArray();
			$unit = UnitMeasurement::whereIN('id',$p_unit)->get();
			$p_grade = ProductGrade::where('product_id','=',0)->pluck('grade_id')->toArray();
			$grade = GradeMaster::whereIN('id',$p_grade)->get();
		}
		
		return view('material_request_sea/index',compact('req_no','x','products','last_entries','n_type_count','nfn','prd','category','schedules','months','mr_sea_cmts','mr_sea','unit','grade','copy_id','copy_prd'));
	}

	public function createProductSchedule($x,$pr_insert)
	{
		$schedule = $pr_insert->schedule_id;
		$qty = $pr_insert->qty;
		$sqty = (int) ($qty/$schedule);
		$rqty = $qty % $schedule;
		$end_date = date("Y-m-t", strtotime($pr_insert->requested_month));
		$start_date = date("Y-m-01", strtotime($pr_insert->requested_month));
		$rm_qty = $qty;
		$intrvl = (int) (30/$schedule);
		$scd_date = date("Y-m-01", strtotime($start_date));
		for ($i=1; $i <= $schedule && $scd_date < $end_date; $i++) { 
			MRseaproductschedule::create([
			 		'material_requisition_sea_id' => $x,
			 		'mr_sea_product_id' => $pr_insert->id,
			 		'product_id' => $pr_insert->product_id,
			 		'unit_id' => $pr_insert->unit_id,
			 		'grade_id' => $pr_insert->grade_id,
			 		'qty' => $sqty,
			 		'scheduled_date' => date('Y-m-d', strtotime($scd_date))
			]);
			$scd_date = date('Y-m-d', strtotime($scd_date."+".$intrvl." days"));
		 	$rm_qty = $rm_qty - $sqty;
		}
		if($rm_qty > 0)
		{	
			MRseaproductschedule::where('material_requisition_sea_id','=',$x)
				->where('product_id','=',$pr_insert->product_id)
				->where('unit_id','=',$pr_insert->unit_id)
				->where('grade_id','=',$pr_insert->grade_id)
				->where('mr_sea_product_id','=',$pr_insert->id)
				->where('scheduled_date','=',$start_date)
				->increment('qty',$rm_qty);
		}
		

	}


	public function insertRequest(Request $request)
	{	

		$no_prmsn = MRseaapprovalproduct::where('material_requisition_sea_id','=',$request->get('x'))
										->count();
		if($no_prmsn) {
			return Redirect::back()->with(['resubmit' => true]);
		}
		$schedule = $request->get('schedule');
		$entered_by = Auth::User()->id;
		$customer = Auth::User()->customer_id;
		if(date('Y-m-d') > '2020-01-10') {
			$count = MaterialRequisitionSea::where('customer_id','=',$customer)
							->where('status','!=','PRE')
							->where('request_date','>','2020-01-10')
							->count();

			$count = ($count == 0)? 100 : (100 + $count);
			$req_no = ($count+1);
		} else {
			$count = MaterialRequisitionSea::where('customer_id','=',$customer)->where('status','!=','PRE')->count();
			$req_no = $count+1;	
		}
		
		
		$copy_id = null;
		if($request->get('x') == 0){
			// check already product is requested in this month
			$dup_req_prod_mnth = MRseaproduct::where('product_id','=',$request->get('product'))
									->where('unit_id','=',$request->get('unit'))
									->where('grade_id','=',$request->get('grade'))
									->whereNull('deleted_at')
									->where('requested_month','=',date('Y-m-01', strtotime($request->get('req_mnth'))))
									->count();

			if($dup_req_prod_mnth) {
				return Redirect::back()->with(['exist' => true]);
			}
			
			$insert = MaterialRequisitionSea::create([
							'request_no' => 'MR'.'|'.$customer.'|'.$req_no,
							'entered_by' => $entered_by,
							'customer_id' => $customer,
							'location_id' => Auth::User()->location_id,
							'request_date' => date('Y-m-d'),
							'status' => 'PRE',
							'remarks' => strtoupper($request->get('remarks'))
						]);

			$pr_insert = MRseaproduct::create([
							'material_requisition_sea_id' => $insert->id,
							'product_id' => $request->get('product'),
							'unit_id' => $request->get('unit'),
							'grade_id' => $request->get('grade'),
							'qty' => $request->get('qty'),
							'requested_month' => date('Y-m-01', strtotime($request->get('req_mnth'))),
							'schedule_id' => $request->get('schedule')
						]);
			$req_id = $insert->id;
			$x = $insert->id;
			
			$this->createProductSchedule($x,$pr_insert);

		}
		else{
			$x = $request->get('x');
			
			/*
			$z = MRseaproduct::where('material_requisition_sea_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 Redirect::back()->with(['exist' => true]);
				return redirect()->action('MaterialRequestSeaController@index',['id'=>$x]);
			}*/

			// check already product is requested in this month
			$dup_req_prod_mnth = MRseaproduct::where('product_id','=',$request->get('product'))
									->where('unit_id','=',$request->get('unit'))
									->where('grade_id','=',$request->get('grade'))
									->whereNull('deleted_at')
									->where('requested_month','=',date('Y-m-01', strtotime($request->get('req_mnth'))))
									->count();

			if($dup_req_prod_mnth) {
				return Redirect::back()->with(['exist' => true]);
			}
			
			$pr_insert = MRseaproduct::create([
							'material_requisition_sea_id' => $request->get('x'),
							'product_id' => $request->get('product'),
							'unit_id' => $request->get('unit'),
							'grade_id' => $request->get('grade'),
							'qty' => $request->get('qty'),
							'requested_month' =>  date('Y-m-01', strtotime($request->get('req_mnth'))),
							'schedule_id' => $request->get('schedule')
						]);
			$req_id = $request->get('x');

			$this->createProductSchedule($x,$pr_insert);
		}

		if(!is_null($request->get('ctn_per_pallet')) && !is_null($request->get('pallet_qty'))) {
			Pallet::updateOrCreate([
				'product_id' => $request->get('product'),
				'grade_id' => $request->get('grade'),
				],[
				'ctn_per_pallet' => $request->get('ctn_per_pallet'),
				'pallet_total' => $request->get('pallet_qty')
			]);
		}
				
		$category = CategoryMaster::all();
		$products = MRseaproduct::where('material_requisition_sea_id','=',$req_id)->get();

		if($request->get('savebtn') == "savecopy") {
			$copy_id  = $pr_insert->id;
			return redirect()->action('MaterialRequestSeaController@index',['id'=>$x, 'copy_id' => $copy_id]);	
		}
		
		return redirect()->action('MaterialRequestSeaController@index',['id'=>$x,'copy_id' => 0]);	
	}

	public function viewEdit($id)
	{	
		$material_request = MaterialRequisitionSea::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)
					  ->get();
		}else{
			$prd = Product::all();
		}
		/////////////////////////
		$products = MRseaproduct::where('material_requisition_sea_id','=',$id)->orderBy('id','DESC')->get();
		$category = CategoryMaster::all();
		$customer = Auth::User()->customer_id;
		$last_entries = MaterialRequisitionSea::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);

        $schedules = Common::where('masterkeyword','=','SEA SCHEDULES')->get();
		$month = date("01-M-Y");
		for($i = 1; $i <=12; $i++) {
			$months[] = date("01-M-Y", strtotime($month."+".$i." month"));
		}

		$mr_sea_cmts = MRseacomment::where('material_requisition_sea_id','=',$id)->get();
		//////////////////////
		
		return view('material_request_sea/edit',compact('material_request','products','mr','category','last_entries','n_type_count','nfn','prd','months','schedules','mr_sea_cmts'));
	}

	public function editProduct($id)
	{	
		$mr = MRseaproduct::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)
						  ->get();
		}else{
			$product = Product::all();
		}
		/////////////////////////

		$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_sea_id;
		$products = MRseaproduct::where('material_requisition_sea_id','=',$x)->orderBy('id','DESC')->get();

		$schedules = Common::where('masterkeyword','=','SEA SCHEDULES')->get();
		$month = date("01-M-Y");
		for($i = 1; $i <=12; $i++) {
			$months[] = date("01-M-Y", strtotime($month."+".$i." month"));
		}

		$mr_sea_cmts = MRseacomment::where('material_requisition_sea_id','=',$x)->get();
		return view('material_request_sea/edit_product',compact('mr','x','product','unit','grade','products','schedules','months','mr_sea_cmts'));
	}

	public function updateProduct(Request $request)
	{	
		$no_prmsn = MRseaapprovalproduct::where('material_requisition_sea_id','=',$request->get('x'))
										->count();
		if($no_prmsn) {
			return Redirect::back()->with(['resubmit' => true]);
		}

		$schedule = $request->get('schedule');
		MRseaproductschedule::where('mr_sea_product_id','=',$request->get('mr_id'))
						   ->delete();
		$update = 	MRseaproduct::where('id','=',$request->get('mr_id'))
						->update([
							'material_requisition_sea_id' => $request->get('x'),
							'product_id' => $request->get('product'),
							'unit_id' => $request->get('unit'),
							'grade_id' => $request->get('grade'),
							'qty' => $request->get('qty'),
							'requested_month' => date('Y-m-01', strtotime($request->get('req_mnth'))),
							'schedule_id' => $request->get('schedule')
					]);

		$x = $request->get('x');

		$pr_insert = MRseaproduct::find($request->get('mr_id'));
		$this->createProductSchedule($x,$pr_insert);
		
		if(!is_null($request->get('ctn_per_pallet')) && !is_null($request->get('pallet_qty'))) {
			Pallet::updateOrCreate([
				'product_id' => $request->get('product'),
				'grade_id' => $request->get('grade'),
				'ctn_per_pallet' => $request->get('ctn_per_pallet'),
				'pallet_total' => $request->get('pallet_qty')
			]);
		}

		if($request->get('savebtn') == "savecopy") {
			$copy_id  = $pr_insert->id;
			return redirect()->action('MaterialRequestSeaController@index',['id'=>$x, 'copy_id' => $copy_id]);	
		}
		
		return redirect()->action('MaterialRequestSeaController@index',['id'=>$x]);
	}


	public function storeSeaMrComment(Request $request)
	{
		$mr_sea_cmt = MRseacomment::create([
			'material_requisition_sea_id' => $request->get('mrid'),
			'comment' => $request->get('comment'),
			'enter_by' => Auth::user()->id
		]);
		$data = ['comment' =>strtoupper($mr_sea_cmt->comment),'enter_by' => strtoupper(Auth::user()->name), 'created_at' => date('d-m-Y H:i', strtotime($mr_sea_cmt->created_at)) ];
		
		return $data;
	}

	public function requestSubmit(Request $request)
	{
		$no_prmsn = MRseaapprovalproduct::where('material_requisition_sea_id','=',$request->get('x'))
										->count();
		if($no_prmsn) {
			return Redirect::back()->with(['resubmit' => true]);
		}

		if (isset($_POST['submit'])) {

			MaterialRequisitionSea::where('id','=',$request->get('x'))
					->update([
						'status' => 'REQ',
						'remarks' => strtoupper($request->get('remarks'))
					]);

			$mr_sea_prd = MRseaproduct::where('material_requisition_sea_id','=',$request->get('x'))->selectRaw('material_requisition_sea_id,product_id,qty,unit_id,grade_id,requested_month,schedule_id,id as mr_sea_product_id')->get()->toArray();

			MRseaapprovalproduct::insert($mr_sea_prd);

			$mr_sea_apr_prd = MRseaapprovalproduct::where('material_requisition_sea_id','=',$request->get('x'))->get();
			foreach ($mr_sea_apr_prd as $sea_apr_prd) {
				$mr_sea_schdls = MRseaproductschedule::where('material_requisition_sea_id','=',$request->get('x'))
									->where('mr_sea_product_id','=',$sea_apr_prd->mr_sea_product_id)
									->selectRaw('material_requisition_sea_id,'.$sea_apr_prd->id.' as mr_sea_approval_product_id,product_id,qty,unit_id,grade_id,scheduled_date')
									->get()->toArray();
				
				MRseaapprovedproductschedule::insert($mr_sea_schdls);
			}
			



			MRseaproduct::where('material_requisition_sea_id','=',$request->get('x'))->whereNull('flag_in')->update(['flag_in' => 1]);	
		}

		if (isset($_POST['draft'])) {
			MaterialRequisitionSea::where('id','=',$request->get('x'))
					->update([
						'status' => 'DRT',
						'remarks' => strtoupper($request->get('remarks'))
					]);
		}

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

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


	public function addLastEntries($id, Request $request)
	{	
		$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;
			if(date('Y-m-d') > '2020-01-10') {
				$count = MaterialRequisitionSea::where('customer_id','=',$customer)
								->where('request_date','>','2020-01-10')
								->count();
				$req_no = ($count == 0)? 101 : (100+$count+1);
			} else {
				$count = MaterialRequisitionSea::where('customer_id','=',$customer)->count();
				$req_no = $count+1;
			}
			

			$insert = MaterialRequisitionSea::create([
							'request_no' => 'MR'.'|'.$customer.'|'.$req_no,
							'entered_by' => $entered_by,
							'customer_id' => $customer,
							'location_id' => Auth::User()->location_id,
							'request_date' => date('Y-m-d'),
							'status' => 'REQ',
							'remarks' => strtoupper($request->get('remarks'))
						]);
			$exist_values = MRseaproduct::where('material_requisition_sea_id','=',$mr_id)->get();

			foreach($exist_values as $exist){
				$pr_insert = MRseaproduct::create([
							'material_requisition_sea_id' => $insert->id,
							'product_id' => $exist->product_id,
							'unit_id' => $exist->unit_id,
							'grade_id' => $exist->grade_id,
							'qty' => $exist->qty,
							'requested_month' => date('Y-m-01'),
							'schedule_id' => $exist->schedule_id,
						]);
				$ext_mr_sea_schds = MRseaproductschedule::where('material_requisition_sea_id','=',$exist->material_requisition_sea_id)
													   ->where('mr_sea_product_id','=',$exist->id)
													   ->get();
				foreach($ext_mr_sea_schds as $schd) {
						$dates = $schd->scheduled_date;
						$day = date('d', strtotime($dates));
						$newd = date('Y-m-'.$day);
					 MRseaproductschedule::create([
					 		'material_requisition_sea_id' => $insert->id,
					 		'mr_sea_product_id' => $pr_insert->id,
					 		'product_id' => $schd->product_id,
					 		'qty' => $schd->qty,
					 		'unit_id' => $schd->unit_id,
					 		'grade_id' => $schd->grade_id,
					 		'standard_id' => $schd->standard_id,
					 		'unit_price' => $schd->unit_price,
					 		'scheduled_date' => $newd,
					 	]);
				}
				
			}
			
			$x = $insert->id;

			
		}
		else{
			$to_add = MRseaproduct::where('material_requisition_sea_id','=',$mr_id)->get();
			$current = MRseaproduct::where('material_requisition_sea_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 = MRseaproduct::where('id','=',$curr->id)
									->update(['qty' => $curr->qty + $value->qty]);

						$flag = 1;
					}
				}

				if($flag == 0){
					$create = MRseaproduct::create([
															'material_requisition_sea_id' => $current_id,
															'product_id' => $value->product_id,
															'unit_id' => $value->unit_id,
															'grade_id' => $value->grade_id,
															'qty' => $value->qty,
															'requested_month' => date('Y-m-01'),
														]);
					$ext_mr_sea_schds = MRseaproductschedule::where('material_requisition_sea_id','=',$current_id)
														   ->where('mr_sea_product_id','=',$value->id)
														   ->get();
					foreach($ext_mr_sea_schds as $schd) {
							$dates = $schd->scheduled_date;
							$day = date('d', strtotime($dates));
							$newd = date('Y-m-'.$day);
						 MRseaproductschedule::create([
						 		'material_requisition_sea_id' => $current_id,
						 		'mr_sea_product_id' => $value->id,
						 		'product_id' => $schd->product_id,
						 		'qty' => $schd->qty,
						 		'unit_id' => $schd->unit_id,
						 		'grade_id' => $schd->grade_id,
						 		'standard_id' => $schd->standard_id,
						 		'unit_price' => $schd->unit_price,
						 		'scheduled_date' => $newd,
						 	]);
					}
				}
			}	

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

	}


	public function viewApprovedProduct($id)
	{	
		$m_r = MaterialRequisitionSea::find($id);
		$products = MRseaapprovalproduct::where('material_requisition_sea_id','=',$id)->orderBy('id','DESC')->get();
		return view('material_request_sea/viewApproved',compact('products','m_r'));
	}
}