<?php

/*
 * PuzzleApp
 * Webemyos
 * Jérôme Oliva
 * GNU Licence
 */

namespace Apps\Calendar\Helper;

use Apps\Calendar\Widget\CalendarEventUserForm\CalendarEventUserForm;
use Apps\Calendar\Entity\CalendarEvent;
use Apps\Calendar\Entity\CalendarEventUser;

use Apps\Calendar\Helper\EmailHelper;

class EventHelper {
    
    /***
     * User to a event
     */
    public static function AddEventUser($core, $data, $userId = ""){
        
        $event = new CalendarEvent($core);
        $event->GetById($data["EventId"]);
        
        if(!$event->IsDispo()){
            return $core->GetCode("Calendar.NotDispo");
        }
        
        if($event->EmailExist($data["Email"])){
            return $core->GetCode("Calendar.EmailExist");
        }
        
        $eventUserForm = new CalendarEventUserForm($core, $data);
        
        if($eventUserForm->Validate($data)){
            
            $eventUser = new CalendarEventUser($core);
            $eventUserForm->Populate($eventUser);
            
            if($core->IsConnected()){
                $eventUser->UserId->Value = $core->User->IdEntite;
            } else if($userId){
                $eventUser->UserId->Value = $userId;
            }
            
            $eventUser->Save();


            EmailHelper::SendEmail($this->Core, 
                "Calendar-saveRegistration", 
                $this->Core->User->Email->Value, 
                array("{{userName}}" => $this->Core->User->GetPseudo()
                ),
                $this->Core->GetCode("Calendar.EmailSaveRegistrationTitle"),
                $this->Core->GetCode("Base.EmailSaveRegistrationMessage"),
            );


            return true;
            
        } else {
            return $eventUserForm->Error();
        }
    }
    
    /***
     * Get all Events 
     */
    public static function GetEvents($core){
        $event = new CalendarEvent($core);
        $events = $event->Find("DateStart > Now() order by DateStart desc");
        
        return $event->ToAllArray($events);
    }
    
    /***
     * Get all Events 
     */
    public static function GetEvent($core, $eventId){

        $event = new CalendarEvent($core);
        $event->GetById($eventId);
        
        return $event->ToArray();
    }
}