<?php

class ZtlController extends Controller
{
  protected function beforeAction($event)
  {
    access_denied_check("ztl_view");
    return parent::beforeAction($event);
  }
   
  public function actionIndex()
  {
    $this->render('index');
  }

  /**
   * Displays Gate details
   * @param integer $id the ID of the model to be displayed
   */
  public function actionGateSchedule($gate, $year=null, $month=null, $day=null)
  {
    set_time_limit(0);

    $gateObj = $this->loadModelByGate($gate);

    $now=new DateTimeEx();

    if($month == null)
      $month = $now->month;
     
    if($year == null)
      $year = $now->year;
     
    $prev_month_url = "";
    $prev_month_text = "";
    $next_month_url = "";
    $next_month_text = "";

    $days = array();
    $hours = array();
    
    if($day == null)
    {
      $selectedMonthEx = new DateTimeEx();
       
      $selectedMonthEx->year = $year;
      $selectedMonthEx->month = $month;
      $selectedMonthEx->day = 15;
      $selectedMonthEx->hour = 0;
      $selectedMonthEx->minute = 0;
      $selectedMonthEx->second = 0;
       
      $prevMonthEx = clone $selectedMonthEx;
      $prevMonthEx->decMonth();
      $prev_month_url = "?gate=$gate&year=$prevMonthEx->year&month=$prevMonthEx->month";
      $prev_month_text = ucwords(DateHelper::getMonthName($prevMonthEx->month))." $prevMonthEx->year";
       
      $nextMonthEx = clone $selectedMonthEx;
      $nextMonthEx->incMonth();
      $next_month_url = "?gate=$gate&year=$nextMonthEx->year&month=$nextMonthEx->month";
      $next_month_text = ucwords(DateHelper::getMonthName($nextMonthEx->month))." $nextMonthEx->year";
       
      // month
      $daysCount = cal_days_in_month(CAL_GREGORIAN, $month, $year);
      for($i=1;$i<=$daysCount;$i++)
      {
        $dayObj=new DateTimeEx();
         
        $dayObj->hour = 12;
        $dayObj->minute = 30;
        $dayObj->second = 30;
        $dayObj->year = $year;
        $dayObj->month = $month;
        $dayObj->day = $i;
        
        //$validZtls = array();
        //$limited = $gateObj->isZtlLimitedEx($dayObj->toDateTime(),$validZtls);

        $cell = new CArray();
         
        $cell->isDay = true;
        //$cell->limited = $limited;
        $cell->date = $dayObj->toDateTime();
        $cell->dateex = new DateTimeEx($cell->date);
        $cell->day = intval($cell->dateex->day);
        $cell->dayOfWeek = intval($cell->date->format('w'));
        $cell->validZtls = $validZtls;
        $cell->fascePermessi = CommonHelper::getTimeSchedulesOfGateForDay($gateObj->ID, $dayObj);

        switch($cell->dayOfWeek)
        {
          /* dom */ case 0: $cell->dayOfWeekIta = 7; break;
          /* lun */ case 1: $cell->dayOfWeekIta = 1; break;
          /* mar */ case 2: $cell->dayOfWeekIta = 2; break;
          /* mer */ case 3: $cell->dayOfWeekIta = 3; break;
          /* gio */ case 4: $cell->dayOfWeekIta = 4; break;
          /* ven */ case 5: $cell->dayOfWeekIta = 5; break;
          /* sab */ case 6: $cell->dayOfWeekIta = 6; break;
        }
        $cell->dayOfWeekString = $cell->date->format('D');
        $cell->color = 'white';
        $cell->fontcolor = $cell->limited ? 'red' : 'green';
        $cell->text = "".$cell->dateex->day; // ." - ".($limited ? t('Limited') : t('Free'));

        $days[] = $cell;
      }
       
      $firstDay = $days[0];
      $fillHead = $firstDay->dayOfWeekIta;
      $firstDays = array();
      for($j=1;$j<$fillHead;$j++)
      {
        $cell = new CArray();
        $cell->isDay = false;
        $cell->color = 'white';
        $cell->fontcolor = 'black';
        $cell->text = '';
        $firstDays[] = $cell;
      }
       
      $days = array_merge($firstDays, $days);

      $headersDays = array();
      for($j=1;$j<=7;$j++)
      {
        $cell = new CArray();
        $cell->isDay = false;
        $cell->color = 'white';
        $cell->fontcolor = 'blue';
        $cell->text = DateHelper::getDayName($j);
        $headersDays[] = $cell;
      }
       
      $days = array_merge($headersDays, $days);

      $fillTail = 7 - count($days) % 7;
      $lastDays = array();
      if($fillTail < 7)
      for($j=0;$j<$fillTail;$j++)
      {
        $cell = new CArray();
        $cell->isDay = false;
        $cell->color = 'white';
        $cell->fontcolor = 'black';
        $cell->text = '';
        $lastDays[] = $cell;
      }
       
      $days = array_merge($days, $lastDays);
    }
    else
    {
      // giorno
      $selectedDayEx = new DateTimeEx();

      $selectedDayEx->year = $year;
      $selectedDayEx->month = $month;
      $selectedDayEx->day = $day;
      $selectedDayEx->hour = 0;
      $selectedDayEx->minute = 0;
      $selectedDayEx->second = 0;
      
      $dayptr = clone $selectedDayEx;
      
      $fascePermessi = CommonHelper::getTimeSchedulesOfGateForDay($gateObj->ID, $dayptr);
       
      $last = null;
      for($h=0;$h<24;$h++)
      {
        $gap = 1;//3
        for($m=0;$m<60;$m+=$gap)
        {
          if($h == 23 && $m == 57)
            $gap = 1;
          
          $dayptr->hour = $h;
          $dayptr->minute = $m;

          $status = new CArray();
          $status->datetime = clone $dayptr;

          $validZtls = array();
          $status->limited = $gateObj->isZtlLimitedEx($dayptr->toDateTime(),$validZtls);
          $status->validZtls = $validZtls;
          $status->validZtlsCount = count($validZtls);
          $status->ztl = count ( $validZtls ) == 1 ? array_first($validZtls)->ztl : null;
          $status->ztl_first = count ( $validZtls ) > 0 ? array_first($validZtls)->ztl : null;
          $status->ztl_last  = count ( $validZtls ) > 0 ? array_last($validZtls)->ztl  : null;
          
          $status->exceptions = CommonHelper::getWinningTimeSchedules($fascePermessi, $dayptr->toDateTime()); 
          
          if($last==null || $last->limited!=$status->limited)
          {
            if($last!=null)
            {
              $fascia = new CArray();

              $fascia->inizia = $last;
              $fascia->finisce = $status;

              $hours[] = $fascia;
            }
            $last = $status;
          }
        }
      }
       
      if(count($hours)>0)
      {
        $final = $hours[count($hours)-1];
        if($final->finisce->datetime != $dayptr)
        {
          $status = new CArray();
          $status->datetime = clone $dayptr;
          $status->limited = $final->finisce->limited;
          $status->exceptions = $fascePermessi;
          
          $fascia = new CArray();
           
          $fascia->inizia = clone $final->finisce;
          $fascia->finisce = $status;
           
          $hours[] = $fascia;
        }
      }
      else
      {
        $status = new CArray();
        $status->datetime = (clone $selectedDayEx);
        
        $validZtls = array();
        $status->limited = $gateObj->isZtlLimitedEx($dayptr->toDateTime(),$validZtls);
        $status->validZtls = $validZtls;
        $status->validZtlsCount = count($validZtls);
        $status->ztl = count ( $validZtls ) == 1 ? array_first($validZtls)->ztl : null;
        $status->ztl_first = count ( $validZtls ) > 0 ? array_first($validZtls)->ztl : null;
        $status->ztl_last  = count ( $validZtls ) > 0 ? array_last($validZtls)->ztl  : null;
        $status->exceptions = $fascePermessi;
        
        $status2 = new CArray();
        $status2->datetime = (clone $selectedDayEx);
        $status2->datetime = $status2->datetime->setTime(23,59,59);
        $status2->limited = $status->limited;
        $status2->exceptions = $fascePermessi;
        
        $fascia = new CArray();

        $fascia->inizia = $status;
        $fascia->finisce = $status2;

        $hours[] = $fascia;
      }
    }
     
    $this->render('gateSchedule',array(
        'gate'=>$gateObj,
        'year'=>$year,
        'month'=>$month,
        'day'=>$day,
        'days'=>$days,
        'hours'=>$hours,
        'prev_month_url' => $prev_month_url,
        'prev_month_text' => $prev_month_text,
        'next_month_url' => $next_month_url,
        'next_month_text' => $next_month_text,
    ));
  }
   
  public function actionEdit($gate)
  {
    $gateObj = $this->loadModelByGate($gate);
  }

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer the Gate ID of the model to be loaded
   * @return Gate
   */
  public function loadModelByGate($gate)
  {
    $model=Gate::model()->find('Gate=:gt', array(':gt'=>$gate));
    if($model===null)
      throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }
}