<?php

namespace Plugins\BookingPlugin;

use Core\View\View;
use Core\View\ElementView;
use Core\Core\Request;
use Core\Core\Response;
use Core\Entity\Entity\Argument;
use Core\Control\Form\Form;
use Core\Control\Libelle\Libelle;
use Core\Control\ListBox\ListBox;
use Core\Utility\Date\Date;
use Apps\Booking\Entity\BookingType;
use Apps\Booking\Entity\BookingOpeningTime;
use Apps\Booking\Helper\SlotHelper;
use Apps\Booking\Helper\ReservationHelper;

class BookingPlugin {

    public $Author = 'Webemyos';
    public $Version = '1.0.0.0';

    function __construct($core) {
        $this->Core = $core;
    }

    /**
     * Type de plugin, utilisé par AppHelper::GetPluginType
     */
    function GetType() {
        return "Booking";
    }

    /**
     * Script d'enregistrement du plugin (inclus dans la page publique)
     */
    function GetRegisterPlugin() {
        return "<script>document.addEventListener('DOMContentLoaded', function() { " . $this->GetRegister() . " }) ;</script>";
    }

    function GetRegister() {
        return "Plugin.Register('BookingPlugin', 'BookingPlugin', function(){ BookingPlugin.Init(); });";
    }

    /**
     * Rendu principal : formulaire de réservation lié à une entité
     *
     * @param  string $entityName  ex: "CoursesCour"
     * @param  int    $entityId
     */
    function RenderOld($entityName = "", $entityId = 0) {
        $view = new View(__DIR__ . "/View/index.tpl", $this->Core);

        // Récupération de tous les types de réservation disponibles
        $typeEntity = new BookingType($this->Core);
        $types = $typeEntity->Find("1=1");

        // Si un seul type, on le pré-sélectionne
        $defaultType = count($types) === 1 ? $types[0]->Id->Value : null;

        $view->AddElement(new ElementView("Types", $types));
        $view->AddElement(new ElementView("DefaultType", $defaultType));
        $view->AddElement(new ElementView("EntityName", $entityName));
        $view->AddElement(new ElementView("EntityId", $entityId));

        return $view->Render();
    }

    /**
     * Charge une semaine du calendrier
     * @param type $weekNumber
     */
    function Render($entityName = "", $entityId = "", $WeekNumber = "current" ) {
        //Construction du tableau
        $days = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche');

        //Semaine en cours
        $week = ($WeekNumber == 'current') ? date('W') : $WeekNumber;
        $year = date('Y');
        $StartDate = Date::GetFirstDay($week, $year);

        //Affichage de la semaine et des controles de selection
        $view = $this->GetTool($week);

        $view .= "<div id='bookingPluginContainer' data-entity-name='" . $entityName . "' data-entity-id='" . $entityId . "' >";
        //Tableau de la semaine
        $view .= "<table id='taAgenda' class='grid gridTd'>";

        //Entete
        $view .= '<tr>';
        $view .= '<td class="subTitle"></td>';

        //
        $dateDay = array();
        foreach ($days as $day) {
            //Creation de la date actuelle
            $dateDay[] = $StartDate;

            $view .= '<th class="subTitle"><b>' . $this->Core->GetCode($day) . '</b><br/>';
            $view .= '<span class="calendar date">' . Date::ReverseFrench($StartDate, false) . '</span>';
            $view .= '</th>';

            $StartDate = Date::AddDay($StartDate, 1);
        }

        //Creation des lignes
        $view .= '</tr>';

        //recuperation des evenements de l'utilisateur
        $DateStart = Date::AddDay($dateDay[0], -1, true);
        $DateEnd = Date::AddDay($dateDay[0], 7, true);

        $AgendaEvent = new BookingOpeningTime($this->Core);
        $AgendaEvent->AddArgument(new Argument("Apps\Booking\Entity\BookingOpeningTime", "TypeId", EQUAL, 1));
        $EventsUser = $AgendaEvent->GetByArg();

        for ($hours = 9; $hours < 20; $hours++) {
            $view .= '<tr>';

            if ($hours < 10) {
                $hours = "0" . $hours;
            }

            $view .= '<td>' . $hours . ':00</td>';

            //Parcourt des jours
            //foreach($dateDay as $day)
            for ($d = 0; $d < count($dateDay); $d++) {
                //Charge un tableau avec touts les rendez-vous
                $drawCell = true;

                //Parcourt des rendez-vous de l'utilisateur
                if (isset($EventsUser) && count($EventsUser) > 0) {
                    foreach ($EventsUser as $event) {
                        // echo $event->DateStart->Value . "=>" . $dateDay[$d].' '.$hours.':00:00';
                        //Evenement qui commence dans la cellule
                        if (($event->HourStartAm->Value <= $hours . ':00:00' && $event->HourEndAm->Value >= ($hours) . ':00:00' /* Date::IsEqual($event->DateStart->Value,$dateDay[$d].' '.$hours.':00:00' ) */ ||
                                $event->HourStartPm->Value <= $hours . ':00:00' && $event->HourEndPm->Value >= ($hours) . ':00:00' /* Date::IsEqual($event->DateStart->Value,$dateDay[$d].' '.$hours.':00:00' ) */
                                ) && $event->Day->Value == $d
                        ) {

                            $rowSpan = 1;
                            $colSpan = 1;

                            //Affichage de la cellule
                            $view .= '<td class="openingTime" id="' .Date::ReverseFrench($dateDay[$d]) . '|' . $hours . '|" >';
                            //$view .= $this->GetEvent($event, $colSpan, $rowSpan);
                            $view .= "HORAIRE OUVERTURE";

                            $view .= '</td>';

                            $drawCell = false;
                        }
                    }
                }

                //Evenements invités
                if (isset($EventInvits) && count($EventInvits) > 0) {
                    foreach ($EventInvits as $event) {
                        //Evenement qui commence dans la cellule
                        if ($event->Event->Value->DateStart->Value == $dateDay[$d] . ' ' . $hours . ':00:00') {
                            //Dimension de l'evenement
                            $rowSpan = DateHelper::GetDiffHour($event->Event->Value->DateStart->Value, $event->Event->Value->DateEnd->Value);
                            $colSpan = DateHelper::GetDiffDay($event->Event->Value->DateStart->Value, $event->Event->Value->DateEnd->Value);

                            //Affichage de la cellule
                            //$view .=	 '<td id="'.$day.'!'.$hours.'"  colspan="'.$colSpan.'" rowspan="'.$rowSpan.'" >';
                            $view .= '<td id="' . $dateDay[$d] . '!' . $hours . '" >';

                            $view .= $this->GetInvit($event, $colSpan, $rowSpan);
                            $view .= '</td>';

                            $drawCell = false;
                        }
                    }
                }

                //La cellule n'a pas d'évenement
                if ($drawCell) {
                    $view .= '<td id="' . $dateDay[$d] . '!' . $hours . '"></td>';
                }
            }

            $view .= '</tr>';
        }
        $view .= "</table>";

        $view .= "</div>";

        return $view;
    }

