<?php

class PaySlip extends CComponent
{
  private $events;
  private $groupedEvents;

  public function __construct($session)
  {
    $this->events =  Event::model()
      ->byExaminer($session->user)
      ->examinedBetween($session->login_at, $session->last_action_at)
      ->with('service')
      ->findAll();

    $this->groupedEvents = $this->groupByService($this->events);
  }
  
  static public function numOfEventsManaged($session)
  {
  	$numOfEvents =  Event::model()
  	->byExaminer($session->user)
  	->examinedBetween($session->login_at, $session->last_action_at)
  	->howMany();
  
  	return $numOfEvents;
  }

  public function getServices()
  {
    $services = array_map(function($group) { return $group['service']; }, $this->groupedEvents);
    uasort($services, function($a, $b) {
      if ($a->ID == $b->ID)
        return 0;
      return ($a->ID < $b->ID) ? -1 : 1;
    }
    );
    return $services;
  }

  public function getEventsCount()
  {
    return count($this->events);
  }

  public function getFirstEvent()
  {
    if (isset($this->events) && count($this->events)>0)
      return $this->events[0];
  }

  public function getLastEvent()
  {
    if (isset($this->events) && count($this->events)>0)
      return $this->events[count($this->events)-1];
  }

  public function getEventsByService($service)
  {
    foreach ($this->groupedEvents as $group) {
      $groupService = $group['service'];
      if ($groupService->ID == $service->ID)
        return $group['events'];
    }
  }

  private function groupByService($events)
  {
    $grouped = array();
    foreach($events as $event)
    {
      $service = $event->service;
      $grouped[$service->ID]['service'] = $service;
      $grouped[$service->ID]['events'][] = $event;
    }
    return $grouped;
  }

}
