<?php

class TimeScheduleController extends Controller
{

  /**
   *
   * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
   *      using two-column layout. See 'protected/views/layouts/column2.php'.
   */
  public $layout = '//layouts/column2';

  /**
   *
   * @return array action filters
   */
  public function filters()
  {
  }

  public function actions()
  {
    return array (
        'getRowForm' => array (
            'class' => 'ext.dynamictabularform.actions.GetRowForm',
            'view' => '_timeSlotForm',
            'modelClass' => 'TimeSlot' 
        ) 
    );
  }
  
  // test
  public function actionCreateSmart()
  {
    $action = array_get ( $_REQUEST, 'action' );
    
    if (isEmptyOrWhitespace ( $action ))
    {
      $this->render ( 'createsmart/prepare', get_defined_vars () );
    }
    elseif ($action == "picker")
    {
      $granularity = array_get ( $_REQUEST, 'granularity', 'hour' );
      $interval = array_get ( $_REQUEST, 'interval', 'week' );
      
      $rows = array ();
      $cols = array ();
      
      if ($granularity == 'hour' && $interval == 'week')
      {
        $cols = rangek ( 1, 24 );
        $rows = DateHelper::weekdayList ( false, true );
      }
      else if ($granularity == 'day' && $interval == 'week')
      {
        $cols = DateHelper::weekdayList ( false, true );
        $rows = array (
            1 => 'Week' 
        );
      }
      else if ($granularity == 'hour' && $interval == 'day')
      {
        $cols = rangek ( 1, 24 );
        $rows = array (
            1 => 'Everyday' 
        );
      }
      else
      {
        throw new CHttpException ( '500', "NOT YET IMPLEMENTED" );
      }
      
      $hiddenData = array ();
      $hiddenData ['action'] = 'doit';
      $hiddenData ['granularity'] = $granularity; // month day hour minute
      $hiddenData ['interval'] = $interval; // year month week day hour
      
      $this->render ( 'createsmart/picker', get_defined_vars () );
    }
    elseif ($action == "doit")
    {
      // crea
      logObj ( $_REQUEST );
      // $this->render ( 'createsmart/prepare', get_defined_vars () );
      $this->redirectToSelf ();
    }
    else
    {
      throw new CHttpException ( 500 );
    }
  }

  /**
   * Displays a particular model.
   *
   * @param integer $id
   *          the ID of the model to be displayed
   */
  public function actionView($id)
  {
    $this->render ( 'view', array (
        'model' => $this->loadModel ( $id ) 
    ) );
  }

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $returnUrl = array_get ( $_REQUEST, 'returnUrl' );
    
    $model = new TimeSchedule ();
    $timeSlots = array (
        new TimeSlot () 
    );
    
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    
    if (isset ( $_POST ['TimeSchedule'] ))
    {
      $model->attributes = $_POST ['TimeSchedule'];
      
      /**
       * creating an array of TimeSlot objects
       */
      if (isset ( $_POST ['TimeSlot'] ))
      {
        $timeSlots = array ();
        foreach ( $_POST ['TimeSlot'] as $key => $value )
        {
          /*
           * sladetail needs a scenario wherein the fk sla_id
           * is not required because the ID can only be
           * linked after the sla has been saved
           */
          $timeSlot = new TimeSlot ( 'batchSave' );
          $timeSlot->attributes = $value;
          $timeSlots [] = $timeSlot;
        }
      }
      
      /**
       * validating the sla and array of sladetail
       */
      $valid = $model->validate ();
      
      if (count ( $timeSlots ) <= 0 || ! isset ( $timeSlots [0]->updateType ))
      {
        // $valid = false;
        // var_dump($timeSlots);
      }
      
      foreach ( $timeSlots as $timeSlot )
      {
        $valid = $timeSlot->validate () & $valid;
      }
      
      if ($valid)
      {
        if ($model->save ())
        {
          try
          {
            $model->refresh ();
            
            foreach ( $timeSlots as $timeSlot )
            {
              $timeSlot->TimeID = $model->ID;
              $timeSlot->save ();
            }
          }
          catch ( Exception $e )
          {
            $model->delete ();
          }
        }
        
        if (isEmpty ( $returnUrl ))
          $this->redirect ( array (
              'index',
              'id' => $model->ID 
          ) );
        else
          $this->redirect ( $returnUrl );
        return;
      }
    }
    else
    {
      // la stiamo creando
      foreach ( $_REQUEST as $rk => $rv )
        if ($model->hasAttribute ( $rk ))
          $model->$rk = $rv;
    }
    