    /**
     * Obtient la barre d'outil
     */
    function GetTool($week) {
        $view = "<div id='Week'>";

        $imgBefore = new Libelle("<b onclick='AgendaAction.LoadWeekBefore($week);' class='fa fa-arrow-left'  title='" . $this->Core->GetCode("Agenda.WeekBefore") . "' ></b>");
        $view .= $imgBefore->show() . " ";

        $imgAfter = new Libelle("<b onclick='AgendaAction.LoadWeekAfter($week);' class='fa fa-arrow-right' title='" . $this->Core->GetCode("Agenda.WeekBefore") . "' ></b>");
        $view .= " " . $imgAfter->Show();

        //Semaine selectionnée
        $view .= $this->Core->GetCode("Week") . ' : ';

        $lstWeek = new ListBox("lstWeek");
        $lstWeek->Style = 'width:50px';

        //Ajout des semaines
        for ($i = 1; $i < 53; $i++) {
            $lstWeek->Add($i, $i);
        }

        $lstWeek->Selected = $week;
        $lstWeek->OnChange = 'AgendaAction.LoadWeek(this)';
        $view .= $lstWeek->Show();

        //Legend 
        $view .= "<i class='legendEvent'>&nbsp;</i><i>" . $this->Core->GetCode("Agenda.MyEvent") . "</i>";
        $view .= "<i class='legendInvit'>&nbsp;</i><i>" . $this->Core->GetCode("Agenda.MyInvit") . "</i>";
        $view .= "<i class='legendApp'>&nbsp;</i><i>" . $this->Core->GetCode("Agenda.EventApp") . "</i>";

        $view .= "</div>";

        return $view;
    }

    function OpenReserveDate($params) {
        $contactForm = new Form("reservationForm", $data);

        $contactForm->SetView(__DIR__ . "/View/reservationForm.tpl", $this->Core);
        $contactForm->SetAction("/View/reservationForm.tpl");

        $contactForm->Add(array("Type" => "Hidden",
        "Id" => "EntityName",
        "Value" => $params->EntityName
        ));
        
        $contactForm->Add(array("Type" => "Hidden",
            "Id" => "EntityId",
            "Value" => $params->EntityId
        ));
       
        $contactForm->Add(array("Type" => "Hidden",
            "Id" => "DateStart",
            "Value" => $params->DateStart
        ));
        
        $contactForm->Add(array("Type" => "Hidden",
            "Id" => "HourStart",
            "Value" => $params->HourStart . ":00"
        ));
       
        $contactForm->Add(array("Type" => "TextBox",
            "Id" => "FirstName",
            "Validators" => ["Required"]
        ));
        
        $contactForm->Add(array("Type" => "TextBox",
            "Id" => "Name",
            "Validators" => ["Required"]
        ));
        
        $contactForm->Add(array("Type" => "EmailBox",
            "Id" => "Email",
            "Validators" => ["Required"]
        ));

        $contactForm->Add(array("Type" => "TelBox",
            "Id" => "Tel",
            "Validators" => ["Required"]
        ));
        
        $contactForm->Add(array("Type" => "Button",
            "Id" => "btnSendBookingForm",
            "Value" => $this->Core->GetCode("BookingPlugin.SendReservation"),
            "CssClass" => "btn btn-primary"
        ));

        return $contactForm->Render();
    }
}

?>
