<?php

namespace App\Http\Controllers;

use App\Block;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Boat;
use App\Port;
use App\Http\Requests\BoatRequest;
use App\User;
use App\Customer;
use App\BoatType;
use Auth;

class BoatController extends Controller
{
	public function __construct()
	{
		$this->middleware('auth');
	}

	public function index()
	{


		if(Auth::user()->role->role_permission('view_boat')){
			if(Auth::user()->role->role_permission('view_boat')->level == 'all'){

				$boats = Boat::paginate(30);
				$boatTypes = BoatType::lists('name', 'id')->toArray();
				$port = Port::lists('name', 'id')->toArray();

			}elseif(Auth::user()->role->role_permission('view_boat')->level == 'team'){
				$customers = User::pluck('id');
				$boats = Boat::whereIn('customer_id', $customers)->paginate(30);
			}else{
				$boats = Boat::where('customer_id', Auth::user()->customer_id)->paginate(30);

			}

			return view('boats.index', compact('boats','boatTypes','port'));
		}else{
			abort(403);
		}
	}

	public function deletedIndex()
	{
		if(Auth::user()->role->role_permission('view_boat')){

			if(Auth::user()->role->role_permission('view_boat')->level == 'all'){

				$boats = Boat::onlyTrashed()->paginate(30);
				$boatTypes = BoatType::lists('name', 'id')->toArray();
				$port = Port::lists('name', 'id')->toArray();

			}elseif(Auth::user()->role->role_permission('view_boat')->level == 'team'){
				$customers = User::pluck('id');
				$boats = Boat::onlyTrashed()->whereIn('customer_id', $customers)->paginate(30);
			}else{
				$boats = Boat::onlyTrashed()->where('customer_id', Auth::user()->customer_id)->paginate(30);

			}

			return view('boats.deleted', compact('boats','boatTypes','port'));
		}else{
			abort(403);
		}

	}

	public function restore(Boat $boat) {

		if(Auth::user()->role->role_permission('view_boat')){
			if(Auth::user()->role->role_permission('edit_boat')){
				Boat::withTrashed()->find($boat->id)->restore();
			}
			return redirect('boats')->withSuccess('Successfully restored boat');
		}else{
			abort(403);
		}

	}

	public function search(Request $request)
	{
		if(Auth::user()->role->role_permission('view_boat')){
			if(Auth::user()->role->role_permission('view_boat')->level == 'all'){
				$customers = Customer::whereRaw("(fiscal_reason like ?)", ['%'.$request->get('term').'%'])->get();
				$boats = Boat::whereIn('customer_id', $customers->pluck('id'))->paginate(30);
			}elseif(Auth::user()->role->role_permission('view_boat')->level == 'team'){
				$users = Customer::whereRaw("(fiscal_reason like ?)", ['%'.$request->get('term').'%'])->pluck('id');
				$boats = Boat::whereIn('customer_id', $customers)->paginate(30);
			}else{
				$customers = Customer::whereRaw("(fiscal_reason like ?)", ['%'.$request->get('term').'%'])->where('customer_id', Auth::user()->customer_id)->pluck('id');
				$boats = Boat::whereIn('customer_id', $customers)->paginate(30);
			}
			return view('boats.index', compact('boats'));
		}else{
			abort(403);
		}
	}

	public function create(User $user)
	{
		if(Auth::user()->role->role_permission('create_boat')){
			$boatTypes = BoatType::lists('name', 'id')->toArray();
			$port = Port::lists('name', 'id')->toArray();
			$users = Customer::select(DB::raw('CONCAT(fiscal_reason, " ", cif) AS text'), 'id')
				->orderBy('fiscal_reason')->get();
			$users = json_encode($users);
			return view('boats.create', compact('users','user', 'boatTypes','port'));
		}else{
			abort(403);
		}
	}

	public function store(BoatRequest $request, Customer $customer)
	{

		if(Auth::user()->role->role_permission('create_boat')){

			if(isset($request->users)) {
				$user = collect($request->users);
				if($user->count() <= 7){
					$boat = Boat::create($request->all());
					$boat->customers()->sync($request->users);
				}
				else{
					return redirect(isset($user->id) ? 'users/'.$user->id : 'boats')->withErrors('Usuarios ('. $user->count() .') .No puede asociar más de 7 usuarios a una embarcación.');

				}
			}

			return redirect(isset($user->id) ? 'users/'.$user->id : 'boats')->withSuccess('Boat has been saved.');
		}else{
			abort(403);
		}
	}

	public function show(Boat $boat)
	{
		if(Auth::user()->role->role_permission('view_boat')){
			if(Auth::user()->role->role_permission('view_boat')->level == 'team'){
				$users = Customer::pluck('id');
				$boat = Boat::where('id', $boat->id)->whereIn('customer_id', $users)->first();
			}elseif(Auth::user()->role->role_permission('view_boat')->level == 'self'){
				$boat = Boat::where('id', $boat->id)->where('customer_id', Auth::user()->id)->first();
			}
			return $boat ? $boat : abort(403);
		}else{
			abort(403);
		}
	}

	public function edit(Boat $boat)
	{

		if(Auth::user()->role->role_permission('edit_boat')){
			if(Auth::user()->role->role_permission('edit_boat')->level == 'all'){
				$users = Customer::pluck('id');
				$boat = Boat::where('id', $boat->id)->first();
				$boatTypes = BoatType::lists('name', 'id')->toArray();
				$port = Port::lists('name', 'id')->toArray();
				$selectedUsers = [];
				foreach($boat->customers as $boatuser) {
					$selectedUsers[] = $boatuser->id;
				}
				$selectedUsers = json_encode($selectedUsers);

				$users =  Customer::select(DB::raw('CONCAT(fiscal_reason, " ", cif) AS text'), 'id')
					->orderBy('fiscal_reason')->get();
				$users = json_encode($users);
			}elseif(Auth::user()->role->role_permission('edit_boat')->level == 'team'){

				$boat = Boat::where('id', $boat->id)->where('user_id', Auth::user()->id)->first();
			}
			return view('boats.edit', compact('boat', 'users','selectedUsers','boatTypes','port'));
		}else{
			abort(403);
		}
	}

	public function update(BoatRequest $request, Boat $boat)
	{
		if(Auth::user()->role->role_permission('edit_boat')){


			if(isset($request->users)) {

				if($boat->customers()->count() <= 6){
					$boat->update($request->all());
					$boat->customers()->sync($request->users);
				}
				else{

					return redirect('boats')->withErrors('Usuarios ('. $boat->customers()->count() .') .No puede asociar más de 7 usuarios a una embarcación.');
				}

			}
			else {
				$boat->customers()->detach();
			}
			return redirect('boats')->withSuccess('Boat has been updated.');
		}else{
			abort(403);
		}
	}

	public function destroy(Boat $boat)
	{
		if(Auth::user()->role->role_permission('delete_boat')){
			if ($boat->customers()->count() === 0) {
				$boat->delete();
				Block::where('boat_id', $boat->id)->delete();
				DB::table('boat_customer')->where('boat_id', $boat->id)->delete();
				DB::table('credit_register')->where('boat_id', $boat->id)->delete();
				DB::table('reservations')->where('boat_id', $boat->id)->delete();
				$message = 'Boat has been deleted.';
				return redirect('boats')->withSuccess($message);
			} else {
				$customer = $boat->customers()->first();
				$message = 'This boat is assigned to '. $customer->fiscal_reason.', please remove any assignations before deleting the client';
				return redirect('boats')->withErrors($message);
			}


		}else{
			abort(403);
		}
	}
}
