<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Reservations;
use App\Status;
use App\Customer;
use App\Festive;
use App\Block;
use App\User;
use App\Boat;
use App\Http\Requests\ReservationsRequest;
use Auth;
use Carbon\Carbon;

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

    public function index(Request $request)
    {


        $from = Carbon::now();
        $to = $this->data_last_month_day();
        $dates = $this->generateDateRange($from,$to);

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

                $users = ["" => ""] + User::select(DB::raw('CONCAT(first_name, " ",last_name) AS fullname, id'))
                        ->lists('fullname', 'id')->toArray();

                // $reservation = Reservations::orderBy('date_start', 'id', 'desc')->with('boat')->get();


                $boat = null;
                $boatId =  $request->boat_id;
                if ($boatId > 0)
                {

                    // $reservation = Reservations::orderBy('date_start', 'id', 'desc')->with('boat')->get();
                    $reservation = Reservations::orderBy('date_start', 'id','desc')
                        ->where('boat_id',$request->boat_id)
                        ->with('boat')->get();

                    $boat = Boat::where('id',$boatId)->first();
                }else{

                  if(isset($_COOKIE['current_boat_id']) && !empty($_COOKIE['current_boat_id'])){
                    $boat_id = $_COOKIE['current_boat_id'];
                      $boat = Boat::find($boat_id);
                  }else{
                    $boat = Boat::first();

                  }

                    $reservation = Reservations::orderBy('date_start', 'id','desc')
                        ->where('boat_id',$boat->id)
                        ->with('boat')->get();

                }

                if (count($request->all())){
                    if($request->user_id == ''){
                        $reservation = Reservations::orderBy('date_start', 'id','desc')
                        ->where('boat_id',$request->boat_id)
                        ->with('boat')->get();
                        // ->where('user_id',Auth::user()->id)
                    }else{
                        $reservation = Reservations::orderBy('date_start', 'id','desc')
                        ->where('user_id',$request->user_id)
                        ->where('boat_id',$request->boat_id)
                        ->with('boat')->get();
                    }
                }


                $status = Status::get();

                $eventos = [];
                foreach ($reservation as $reserva) {
        		        if ($reserva->status_id != 3){

                            if ($reserva->status_id == 1) {
                                // prereserva
                                $color = '#5cb85c';
                            } elseif ($reserva->status_id == 2) {
                                // reserva
                                $color = '#f39c12';
                            } elseif ($reserva->status_id == 4) {
                                // espera
                                $color = '#00c0ef';
                            } else {
                                // cancelado
                                $color = '#dd4b39';
                            }

                            $urlEvento = (Auth::user()->role->role_permission('edit_reservation')) ? 'reservations/' . $reserva->id . '/edit' : '';
                            $turno = ($reserva->schedule_id == 1 || $reserva->schedule_id == 3) ? 'DIA' : 'NOCHE';

                            $eventos[] = \Calendar::event(
                                $turno .'-' . $reserva->first_name .' '. $reserva->last_name .' - '.  $reserva->boat->name,
                                true,
                                Carbon::createFromFormat('d/m/Y', $reserva->date_start)->format('Y-m-d'), // HERE TO FORMAT DATE AS NEEDED BY CALENDAR
                                // $reserva->date_start,
                                $reserva->date_end,
                                0,
                                [
                                    'color' => $color,
                                    'url' => $urlEvento,
                                    'className' => 'reserva'
                                ]
                            );
	                }
                }

                $festive = [];
                $festivos = Festive::orderBy('date', 'asc')->get();
                foreach ($festivos as $festivo) {
                    $color = '#EF5773';
                    $festive[] = \Calendar::event(
                        $festivo->name,
                        true,
                        $festivo->date,
                        $festivo->date,
                        0,
                        ['color' => $color]
                    );
                }

                $blocks = [];

                $bloc = Block::orderBy('day', 'asc')->get();


                foreach ($bloc as $blck) {

                    $color = '#abafb7';

                    if ($blck->reason == 'L')
                        $motivo = 'Limpieza ';
                    elseif ($blck->reason == 'M')
                        $motivo = 'Mantenimiento ';
                    elseif ($blck->reason == 'F')
                        $motivo = 'Formación ';

                    $blocks[] = \Calendar::event(
                        $motivo . $blck->boat->name . ' ' . $blck->schedule->name,
                        true,
                        $blck->day,
                        $blck->day,
                        0,
                        ['color' => $color, 'className' => 'bloqueo']
                    );
                }

                $calendar = \Calendar::addEvents($eventos)->setCallbacks([ 'eventClick' => 'function(event) { alert(event.title); return false; }']);
                $calendar = \Calendar::addEvents($festive);
                $calendar = \Calendar::addEvents($blocks);

                return view('calendar.activities', compact('calendar', 'status', 'festive', 'users','boat'));

            }elseif(Auth::user()->role->role_permission('view_reservation')->level == 'self'){
                $users =  User::select(DB::raw('CONCAT(first_name, " ",last_name) AS fullname, id'))->where('id', Auth::user()->id)
                        ->lists('fullname', 'id')->toArray();

                $boats = DB::table('boat_customer')->where('customer_id', Auth::user()->customer_id)->pluck('boat_id');
		            $barcos = Customer::find(Auth::user()->customer_id)->boats()->pluck('name','id')->toArray();


                if ($request->boat_id){
                    $boatpost = Boat::find($request->boat_id);
                    $boat = Boat::where('id',$request->boat_id)->first();
                }else{

                  if(isset($_COOKIE['current_boat_id']) || !empty($_COOKIE['current_boat_id'])){
                    $boat_id = $_COOKIE['current_boat_id'];
                    $boatpost = Boat::find($boat_id);
                    $boat = Boat::where('id',$boat_id)->first();
                  }else{
                    $boatpost = Boat::find($boats[0]);
                    $boat = Boat::where('id',$boats[0])->first();
                  }
                }
                // dd($boat);

                $reservation = Reservations::where('boat_id', $boatpost->id)->where('user_id', Auth::user()->id)->whereDate('date_start','>=',Carbon::today())->orderBy('date_start', 'id', 'desc')->with('boat')->get();

                if (count($request->all())){

                    $usuarioId = ($request->user_id == '') ? Auth::user()->id  : $request->user_id;  // Auth::user()->customer_id

                    $reservation = Reservations::orderBy('date_start', 'id','desc')
                        ->whereDate('date_start','>=',Carbon::today())
                        ->where('user_id', $usuarioId)
                        ->where('boat_id',$request->boat_id)
                        ->with('boat')->get();
                    $boatpost = Boat::find($request->boat_id);
                }

                $tipo = ($boatpost != null) ? $boatpost->boattype_id : '';

                $status = Status::get();

                $eventos = [];
                foreach ($reservation as $reserva) {
                    // No mostramos las reservas canceladas
                    if ($reserva->status_id != 3){
                        if ($reserva->status_id == 1) {
                            // confirmado
                            $color = '#5cb85c';
                        } elseif ($reserva->status_id == 2) {
                            // prereserva
                            $color = '#f39c12';
                        } elseif ($reserva->status_id == 4) {
                            // espera
                            $color = '#00c0ef';
                        } else {
                            // cancelado
                            $color = '#dd4b39';
                        }

                        $urlEvento = (Auth::user()->role->role_permission('edit_reservation')) ? 'reservations/' . $reserva->id . '/edit' : '';
                        $turno = ($reserva->schedule_id == 1 || $reserva->schedule_id == 3) ? 'DIA' : 'NOCHE';

                        $eventos[] = \Calendar::event(
                            $turno .' - '.$reserva->boat->name,
                            true,
                            // $reserva->date_start,
                            Carbon::createFromFormat('d/m/Y', $reserva->date_start)->format('Y-m-d'),
                            $reserva->date_end,
                            0,
                            [
                              'color' => $color,
                              'url' => $urlEvento,
                            ]
                        );
                    }
                }

                $festive = [];
                $festivos = Festive::whereDate('date','>=',Carbon::today())->orderBy('date', 'asc')->get();
                foreach ($festivos as $festivo) {
                    $color = '#EF5773';
                    $festive[] = \Calendar::event(
                        'aafestivo',
                        true,
                        $festivo->date,
                        $festivo->date,
                        0,
                        ['color' => $color, 'textColor' => $color]
                    );
                }


                $blocks = [];
                $bloc = Block::where('boat_id', '=', $boatpost->id)->whereDate('day','>=',Carbon::today())->orderBy('day', 'asc')->get();
                if (isset($request->boat_id))
                    $bloc = Block::where('boat_id', '=', $request->boat_id)->whereDate('day','>=',Carbon::today())->orderBy('day', 'asc')->get();

                foreach ($bloc as $blck) {
                    $color = '#abafb7';

                    if ($blck->reason == 'L')
                        $motivo = 'Limpieza ';
                    elseif ($blck->reason == 'M')
                        $motivo = 'Mantenimiento ';
                    elseif ($blck->reason == 'F')
                        $motivo = 'Formación ';

                    $blocks[] = \Calendar::event(
                        $motivo . $blck->boat->name . ' HERE  ' . $blck->schedule->name,
                        true,
                        $blck->day,
                        $blck->day,
                        0,
                        ['color' => $color]
                    );
                }

                // SELECT * FROM `reservations` WHERE user_id = 3 and status_id in (1,2,4) and date_start > NOW() and boat_id = 10

                $sDia = ($tipo == 2) ? 1 : 3;
                $bloqueosDia = DB::table('reservations')
                    ->select(DB::raw('DATE_FORMAT( date_start, "%d-%m-%Y") as fecha'))
                    ->where('boat_id', $boatpost->id)
                    ->where('schedule_id', $sDia)
                    ->where('status_id', 2)
                    ->whereDate('date_start','>=',Carbon::today())
                ->pluck('fecha');
                $bloqueosDiaConfirmadas = DB::table('reservations')
                    ->select(DB::raw('DATE_FORMAT( date_start, "%d-%m-%Y") as fecha'))
                    ->where('boat_id', $boatpost->id)
                    ->where('schedule_id', $sDia)
                    ->where('status_id', 1)
                    ->whereDate('date_start','>=',Carbon::today())
                    ->pluck('fecha');
                //dd($bloqueosDia);

                $sNoche = ( $tipo == 2) ? 2 : 4;
                $bloqueosNoche = Reservations::selectRaw('DATE_FORMAT( date_start, "%d-%m-%Y") as fecha')
                    ->where('boat_id', $boatpost->id)
                    ->where('schedule_id', $sNoche)
                    ->where('status_id', 2)
                    ->whereDate('date_start','>=',Carbon::today())
                    ->pluck('fecha')->toArray();
                $bloqueosNocheConfirmadas = Reservations::selectRaw('DATE_FORMAT( date_start, "%d-%m-%Y") as fecha')
                    ->where('boat_id', $boatpost->id)
                    ->where('schedule_id', $sNoche)
                    ->where('status_id', 1)
                    ->whereDate('date_start','>=',Carbon::today())
                    ->pluck('fecha')->toArray();

                //dd($bloqueosNoche);


                $bloqueosDiaBloc = Block::selectRaw('DATE_FORMAT( day, "%d-%m-%Y") as fecha')
                    ->where('boat_id', $boatpost->id)
                    ->where('schedule_id', $sDia)
                    ->whereDate('day','>=',Carbon::today())
                    ->pluck('fecha')->toArray();

                $bloqueosNocheBloc = Block::selectRaw('DATE_FORMAT( day, "%d-%m-%Y") as fecha')
                    ->where('boat_id', $boatpost->id)
                    ->where('schedule_id', $sNoche)
                    ->whereDate('day','>=',Carbon::today())
                    ->pluck('fecha')->toArray();

                $bloqueoReservationsDia = Reservations::select(DB::raw('DISTINCT DATE_FORMAT( date_start, "%d-%m-%Y") as fecha'))
                    ->where('boat_id', $boatpost->id)
                    ->whereDate('date_start','>=',Carbon::today())
                    ->where('schedule_id', $sDia)
                    ->where('user_id', Auth::user()->id)
                    ->where('status_id', '!=', 3)
                    ->with('boat')->pluck('fecha')->toArray();;
                 //dd($bloqueoReservationsDia);

                $bloqueoReservationsNoche = Reservations::select(DB::raw('DISTINCT DATE_FORMAT( date_start, "%d-%m-%Y") as fecha'))
                    ->where('boat_id', $boatpost->id)
                    ->where('schedule_id', $sNoche)
                    ->where('user_id', Auth::user()->id)
                    ->where('status_id', '!=', 3)
                    ->whereDate('date_start','>=',Carbon::today())
                    ->with('boat')->pluck('fecha')->toArray();;
                // dd($bloqueoReservationsNoche);

                $rangedates = [];
                foreach($dates as $day) {
                    $color = '#fafafa';
                    $text_color = '#000';
                    $date = Carbon::createFromFormat('Y-m-d', $day)->format('d-m-Y'); // HERE
                    $dia = 'Dia';

                    if ( (is_array($bloqueoReservationsDia) && in_array($date,$bloqueoReservationsDia))  ||
                        (is_array($bloqueosDiaConfirmadas) && in_array($date,$bloqueosDiaConfirmadas)) || (is_array($bloqueosDiaBloc) && in_array($date,$bloqueosDiaBloc) ) ){

                    }
                    elseif ( is_array($bloqueosDia) && in_array($date,$bloqueosDia) )
                    {
                        // "En espera",
                        $rangedates[] = \Calendar::event(
                            "Dia",
                            true,
                            $day,
                            $day,
                            1,
                            [
                                'url' => route('reservations', ['date_start'=> $date,'user_id' => Auth::user()->id,'boat_id' => $boatpost,'schedule' => $sDia, 'status' => 4]),
                                'color' => '#00c0ef',
                                'textColor' => $text_color,
                                'className' => 'wait-reservations'
                            ]
                        );
                    }
                    else{
                        $rangedates[] = \Calendar::event(
                            $dia,
                            true,
                            $day,
                            $day,
                            1,
                            [
                                'url' => route('reservations', ['date_start'=> $date,'user_id' => Auth::user()->id,'boat_id' => $boatpost,'schedule' => $sDia]),
                                'color' => $color,
                                'textColor' => $text_color,
                                'className' => 'prereservations'
                            ]
                        );

                    }


                    $dia = 'Noche';
                    if( (is_array($bloqueoReservationsNoche) && in_array($date, $bloqueoReservationsNoche)) || (is_array($bloqueosNocheConfirmadas) && in_array($date,$bloqueosNocheConfirmadas)) || (is_array($bloqueosNocheBloc) && in_array($date,$bloqueosNocheBloc))  ){

                    }
                    elseif(is_array($bloqueosNoche) && in_array($date, $bloqueosNoche))
                    {
                        // "En espera",
                        $rangedates[] = \Calendar::event(
                            "Noche",
                            true,
                            $day,
                            $day,
                            1,
                            [
                                'url' => route('reservations', ['date_start'=> $date,'user_id' => Auth::user()->id,'boat_id' => $boatpost, 'schedule' => $sNoche, 'status' => 4]),
                                'color' => '#00c0ef',
                                'textColor' => $text_color,
                                'className' => 'wait-reservations'
                            ]);
                    }else{
                        $rangedates[] = \Calendar::event(
                            $dia,
                            true,
                            $day,
                            $day,
                            1,
                            [
                                'url' => route('reservations', ['date_start'=> $date,'user_id' => Auth::user()->id,'boat_id' => $boatpost, 'schedule' => $sNoche]),
                                'color' => $color,
                                'textColor' => $text_color,
                                'className' => 'prereservations'
                            ]);

                    }
                }

                $calendar = \Calendar::addEvents($eventos);
                $calendar = \Calendar::addEvents($festive);
                $calendar = \Calendar::addEvents($blocks);
                $calendar = \Calendar::addEvents($rangedates);

                return view('calendar.activities', compact('calendar', 'status', 'festive', 'users', 'boats', 'boatpost', 'barcos', 'boat', 'blocks'));

            }

        }else{
            abort(403);
        }
    }

    public function boat(Request $request)
    {
        $user = User::where('id', $request->user)->first();
        if($user->role_id == 1){
          $boat = Boat::whereNull('deleted_at')->get()->toArray();
        }else{
          $boat =  Customer::find($user->customer_id)->boats()->get()->toArray();
        }
        $boat = json_encode($boat);
        return $boat;
        // return ['boat'=>$boat, 'user'=>$user, 'request' => $request ];
    }

    private function generateDateRange(Carbon $start_date, Carbon $end_date)
    {
        $dates = [];

        for($date = $start_date; $date->lte($end_date); $date->addDay()) {
            $dates[] = $date->format('Y-m-d');

        }

        return $dates;
    }

    /** Actual month last day **/
    function data_last_month_day() {
        $month = date('m');
        $year = date('Y')+1;
        $day = date("d", mktime(0,0,0, $month+1, 0, $year));
        $date= Carbon::createFromDate($year, 12, $day);
        return $date;

    }

    /** Actual month first day **/
    function data_first_month_day() {
        $month = date('m');
        $year = date('Y');
        return date('Y-m-d', mktime(0,0,0, $month, 1, $year));
    }

}
