<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Block;
use App\Schedule;
use App\Boat;
use App\Customer;
use Auth;

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

    public function index(Request $request)
    {
			if(Auth::user()->role->role_permission('view_events')){
				$boat_id = $request->boat->id;
				$blocks = Block::with('schedule')->where('boat_id', '=', $boat_id)->orderBy('day', 'desc')->paginate(30);
				$boats = Boat::lists('name', 'id')->toArray();
			

				$schedule = ["" => ""] + Schedule::groupBy('name')->lists('name', 'id')->toArray();
				return view('blocks.index', compact('blocks','boat_id','boats','schedule'));
			}else{
				abort(403);
			}
    }

    public function create(Boat $boat)
    {

			if(Auth::user()->role->role_permission('create_events')){
				$boats = Boat::lists('name', 'id')->toArray();

				$array_of_boats = Boat::all();

				$motor = null;
		  	    $vela = null;

                $customer_id = Auth::user()->customer_id;
			  	$tipo= Customer::find($customer_id)->boats;
				  foreach($tipo as $type){
						if($type->boattype_id == 2){
							$vela = 2;
						}
						elseif($type->boattype_id == 1){
							$motor = 1;
						}
				  }

				$schedule = ["" => ""] + Schedule::where('boattype_id',$vela)->orWhere('boattype_id',$motor)->lists('name', 'id')->toArray();

				$array_of_schedules = Schedule::all();

				return view('blocks.create', compact('boats','schedule', 'array_of_boats', 'array_of_schedules', 'boat'));
			}else{
				abort(403);
			}
    }

    public function store(Request $request)
		{
			if(Auth::user()->role->role_permission('create_events')){
				if($request->has('boat_id') && $request->has('schedule_id') && $request->has('day')){
					$block = Block::create($request->all());

					return redirect('blocks/'.$request->boat_id.'/listado')->withSuccess('Block has been saved.');
				}else{
					return redirect()->back()->withErrors('Todos los campos son obligatorios.');
				}
			}else{
				abort(403);
			}
    }

    public function destroy(Block $block)
    {
			if(Auth::user()->role->role_permission('delete_events')){
				$boat_id = $block->boat_id;
				$block->delete();
				return redirect('blocks/'.$boat_id.'/listado')->withSuccess('Block has been deleted.');
			}else{
				abort(403);
			}
    }
}