    $this->render ( 'create', array (
        'model' => $model,
        'timeSlots' => $timeSlots 
    ) );
  }

  public function actionSwitchParam($id, $param)
  {
    $model = $this->loadModel ( $id );
    $model->$param = $model->$param ? 0 : 1;
    $model->save ();
    $this->redirectTo ( 'timeSchedule' );
  }

  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   *
   * @param integer $id
   *          the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    $model = $this->loadModel ( $id );
    $timeSlots = $model->timeSlots;
    
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    
    if (isset ( $_POST ['TimeSchedule'] ))
    {
      $model->attributes = $_POST ['TimeSchedule'];
      
      if (isset ( $_POST ['TimeSlot'] ))
      {
        $timeSlots = array ();
        foreach ( $_POST ['TimeSlot'] as $key => $value )
        {
          /**
           * here we will take advantage of the updateType attribute so
           * that we will be able to determine what we want to do
           * to a specific row
           */
          
          if ($value ['updateType'] == DynamicTabularForm::UPDATE_TYPE_CREATE)
            $timeSlots [$key] = new TimeSlot ();
          
          else if ($value ['updateType'] == DynamicTabularForm::UPDATE_TYPE_UPDATE)
            $timeSlots [$key] = TimeSlot::model ()->findByPk ( $value ['ID'] );
          
          else if ($value ['updateType'] == DynamicTabularForm::UPDATE_TYPE_DELETE)
          {
            $delete = TimeSlot::model ()->findByPk ( $value ['ID'] );
            if ($delete->delete ())
            {
              unset ( $timeSlots [$key] );
              continue;
            }
          }
          
          $timeSlots [$key]->attributes = $value;
        }
        
        $valid = $model->validate ();
        
        if (count ( $timeSlots ) <= 0 || ! isset ( $timeSlots [0]->updateType ))
        {
          // $valid = false;
          // var_dump($timeSlots);
        }
        

        
        foreach ( $timeSlots as $timeSlot )
        {
          $valid = $timeSlot->validate () & $valid;
          
        }
        
        if ($valid)
        {
          if ($model->save ())
          {
            $model->refresh ();
            
            foreach ( $timeSlots as $timeSlot )
            {
              $timeSlot->TimeID = $model->ID;
              $timeSlot->save ();
            }
          }
          
          $this->redirect ( array (
              'index',
              'id' => $model->ID 
          ) );
        }
      }
    }

    $this->render ( 'update', array (
        'model' => $model,
        'timeSlots' => $timeSlots 
    ) );
  }

  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   *
   * @param integer $id
   *          the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    // if(Yii::app()->request->isPostRequest)
    {
      // we only allow deletion via POST request
      $this->loadModel ( $id )
        ->delete ();
      
      // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
      if (! isset ( $_GET ['ajax'] ))
        $this->redirect ( isset ( $_POST ['returnUrl'] ) ? $_POST ['returnUrl'] : array (
            'index' 
        ) );
    }
    // else
    // throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
  }

  /**
   * Lists all models.
   */
  public function actionIndex()
  {
    $dataProvider = new CActiveDataProvider ( 'TimeSchedule' );
    $dataProvider->pagination = false;
    $this->render ( 'index', array (
        'dataProvider' => $dataProvider 
    ) );
  }

  /**
   * Manages all models.
   */
  public function actionAdmin()
  {
    $this->redirectTo ( 'TimeSchedule/index' );
  }

  /**
   * 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 ID of the model to be loaded
   * @return TimeSchedule
   */
  public function loadModel($id)
  {
    $model = TimeSchedule::model ()->findByPk ( $id );
    if ($model === null)
      throw new CHttpException ( 404, 'The requested page does not exist.' );
    return $model;
  }

  /**
   * Performs the AJAX validation.
   *
   * @param
   *          CModel the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if (isset ( $_POST ['ajax'] ) && $_POST ['ajax'] === 'time-schedule-form')
    {
      echo CActiveForm::validate ( $model );
      Yii::app ()->end ();
    }
  }
}
