<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \App\Notifications\mail;
use \App\Notifications\sms;
use \App\Notifications\Alert;
use \App\Log;
use \App\Schedule;
use \App\Local;
use \App\User;
use Carbon\Carbon;


class CalendarController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['generate','load','delete']]);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        Log::saveLog("Affichage de l'horaire");

        $this->listClass();

        return view('admin.calendar.calendar_display');
    }

    public function generate()
    {
        $lang = str_replace('_', '-', app()->getLocale());
        setlocale(LC_ALL, $lang.'_'.strtoupper($lang).'.utf8','fra'); 

        $month = request('month');
        $year = request('year');

        $nextMonth = $month + 1;
        $nextYear = $year;

        if ($nextMonth > 12) {
            $nextMonth = 1;
            $nextYear = $nextYear + 1;
        }

        $prevMonth = $month - 1;
        $prevYear = $year;

        if ($prevMonth < 1) {
            $prevMonth = 12;
            $prevYear = $prevYear - 1;
        }

        $calendar = array();

        $dayinmonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);

        $firstdaymonth = date("w", strtotime("01-".$month."-".$year));

        $addingday = 0;

        for ($i=$firstdaymonth ; $addingday < $dayinmonth ; $i++) {
            $addingday = $addingday + 1;
            $calendar[$i] = $addingday;
        }

        echo '<div class="table calendar">';
        echo '<div class="thead-dark">';
        echo '<div class="row"><div class="col-2"><a class="btn" onclick="generate('.$prevMonth.','.$prevYear.')"><i class="fa fa-chevron-left" aria-hidden="true"></i></a></div><div class="col-8">'.ucfirst(strftime("%B %Y", strtotime("01-".$month."-".$year))).'</div><div class="col-2"><a class="btn" onclick="generate('.$nextMonth.','.$nextYear.')"><i class="fa fa-chevron-right" aria-hidden="true"></i></a></div></div>';
        echo '<div class="row calendar-head"><div style="width:14%;">Dimanche</div><div style="width:14%;">Lundi</div><div style="width:14%;">Mardi</div><div style="width:14%;">Mercredi</div><div style="width:14%;">Jeudi</div><div style="width:14%;">Vendredi</div><div style="width:14%;">Samedi</div></div>';
        echo '</div>';
        echo '<div class="card-body">';
        for ($i=0; $i < 6 ; $i++)
        {
            echo '<div class="row">';
            for ($a=0; $a < 7 ; $a++)
            {
                if (isset($calendar[(($i*7) + $a)]))
                {
                    /** Date info */
                    $today = date("Y-m-d", strtotime($year."-".$month."-".$calendar[(($i*7) + $a)]));
                    $activityToday = Schedule::where('date','=',$today)->get();

                    /** If nothing today */
                    if ($activityToday->isEmpty()) {
                    echo '<a class="calendar-container calendar-empty" name="'.$today.'" type="button" data-toggle="modal" data-target="#scrollmodal" id="calendar_'.$calendar[(($i*7) + $a)].'" class="btn btn-block btn-calendar" onclick="openCalendar(this.name)"><div class="calendar-date">'.date("j", strtotime($today)).'</div></a>';
                    } else {
                        echo '<a class="calendar-container" name="'.$today.'" type="button" data-toggle="modal" data-target="#scrollmodal" id="calendar_'.$calendar[(($i*7) + $a)].'" class="btn btn-block btn-calendar" onclick="openCalendar(this.name)"><div class="calendar-date">'.date("j", strtotime($today)).'</div>';
                        $text = "";
                        foreach ($activityToday as $activity) {
                            echo '<div class="calendar-text" style="width:90%;height:3rem;">';
                                        switch ($activity->type) {
                                            case 'regular':
                                                echo '<div class="row" style="color:orange;"><span class="fa-stack fa-lg col-md-2"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-book fa-stack-1x fa-inverse"></i></span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>";
                                                break;
                                            
                                            case 'pilotage':
                                                echo '<div class="row" style="color:#58D3F7;"><span class="fa-stack fa-lg col-md-2"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-plane fa-stack-1x fa-inverse"></i></span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>";
                                                break;
                                            
                                            case 'drill':
                                                echo '<div class="row" style="color:blue;"><span class="fa-stack fa-lg col-md-2"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-trophy fa-stack-1x fa-inverse"></i></span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>";                                                
                                                break;
                                            
                                            case 'music':
                                                echo '<div class="row" style="color:green;"><span class="fa-stack fa-lg col-md-2"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-music fa-stack-1x fa-inverse"></i></span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>"; 
                                                break;
                                            
                                            case 'biathlon':
                                                echo '<div class="row" style="color:red;"><span class="fa-stack fa-lg col-md-2"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-snowflake-o fa-stack-1x fa-inverse"></i></span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>"; 
                                                break;
                                            
                                            case 'marksmanship':
                                                echo '<div class="row" style="color:grey;"><span class="fa-stack fa-lg col-md-2"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-star fa-stack-1x fa-inverse"></i></span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>"; 
                                                break;
                                            
                                            case 'founding':
                                                echo '<div class="row" style="color:#00FF40;"><span class="fa-stack fa-lg col-md-2"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-usd fa-stack-1x fa-inverse"></i></span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>"; 
                                                break;
                                            
                                            case 'volunteer':
                                                echo '<div class="row" style="color:#DF0174;"><span class="fa-stack fa-lg col-md-2"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-handshake-o fa-stack-1x fa-inverse"></i></span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>"; 
                                                break;
                                                
                                            case 'other':
                                                echo '<div class="row" style="color:#DF0174;"><span class="fa-stack fa-lg col-md-2"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-handshake-o fa-stack-1x fa-inverse"></i></span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>"; 
                                                break;
                                            
                                            default:
                                                echo '<div class="row" style="color:'.\App\ComplementaryActivity::find($activity->type)->calendar_color.';"><span class="fa-stack fa-lg col-md-2">'.\App\ComplementaryActivity::find($activity->type)->calendar_icon.'</span><div class="col-md-10 calendar_event_name">'.ucfirst($activity->data['event_name'])."</div></div>"; 
                                                break;
                                        }
                                echo '</div>';
                        }
                    echo '</a>';
                    }
                } else {
                    echo '<div class="calendar-container¸calendar-empty" style="border:none !important; width:14%;"></div>';
                }
            }
            echo '</div>';
        }

    }

    public function load()
    {

        $lang = str_replace('_', '-', app()->getLocale());
        setlocale(LC_ALL, $lang.'_'.strtoupper($lang).'.utf8','fra');

        $Requestdate = request('date');

        $url = str_replace("-","_", $Requestdate);

        /** Dont work ... API stuff
         * Log::saveLog("a consulté l'horaire du ".$date);
         **/

        $today = Schedule::where('date','=',$Requestdate)->get();
        $isEmpty = $today->isEmpty();

        echo '<div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="scrollmodalLabel">'.ucfirst(strftime("%A le %e %B %Y", strtotime($Requestdate))).'</h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button></div><div class="modal-body">';
        foreach ($today as $date) {

            if ($date->data['is_event_mandatory'] == "on") {
                $is_mandatory = "<div class='btn btn-block btn-warning m-l-10 m-b-10 float-right'>Activité obligatoire</div>";
            } else {
                $is_mandatory = "<div class='btn btn-block btn-primary m-l-10 m-b-10 float-right'>Activité n'est pas obligatoire</div>";
            }

            echo(
                '<div class="row">'.
                    '<div class="col-7">'.
                        '<p>'.$date->data['event_name'].trans('calendar.begin_at').$date->data['event_begin_time'].trans('calendar.end_at').$date->data['event_end_time'].'</p>'.
                    '</div>'.
                    '<div class="col-3">'.
                        $is_mandatory.
                    '</div>'.
                    '<div class="col-1">'.
                        '<a href="/admin/calendar/edit/'.$date->id.'" type="button" class="btn btn-secondary"><i class="fa fa-cog"></i>&nbsp; Modifier</a>'.
                    '</div>'.
                    '<div class="col-1">'.
                        '<a type="button" class="btn btn-danger" onclick="deleteEvent('.$date->id.');"><i class="fa fa-times-circle" style="color:white;"></i></a>'.
                    '</div>'.
                '</div>'.
                '<p>'.$date->data['event_desc'].
                '</p>'
            );

            if ($date->type == "regular") {

                if($date->data['n1_p1_plandone'] == "on")
                {
                    $isdone_n1_p1 = '<span class="badge badge-success">Remis</span></i>';
                } else {
                    $isdone_n1_p1 = '<span class="badge badge-danger">Non remis</span>';
                }

                if($date->data['n1_p2_plandone'] == "on")
                {
                    $isdone_n1_p2 = '<span class="badge badge-success">Remis</span></i>';
                } else {
                    $isdone_n1_p2 = '<span class="badge badge-danger">Non remis</span>';
                }

                if($date->data['n2_p1_plandone'] == "on")
                {
                    $isdone_n2_p1 = '<span class="badge badge-success">Remis</span></i>';
                } else {
                    $isdone_n2_p1 = '<span class="badge badge-danger">Non remis</span>';
                }

                if($date->data['n2_p2_plandone'] == "on")
                {
                    $isdone_n2_p2 = '<span class="badge badge-success">Remis</span></i>';
                } else {
                    $isdone_n2_p2 = '<span class="badge badge-danger">Non remis</span>';
                }

                if($date->data['n3_p1_plandone'] == "on")
                {
                    $isdone_n3_p1 = '<span class="badge badge-success">Remis</span></i>';
                } else {
                    $isdone_n3_p1 = '<span class="badge badge-danger">Non remis</span>';
                }

                if($date->data['n3_p2_plandone'] == "on")
                {
                    $isdone_n3_p2 = '<span class="badge badge-success">Remis</span></i>';
                } else {
                    $isdone_n3_p2 = '<span class="badge badge-danger">Non remis</span>';
                }
                echo '<table class="table">
                <thead class="thead-dark">
                  <tr>
                    <th>Niveau</th>
                    <th style="width:45%">1er Période</th>
                    <th style="width:45%">2e Période</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <th>1</th>
                    <td>
                        <table class="table float center" style="border:none; max-width:80%; margin:auto;">
                            <tbody>
                                <tr style="border:none;">
                                    <td style="border:none; width:80%">'.User::find($date->data['n1_p1_instructor'])->fullname().'</td>
                                    <td style="border:none;">'.$isdone_n1_p1.'</td>
                                    <td style="border:none;"><a href="/admin/inventory/'.$date->id.'/1/1" type="button" class="btn btn-info"><i class="fa fa-archive" style="color:white;"></i></a></td>
                                </tr>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.$date->data['n1_p1_ocom'].' - '.$date->data['n1_p1_name'].'</td>
                                    <td style="border:none;">'.Local::find($date->data['n1_p1_local'])->name.'</td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                    <td>
                        <table class="table float center" style="border:none; max-width:80%; margin:auto;">
                            <tbody>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.User::find($date->data['n1_p2_instructor'])->fullname().'</td>
                                    <td style="border:none;">'.$isdone_n1_p2.'</td>
                                    <td style="border:none;"><a href="/admin/inventory/'.$date->id.'/2/1" type="button" class="btn btn-info"><i class="fa fa-archive" style="color:white;"></i></a></td>
                                </tr>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.$date->data['n1_p2_ocom'].' - '.$date->data['n1_p2_name'].'</td>
                                    <td style="border:none;">'.Local::find($date->data['n1_p2_local'])->name.'</td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                  </tr>
                  <tr>
                    <th>2</th>
                    <td>
                        <table class="table float center" style="border:none; max-width:80%; margin:auto;">
                            <tbody>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.User::find($date->data['n2_p1_instructor'])->fullname().'</td>
                                    <td style="border:none;">'.$isdone_n2_p1.'</td>
                                    <td style="border:none;"><a href="/admin/inventory/'.$date->id.'/1/2" type="button" class="btn btn-info"><i class="fa fa-archive" style="color:white;"></i></a></td>
                                </tr>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.$date->data['n2_p1_ocom'].' - '.$date->data['n2_p1_name'].'</td>
                                    <td style="border:none;">'.Local::find($date->data['n2_p1_local'])->name.'</td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                    <td>
                        <table class="table float center" style="border:none; max-width:80%; margin:auto;">
                            <tbody>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.User::find($date->data['n2_p2_instructor'])->fullname().'</td>
                                    <td style="border:none;">'.$isdone_n2_p2.'</td>
                                    <td style="border:none;"><a href="/admin/inventory/'.$date->id.'/2/2" type="button" class="btn btn-info"><i class="fa fa-archive" style="color:white;"></i></a></td>
                                </tr>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.$date->data['n2_p2_ocom'].' - '.$date->data['n2_p2_name'].'</td>
                                    <td style="border:none;">'.Local::find($date->data['n2_p2_local'])->name.'</td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                  </tr>
                  <tr>
                    <th>3</th>
                    <td>
                        <table class="table float center" style="border:none; max-width:80%; margin:auto;">
                            <tbody>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.User::find($date->data['n3_p1_instructor'])->fullname().'</td>
                                    <td style="border:none;">'.$isdone_n3_p1.'</td>
                                    <td style="border:none;"><a href="/admin/inventory/'.$date->id.'/1/3" type="button" class="btn btn-info"><i class="fa fa-archive" style="color:white;"></i></a></td>
                                </tr>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.$date->data['n3_p1_ocom'].' - '.$date->data['n3_p1_name'].'</td>
                                    <td style="border:none;">'.Local::find($date->data['n3_p1_local'])->name.'</td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                    <td>
                        <table class="table float center" style="border:none; max-width:80%; margin:auto;">
                            <tbody>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.User::find($date->data['n3_p2_instructor'])->fullname().'</td>
                                    <td style="border:none;">'.$isdone_n3_p2.'</td>
                                    <td style="border:none;"><a href="/admin/inventory/'.$date->id.'/2/3" type="button" class="btn btn-info"><i class="fa fa-archive" style="color:white;"></i></a></td>
                                </tr>
                                <tr style="border:none;">
                                    <td style="border:none;width:80%">'.$date->data['n3_p2_ocom'].' - '.$date->data['n3_p2_name'].'</td>
                                    <td style="border:none;">'.Local::find($date->data['n3_p2_local'])->name.'</td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                  </tr>
                </tbody>
              </table>';
            }
            echo '<br><hr><br>';
        }

        echo '<a href="/admin/calendar/add/'.$url.'" type="button" class="btn btn-primary btn-lg btn-block">'.trans('calendar.add_to_schedule').'</a></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">'.trans('pagination.close').'</button></div></div>';
    }

    public function add($date)
    {
        $lang = str_replace('_', '-', app()->getLocale());
        setlocale(LC_ALL, $lang.'_'.strtoupper($lang).'.utf8','fra');

        $date = str_replace("_", "-", $date);

        $UserList = User::all();
        $LocalList = Local::all();

        return view('admin.calendar.calendar_add' ,[
            'RequestDate' => $date, 
            'Userslist' => $UserList, 
            'LocalsList' => $LocalList,
            'ComplementaryActivity' => \App\ComplementaryActivity::all()]);
    }

    public function edit($id)
    {
        $schedule = Schedule::find($id);
        $UserList = User::all();
        $LocalList = Local::all();

        return view('admin.calendar.calendar_edit' ,['RequestSchedule' => $schedule, 'Userslist' => $UserList, 'LocalsList' => $LocalList]);
    }

    public function store()
    {
        $schedule = new Schedule;

        $schedule->date = request('event_date');
        $schedule->type = request('event_type');

        if(request('event_type') == "regular")
        {
            $eventData = [
                "event_name" => request('event_name'),
                "is_event_mandatory" => request('is_event_mandatory'),
                "event_date" => request('event_date'),
                "event_begin_time" => request('event_begin_time'),
                "event_end_time" => request('event_end_time'),
                "event_location" => request('event_location'),
                "event_desc" => request('event_desc'),
                "n1_p1_name" => request('n1_p1_name'),
                "n1_p1_ocom" => request('n1_p1_ocom'),
                "n1_p1_instructor" => request('n1_p1_instructor'),
                "n1_p1_local" => request('n1_p1_local'),
                "n1_p1_plandone" => request('n1_p1_plandone'),
                "n1_p2_name" => request('n1_p2_name'),
                "n1_p2_ocom" => request('n1_p2_ocom'),
                "n1_p2_instructor" => request('n1_p2_instructor'),
                "n1_p2_local" => request('n1_p2_local'),
                "n1_p2_plandone" => request('n1_p2_plandone'),
                "n2_p1_name" => request('n2_p1_name'),
                "n2_p1_ocom" => request('n2_p1_ocom'),
                "n2_p1_instructor" => request('n2_p1_instructor'),
                "n2_p1_local" => request('n2_p1_local'),
                "n2_p1_plandone" => request('n2_p1_plandone'),
                "n2_p2_name" => request('n2_p2_name'),
                "n2_p2_ocom" => request('n2_p2_ocom'),
                "n2_p2_instructor" => request('n2_p2_instructor'),
                "n2_p2_local" => request('n2_p2_local'),
                "n2_p2_plandone" => request('n2_p2_plandone'),
                "n3_p1_name" => request('n3_p1_name'),
                "n3_p1_ocom" => request('n3_p1_ocom'),
                "n3_p1_instructor" => request('n3_p1_instructor'),
                "n3_p1_local" => request('n3_p1_local'),
                "n3_p1_plandone" => request('n3_p1_plandone'),
                "n3_p2_name" => request('n3_p2_name'),
                "n3_p2_ocom" => request('n3_p2_ocom'),
                "n3_p2_instructor" => request('n3_p2_instructor'),
                "n3_p2_local" => request('n3_p2_local'),
                "n3_p2_plandone" => request('n3_p2_plandone'),
            ];
        } else {
            $eventData = [
                "event_name" => request('event_name'),
                "is_event_mandatory" => request('is_event_mandatory'),
                "event_date" => request('event_date'),
                "event_begin_time" => request('event_begin_time'),
                "event_end_time" => request('event_end_time'),
                "event_location" => request('event_location'),
                "event_desc" => request('event_desc'),
            ];
        }

        $schedule->data = $eventData;

        $schedule->save();

        /** Logs and Notification */
        Log::saveLog("Ajout de l'activité, ".$schedule->data['event_name']." à l'horaire le ".$schedule->date);

        $userToNotify = $schedule->getUserToNotify();
        \Notification::send($userToNotify, new Alert(\Auth::User()->id,"Ajout de l'activité, ".$schedule->data['event_name']." à l'horaire le ".$schedule->date,"/admin/calendar"));

        if(\App\Config::where('name','is_schedule_build')->first()->state == 1)
        {
            \Notification::send($userToNotify, new mail(\Auth::User(),"Ajout d'une activité a l'horaire",\Auth::User()->fullname()." à ajouté l'activité, ".$schedule->data['event_name']." à l'horaire le ".$schedule->date));
        }
        return redirect('/admin/calendar');
        
    }

    public function patch($id)
    {
        $schedule = Schedule::find($id);
        $original = clone($schedule);

        $schedule->date = request('event_date');
        $schedule->type = request('event_type');

        if(request('event_type') == "regular")
        {
            $eventData = [
                "event_name" => request('event_name'),
                "is_event_mandatory" => request('is_event_mandatory'),
                "event_date" => request('event_date'),
                "event_begin_time" => request('event_begin_time'),
                "event_end_time" => request('event_end_time'),
                "event_location" => request('event_location'),
                "event_desc" => request('event_desc'),
                "n1_p1_name" => request('n1_p1_name'),
                "n1_p1_ocom" => request('n1_p1_ocom'),
                "n1_p1_instructor" => request('n1_p1_instructor'),
                "n1_p1_local" => request('n1_p1_local'),
                "n1_p1_plandone" => request('n1_p1_plandone'),
                "n1_p2_name" => request('n1_p2_name'),
                "n1_p2_ocom" => request('n1_p2_ocom'),
                "n1_p2_instructor" => request('n1_p2_instructor'),
                "n1_p2_local" => request('n1_p2_local'),
                "n1_p2_plandone" => request('n1_p2_plandone'),
                "n2_p1_name" => request('n2_p1_name'),
                "n2_p1_ocom" => request('n2_p1_ocom'),
                "n2_p1_instructor" => request('n2_p1_instructor'),
                "n2_p1_local" => request('n2_p1_local'),
                "n2_p1_plandone" => request('n2_p1_plandone'),
                "n2_p2_name" => request('n2_p2_name'),
                "n2_p2_ocom" => request('n2_p2_ocom'),
                "n2_p2_instructor" => request('n2_p2_instructor'),
                "n2_p2_local" => request('n2_p2_local'),
                "n2_p2_plandone" => request('n2_p2_plandone'),
                "n3_p1_name" => request('n3_p1_name'),
                "n3_p1_ocom" => request('n3_p1_ocom'),
                "n3_p1_instructor" => request('n3_p1_instructor'),
                "n3_p1_local" => request('n3_p1_local'),
                "n3_p1_plandone" => request('n3_p1_plandone'),
                "n3_p2_name" => request('n3_p2_name'),
                "n3_p2_ocom" => request('n3_p2_ocom'),
                "n3_p2_instructor" => request('n3_p2_instructor'),
                "n3_p2_local" => request('n3_p2_local'),
                "n3_p2_plandone" => request('n3_p2_plandone'),
            ];
        } else {
            $eventData = [
                "event_name" => request('event_name'),
                "is_event_mandatory" => request('is_event_mandatory'),
                "event_date" => request('event_date'),
                "event_begin_time" => request('event_begin_time'),
                "event_end_time" => request('event_end_time'),
                "event_location" => request('event_location'),
                "event_desc" => request('event_desc'),
            ];
        }

        $schedule->data = $eventData;

        $schedule->save();

        /** Notification */
        $asChange = false;
        $userToNotify = $schedule->getUserToNotify();
        $changes = [];
        $found = false;

        if ($schedule->type == "regular") {
            for ($p=1; $p < 3; $p++) { 
                for ($n=1; $n < 4; $n++) { 
                    $pUser = \App\User::find($schedule->data['n'.$n.'_p'.$p.'_instructor']);
                    foreach ($userToNotify as $user) {
                        if ($user->id == $pUser->id) {
                            $found = true;
                        }
                    }
                    if (!$found) {
                        $userToNotify->push($pUser);
                    }    
                }
            } 
        }

        if ($schedule->data['event_begin_time'] != $original->data['event_begin_time']) {
            array_push($changes,"L'heure de début a été modifié de ".$original->data['event_begin_time']." à ".$schedule->data['event_begin_time']);
        }
        if ($schedule->data['event_end_time'] != $original->data['event_end_time']) {
            array_push($changes,"L'heure de fin a été modifié de ".$original->data['event_end_time']." à ".$schedule->data['event_end_time']);
        }
        if ($schedule->type != $original->type) {
            array_push($changes,"Le type d'évenement a été modifié de ".$original->type." à ".$schedule->type);
        }
        if ($schedule->data['event_name'] != $original->data['event_name']) {
            array_push($changes,"Le nom de l'évenement a été modifié de ".$original->data['event_name']." à ".$schedule->data['event_name']);
        }
        if ($schedule->data['is_event_mandatory'] != $original->data['is_event_mandatory']) {
            if ($schedule->data['is_event_mandatory'] == "on") {
                array_push($changes,"L'évenement est maintenant obligatoire");
            } else {
                array_push($changes,"L'évenement n'est plus obligatoire");
            }
        }
        if ($schedule->data['event_location'] != $original->data['event_location']) {
            array_push($changes,"Le lieu de l'évenement a été modifié de ".$original->data['event_location']." à ".$schedule->data['event_location']);
        }
        if ($schedule->data['event_desc'] != $original->data['event_desc']) {
            array_push($changes,"La description de l'évenement a été modifié de ".$original->data['event_desc']." à ".$schedule->data['event_desc']);
        }   

        if ($schedule->type == "regular") {
            /** Check Instructor */
            if ($schedule->data['n1_p1_instructor'] != $original->data['n1_p1_instructor']) {
                array_push($changes,"L'instructeur du niveau 1 pour la première période a été changé de ".\App\User::find($original->data['n1_p1_instructor'])->fullname()." à ".\App\User::find($schedule->data['n1_p1_instructor'])->fullname());
                \Notification::send(\App\User::find($original->data['n1_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$original->data['n1_p1_name']." du ".$original->date." vous a été retiré."));
                \Notification::send(\App\User::find($schedule->data['n1_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$schedule->data['n1_p1_name']." du ".$schedule->date." vous a été ajouté."));
            }
            if ($schedule->data['n1_p2_instructor'] != $original->data['n1_p2_instructor']) {
                array_push($changes,"L'instructeur du niveau 1 pour la deuxième période a été changé de ".\App\User::find($original->data['n1_p2_instructor'])->fullname()." à ".\App\User::find($schedule->data['n1_p2_instructor'])->fullname());
                \Notification::send(\App\User::find($original->data['n1_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$original->data['n1_p2_name']." du ".$original->date." vous a été retiré."));
                \Notification::send(\App\User::find($schedule->data['n1_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$schedule->data['n1_p2_name']." du ".$schedule->date." vous a été ajouté."));
            }
            if ($schedule->data['n2_p1_instructor'] != $original->data['n2_p1_instructor']) {
                array_push($changes,"L'instructeur du niveau 2 pour la première période a été changé de ".\App\User::find($original->data['n2_p1_instructor'])->fullname()." à ".\App\User::find($schedule->data['n2_p1_instructor'])->fullname());
                \Notification::send(\App\User::find($original->data['n2_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$original->data['n2_p1_name']." du ".$original->date." vous a été retiré."));
                \Notification::send(\App\User::find($schedule->data['n2_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$schedule->data['n2_p1_name']." du ".$schedule->date." vous a été ajouté."));
            }
            if ($schedule->data['n2_p2_instructor'] != $original->data['n2_p2_instructor']) {
                array_push($changes,"L'instructeur du niveau 2 pour la deuxième période a été changé de ".\App\User::find($original->data['n2_p2_instructor'])->fullname()." à ".\App\User::find($schedule->data['n2_p2_instructor'])->fullname());
                \Notification::send(\App\User::find($original->data['n2_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$original->data['n2_p2_name']." du ".$original->date." vous a été retiré."));
                \Notification::send(\App\User::find($schedule->data['n2_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$schedule->data['n2_p2_name']." du ".$schedule->date." vous a été ajouté."));
            }
            if ($schedule->data['n3_p1_instructor'] != $original->data['n3_p1_instructor']) {
                array_push($changes,"L'instructeur du niveau 3 pour la première période a été changé de ".\App\User::find($original->data['n3_p1_instructor'])->fullname()." à ".\App\User::find($schedule->data['n3_p1_instructor'])->fullname());
                \Notification::send(\App\User::find($original->data['n3_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$original->data['n3_p1_name']." du ".$original->date." vous a été retiré."));
                \Notification::send(\App\User::find($schedule->data['n3_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$schedule->data['n3_p1_name']." du ".$schedule->date." vous a été ajouté."));
            }
            if ($schedule->data['n3_p2_instructor'] != $original->data['n3_p2_instructor']) {
                array_push($changes,"L'instructeur du niveau 3 pour la deuxième période a été changé de ".\App\User::find($original->data['n3_p2_instructor'])->fullname()." à ".\App\User::find($schedule->data['n3_p2_instructor'])->fullname());
                \Notification::send(\App\User::find($original->data['n3_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$original->data['n3_p2_name']." du ".$original->date." vous a été retiré."));
                \Notification::send(\App\User::find($schedule->data['n3_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le cours ".$schedule->data['n3_p2_name']." du ".$schedule->date." vous a été ajouté."));
            }
            /** Check OCOM */
            if ($schedule->data['n1_p1_ocom'] != $original->data['n1_p1_ocom']) {
                array_push($changes,"L'OCOM du niveau 1 pour la première période a été changé de ".$original->data['n1_p1_ocom']." à ".$schedule->data['n1_p1_ocom']);
                \Notification::send(\App\User::find($schedule->data['n1_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","L'ocom du cours ".$schedule->data['n1_p1_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n1_p1_ocom']));
            }
            if ($schedule->data['n1_p2_ocom'] != $original->data['n1_p2_ocom']) {
                array_push($changes,"L'OCOM du niveau 1 pour la deuxième période a été changé de ".$original->data['n1_p2_ocom']." à ".$schedule->data['n1_p2_ocom']);
                \Notification::send(\App\User::find($schedule->data['n1_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","L'ocom du cours ".$schedule->data['n1_p2_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n1_p2_ocom']));
            }
            if ($schedule->data['n2_p1_ocom'] != $original->data['n2_p1_ocom']) {
                array_push($changes,"L'OCOM du niveau 2 pour la première période a été changé de ".$original->data['n2_p1_ocom']." à ".$schedule->data['n2_p1_ocom']);
                \Notification::send(\App\User::find($schedule->data['n2_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","L'ocom du cours ".$schedule->data['n2_p1_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n2_p1_ocom']));
            }
            if ($schedule->data['n2_p2_ocom'] != $original->data['n2_p2_ocom']) {
                array_push($changes,"L'OCOM du niveau 2 pour la deuxième période a été changé de ".$original->data['n2_p2_ocom']." à ".$schedule->data['n2_p2_ocom']);
                \Notification::send(\App\User::find($schedule->data['n2_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","L'ocom du cours ".$schedule->data['n2_p2_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n2_p2_ocom']));
            }
            if ($schedule->data['n3_p1_ocom'] != $original->data['n3_p1_ocom']) {
                array_push($changes,"L'OCOM du niveau 3 pour la première période a été changé de ".$original->data['n3_p1_ocom']." à ".$schedule->data['n3_p1_ocom']);
                \Notification::send(\App\User::find($schedule->data['n3_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","L'ocom du cours ".$schedule->data['n3_p1_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n3_p1_ocom']));
            }
            if ($schedule->data['n3_p2_ocom'] != $original->data['n3_p2_ocom']) {
                array_push($changes,"L'OCOM du niveau 3 pour la deuxième période a été changé de ".$original->data['n3_p2_ocom']." à ".$schedule->data['n3_p2_ocom']);
                \Notification::send(\App\User::find($schedule->data['n3_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","L'ocom du cours ".$schedule->data['n3_p2_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n3_p2_ocom']));
            }
            /** Check Local */
            if ($schedule->data['n1_p1_local'] != $original->data['n1_p1_local']) {
                array_push($changes,"Le local du niveau 1 pour la première période a été changé de ".$original->data['n1_p1_local']." à ".$schedule->data['n1_p1_local']);
            }
            if ($schedule->data['n1_p2_local'] != $original->data['n1_p2_local']) {
                array_push($changes,"Le local du niveau 1 pour la deuxième période a été changé de ".$original->data['n1_p2_local']." à ".$schedule->data['n1_p2_local']);
            }
            if ($schedule->data['n2_p1_local'] != $original->data['n2_p1_local']) {
                array_push($changes,"Le local du niveau 2 pour la première période a été changé de ".$original->data['n2_p1_local']." à ".$schedule->data['n2_p1_local']);
            }
            if ($schedule->data['n2_p2_local'] != $original->data['n2_p2_local']) {
                array_push($changes,"Le local du niveau 2 pour la deuxième période a été changé de ".$original->data['n2_p2_local']." à ".$schedule->data['n2_p2_local']);
            }
            if ($schedule->data['n3_p1_local'] != $original->data['n3_p1_local']) {
                array_push($changes,"Le local du niveau 3 pour la première période a été changé de ".$original->data['n3_p1_local']." à ".$schedule->data['n3_p1_local']);
            }
            if ($schedule->data['n3_p2_local'] != $original->data['n3_p2_local']) {
                array_push($changes,"Le local du niveau 3 pour la deuxième période a été changé de ".$original->data['n3_p2_local']." à ".$schedule->data['n3_p2_local']);
            }
            /** Check Name */
            if ($schedule->data['n1_p1_name'] != $original->data['n1_p1_name']) {
                array_push($changes,"Le nom du cours niveau 1 pour la première période a été changé de ".$original->data['n1_p1_name']." à ".$schedule->data['n1_p1_name']);
                \Notification::send(\App\User::find($schedule->data['n1_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le nom du cours ".$original->data['n1_p1_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n1_p1_name']));
            }
            if ($schedule->data['n1_p2_name'] != $original->data['n1_p2_name']) {
                array_push($changes,"Le nom du cours niveau 1 pour la deuxième période a été changé de ".$original->data['n1_p2_name']." à ".$schedule->data['n1_p2_name']);
                \Notification::send(\App\User::find($schedule->data['n1_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le nom du cours ".$original->data['n1_p2_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n1_p2_name']));
            }
            if ($schedule->data['n2_p1_name'] != $original->data['n2_p1_name']) {
                array_push($changes,"Le nom du cours niveau 2 pour la première période a été changé de ".$original->data['n2_p1_name']." à ".$schedule->data['n2_p1_name']);
                \Notification::send(\App\User::find($schedule->data['n2_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le nom du cours ".$original->data['n2_p1_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n2_p1_name']));
            }
            if ($schedule->data['n2_p2_name'] != $original->data['n2_p2_name']) {
                array_push($changes,"Le nom du cours niveau 2 pour la deuxième période a été changé de ".$original->data['n2_p2_name']." à ".$schedule->data['n2_p2_name']);
                \Notification::send(\App\User::find($schedule->data['n2_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le nom du cours ".$original->data['n2_p2_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n2_p2_name']));
            }
            if ($schedule->data['n3_p1_name'] != $original->data['n3_p1_name']) {
                array_push($changes,"Le nom du cours niveau 3 pour la première période a été changé de ".$original->data['n3_p1_name']." à ".$schedule->data['n3_p1_name']);
                \Notification::send(\App\User::find($schedule->data['n3_p1_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le nom du cours ".$original->data['n3_p1_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n3_p1_name']));            
            }
            if ($schedule->data['n3_p2_name'] != $original->data['n3_p2_name']) {
                array_push($changes,"Le nom du cours niveau 3 pour la deuxième période a été changé de ".$original->data['n3_p2_name']." à ".$schedule->data['n3_p2_name']);
                \Notification::send(\App\User::find($schedule->data['n3_p2_instructor']), new mail(\Auth::User(),"Modification d'un de vos cours","Le nom du cours ".$original->data['n3_p2_name']." du ".$schedule->date." a été changé pour ".$schedule->data['n3_p2_name']));            
            }
        }

        \Notification::send($userToNotify, new Alert(\Auth::User()->id,"Modification de l'activité, ".$schedule->data['event_name']." à l'horaire le ".$schedule->date,"/admin/calendar"));
    
        $string_Change = "<ul>";
        foreach ($changes as $value) {
            $string_Change = $string_Change."<li>".$value."</li>";
        }
        $string_Change = $string_Change."</ul>";
        if(\App\Config::where('name','is_schedule_build')->first()->state == 1)
        {
            \Notification::send($userToNotify, new mail(\Auth::User(),"Modification d'une activité a l'horaire",\Auth::User()->fullname()." à modifié l'activité, ".$schedule->data['event_name']." à l'horaire le ".$schedule->date."<br>".$string_Change));
        }

        Log::saveLog("Modification de l'activité, ".$schedule->data['event_name']." à l'horaire le ".$schedule->date);

        return redirect('/admin/calendar');

    }

    public function delete()
    {
        $id = request('id');

        $schedule = Schedule::find($id);

        $schedule->delete();

        \Notification::send($userToNotify, new Alert(\Auth::User()->id,"Suppresion de l'activité, ".$schedule->data['event_name']." à l'horaire le ".$schedule->date,"/admin/calendar"));
        
        if(\App\Config::where('name','is_schedule_build')->first()->state == 1)
        {
            \Notification::send($userToNotify, new mail(\Auth::User(),"Suppression d'une activité a l'horaire",\Auth::User()->fullname()." à supprimé l'activité, ".$schedule->data['event_name']." à l'horaire le ".$schedule->date));
        }

        Log::saveLog("Suppression de l'activité, ".$schedule->data['event_name']." à l'horaire le ".$schedule->date);

    }

    private function listClass()
    {
        $schedules = \App\Schedule::all();
        $filtered_schedules = collect();
        $classes = [];

        foreach($schedules as $schedule)
        {
            if($schedule->type == "regular")
            {
                $filtered_schedules->push($schedule);
            }
        }

        foreach($filtered_schedules as $schedule)
        {
            array_push($classes,$schedule->data['n1_p1_ocom']);
            array_push($classes,$schedule->data['n1_p2_ocom']);
            array_push($classes,$schedule->data['n2_p1_ocom']);
            array_push($classes,$schedule->data['n2_p2_ocom']);
            array_push($classes,$schedule->data['n3_p1_ocom']);
            array_push($classes,$schedule->data['n3_p2_ocom']);
        }

        $filtered_classes = array_unique($classes);

        return $filtered_classes;
    }

    public function show()
    {
        $date = request('date');
        return view('admin.calendar.modal.show',['schedules' => \App\Schedule::all()->where('date',$date),'date' => $date]);
    }
}
