<?php

class PlateAuthInsertProfileController 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';

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

  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    access_denied_check ( 'plateauthinsertprofile_create' );
    $model = new PlateAuthInsertProfile ();
    
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    
    if (isset ( $_POST ['PlateAuthInsertProfile'] ))
    {
      $model->attributes = $_POST ['PlateAuthInsertProfile'];
      if ($model->save ())
      {
        $fields = $this->getRequestFields ( $model->id );
        foreach ( $fields as $f )
          $f->save ();
        $this->redirect ( array (
            'view',
            'id' => $model->id 
        ) );
      }
    }
    else
    {
      $fields = $this->getDefaultFields ();
    }
    $this->render ( 'create', get_defined_vars () );
  }

  /**
   * 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)
  {
    access_denied_check ( 'plateauthinsertprofile_update' );
    $model = $this->loadModel ( $id );
    
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    
    if (isset ( $_POST ['PlateAuthInsertProfile'] ))
    {
      $fields = $this->getRequestFields ( $model->id );
      $model->attributes = $_POST ['PlateAuthInsertProfile'];
      if ($model->save ())
      {
        foreach ( $model->fields as $f )
          $f->delete ();
        foreach ( $fields as $f )
          $f->save ();
        $this->redirect ( array (
            'view',
            'id' => $model->id 
        ) );
      }
    }
    else
    {
      $fields = $model->fields;
    }
    
    $this->render ( 'update', get_defined_vars () );
  }

  /**
   * 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)
  {
    access_denied_check ( 'plateauthinsertprofile_delete' );
    if (Yii::app ()->request->isPostRequest)
    {
      // we only allow deletion via POST request
      $model = $this->loadModel ( $id );
      foreach ( $model->fields as $f )
        $f->delete ();
      $model->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 (
            'admin' 
        ) );
    }
    else
      throw new CHttpException ( 400, 'Invalid request. Please do not repeat this request again.' );
  }

  /**
   * Lists all models.
   */
  public function actionIndex()
  {
    $this->redirectTo ( 'PlateAuthInsertProfile/admin' );
  }

  /**
   * Manages all models.
   */
  public function actionAdmin()
  {
    access_denied_check ( 'plateauthinsertprofile_management' );
    $model = new PlateAuthInsertProfile ( 'search' );
    $model->unsetAttributes (); // clear any default values
    if (isset ( $_GET ['PlateAuthInsertProfile'] ))
      $model->attributes = $_GET ['PlateAuthInsertProfile'];
    
    $this->render ( 'admin', array (
        'model' => $model 
    ) );
  }

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

  public function actionClone($id)
  {
    access_denied_check ( 'plateauthinsertprofile_clone' );
    $model = $this->loadModel ( $id );
    $modelAttrs = $model->attributes;
    unset($modelAttrs['id']);
       
    $newModel = new PlateAuthInsertProfile();
    $newModel->setAttributes($modelAttrs, false);
    $newModel->insert();
    
    foreach($model->fields as $field)
    {
      $fieldAttrs = $field->attributes;
      unset($fieldAttrs['id']);
      $fieldAttrs['profile'] = $newModel->id;
       
      $newModelField = new PlateAuthInsertProfileField();
      $newModelField->setAttributes($fieldAttrs, false);
      $newModelField->insert();      
    }
    
    $this->redirectTo('plateauthinsertprofile');
  }

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

  /**
   *
   * @return PlateAuthInsertProfileField[]
   */
  protected function getDefaultFields()
  {
    $fields = array ();
    $order = 0;
    
    // veicolo, targa
    $field = new PlateAuthInsertProfileField ();
    $field->group = "vehicle";
    $field->name = "vehicle_plate";
    $field->label = "Plates";
    $field->description = "List of plates separated by spaces or commas";
    $field->type = PlateAuthInsertProfileFieldType::MULTILINESTRING;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // veicolo, modello
    $field = new PlateAuthInsertProfileField ();
    $field->group = "vehicle";
    $field->name = "vehicle_model";
    $field->label = "Model";
    $field->description = "Model of the vehicle";
    $field->type = PlateAuthInsertProfileFieldType::STRING;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // veicolo, nazionalità
    $field = new PlateAuthInsertProfileField ();
    $field->group = "vehicle";
    $field->name = "vehicle_nationality";
    $field->label = "Nationality";
    $field->description = "Nationality";
    $field->type = PlateAuthInsertProfileFieldType::DROPDOWN;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->default = "CountryList::getGuiLang()";
    $field->values = "array_merge(array('' => ''), CountryList::localized())";
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // veicolo, tipo
    $field = new PlateAuthInsertProfileField ();
    $field->group = "vehicle";
    $field->name = "vehicle_type";
    $field->label = "Type";
    $field->description = "Type";
    $field->type = PlateAuthInsertProfileFieldType::DROPDOWN;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = "array_merge(array('' => ''), VehicleTypes::localized())";
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // owner name
    $field = new PlateAuthInsertProfileField ();
    $field->group = "owner";
    $field->name = "owner_name";
    $field->label = "Name";
    $field->description = "Name of the owner";
    $field->type = PlateAuthInsertProfileFieldType::STRING;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // owner surname
    $field = new PlateAuthInsertProfileField ();
    $field->group = "owner";
    $field->name = "owner_surname";
    $field->label = "Surname";
    $field->description = "Surname of the owner";
    $field->type = PlateAuthInsertProfileFieldType::STRING;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // owner email
    $field = new PlateAuthInsertProfileField ();
    $field->group = "owner";
    $field->name = "owner_email";
    $field->label = "Email";
    $field->description = "Email of the owner";
    $field->type = PlateAuthInsertProfileFieldType::STRING;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // owner phone
    $field = new PlateAuthInsertProfileField ();
    $field->group = "owner";
    $field->name = "owner_phone";
    $field->label = "Phone";
    $field->description = "Phone number of the owner";
    $field->type = PlateAuthInsertProfileFieldType::STRING;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // owner address
    $field = new PlateAuthInsertProfileField ();
    $field->group = "owner";
    $field->name = "owner_address";
    $field->label = "Address";
    $field->description = "Address of the owner";
    $field->type = PlateAuthInsertProfileFieldType::STRING;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // owner city
    $field = new PlateAuthInsertProfileField ();
    $field->group = "owner";
    $field->name = "owner_city";
    $field->label = "City";
    $field->description = "City of the owner";
    $field->type = PlateAuthInsertProfileFieldType::STRING;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // owner overwrite
    $field = new PlateAuthInsertProfileField ();
    $field->group = "owner";
    $field->name = "owner_overwrite";
    $field->label = "Overwrite";
    $field->description = "Overwrite of the owner";
    $field->type = PlateAuthInsertProfileFieldType::CHECKBOX;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = 1;
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // auth type
    $field = new PlateAuthInsertProfileField ();
    $field->group = "plate authorization";
    $field->name = "plateauth_type";
    $field->label = "Type";
    $field->description = "Type of plate authorization";
    $field->type = PlateAuthInsertProfileFieldType::DROPDOWN;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->default = "paramdeep('plateAuthorizations','default','plateAuthType')";
    $field->values = "paramdeep('plateAuthorizations','types')";
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // auth filterGate
    $field = new PlateAuthInsertProfileField ();
    $field->group = "plate authorization";
    $field->name = "plateauth_gate";
    $field->label = "Gate";
    $field->description = "Gate of plate authorization";
    $field->type = PlateAuthInsertProfileFieldType::DROPDOWN;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->default = "paramdeep('plateAuthorizations','default','gate')";
    $field->values = "array('-1' => t('Every gate')) + PlateAuthorizationController::getGateObjects()";
    $field->order = $order ++;
    $field->comment = null;
    $fields [$field->name] = $field;
    
    // auth filterTime
    $field = new PlateAuthInsertProfileField ();
    $field->group = "plate authorization";
    $field->name = "plateauth_time";
    $field->label = "Time Schedule";
    $field->description = "Time Schedule of plate authorization";
    $field->type = PlateAuthInsertProfileFieldType::DROPDOWN;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->default = "paramdeep('plateAuthorizations','default','time')";
    $field->values = "array('-1' => t('Always')) + TimeSchedule::getTimeScheduleArrayForPlateAuths()";
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 0;
    $fields [$field->name] = $field;
    
    // validity buttons
    $field = new PlateAuthInsertProfileField ();
    $field->group = "validity";
    $field->name = "validity_buttons";
    $field->label = "";
    $field->description = "";
    $field->type = PlateAuthInsertProfileFieldType::DATEBUTTONS;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->default = null;
    $field->values = "PlateAuthorizationController::getCustomValidityPeriods()";
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 1;
    $fields [$field->name] = $field;
    
    // validity startDate
    $field = new PlateAuthInsertProfileField ();
    $field->group = "validity";
    $field->name = "validity_startDate";
    $field->label = "Start date";
    $field->description = "Start date of validity period";
    $field->type = PlateAuthInsertProfileFieldType::DATE;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->default = "DateTimeEx::nows('d/m/Y')";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 1;
    $fields [$field->name] = $field;
    
    // validity startTime
    $field = new PlateAuthInsertProfileField ();
    $field->group = "validity";
    $field->name = "validity_startTime";
    $field->label = "Start time";
    $field->description = "Start time of validity period";
    $field->type = PlateAuthInsertProfileFieldType::TIME;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "00:00";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 1;
    $fields [$field->name] = $field;
    
    // validity startDate
    $field = new PlateAuthInsertProfileField ();
    $field->group = "validity";
    $field->name = "validity_endDate";
    $field->label = "End date";
    $field->description = "End date of validity period";
    $field->type = PlateAuthInsertProfileFieldType::DATE;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->default = "DateTimeEx::nows('d/m/Y')";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 1;
    $fields [$field->name] = $field;
    
    // validity endTime
    $field = new PlateAuthInsertProfileField ();
    $field->group = "validity";
    $field->name = "validity_endTime";
    $field->label = "End time";
    $field->description = "End time of validity period";
    $field->type = PlateAuthInsertProfileFieldType::TIME;
    $field->required = true;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "23:59";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 1;
    $fields [$field->name] = $field;
    
    // other source
    $field = new PlateAuthInsertProfileField ();
    $field->group = "other";
    $field->name = "other_source";
    $field->label = "Source";
    $field->description = "Source";
    $field->type = PlateAuthInsertProfileFieldType::DROPDOWN;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->default = "paramdeep('plateAuthorizations','default','vehicleSource')";
    $field->values = "paramdeep('plateAuthorizations','vehicleSources')";
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 1;
    $fields [$field->name] = $field;
    
    // other action
    $field = new PlateAuthInsertProfileField ();
    $field->group = "other";
    $field->name = "other_action";
    $field->label = "Action";
    $field->description = "Action";
    $field->type = PlateAuthInsertProfileFieldType::STRING;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 1;
    $fields [$field->name] = $field;
    
    // other note
    $field = new PlateAuthInsertProfileField ();
    $field->group = "other";
    $field->name = "other_note";
    $field->label = "Note";
    $field->description = "Note";
    $field->type = PlateAuthInsertProfileFieldType::MULTILINESTRING;
    $field->required = false;
    $field->visible = true;
    $field->editable = true;
    $field->defaultVar = "";
    $field->values = null;
    $field->order = $order ++;
    $field->comment = null;
    $field->column = 1;
    $fields [$field->name] = $field;
    
    PlateAuthInsertProfileField::sort ( $fields );
    
    return $fields;
  }

  /**
   *
   * @param int $profileId          
   * @return PlateAuthInsertProfileField[]
   */
  protected function getRequestFields($profileId)
  {
    $fields = array ();
    foreach ( $_REQUEST as $key => $value )
    {
      $fieldName = startsWithGet ( $key, "fielddata_" );
      if (! isEmpty ( $fieldName ))
      {
        // logLine("crea $fieldName");
        $f = new PlateAuthInsertProfileField ();
        // logLine("fillo $fieldName");
        $f->setAttributes ( $value, false );
        // logLine("imposto $fieldName");
        $f->profile = $profileId;
        $f->epoch = DateTimeEx::nows ();
        
        $requiredFields = array (
            'group',
            'name',
            'label',
            'description',
            'type',
            'required',
            'visible',
            'editable' 
        );
        if ($f->group == null)
          $f->group = "unknown";
        if ($f->label == null)
          $f->label = $fieldName;
        if ($f->description == null)
          $f->description = $fieldName;
        if ($f->type == null)
          $f->type = PlateAuthInsertProfileFieldType::STRING;
        if ($f->required == null)
          $f->required = 0;
        if ($f->visible == null)
          $f->visible = 0;
        if ($f->editable == null)
          $f->editable = 0;
        
        $fields [$fieldName] = $f;
      }
    }
    
    PlateAuthInsertProfileField::sort ( $fields );
    
    return $fields;
  }
}
