<?php

/**
 * This is the model class for table "vehicletable".
 *
 * The followings are the available columns in table 'vehicletable':
 * @property string $ID
 * @property string $Descrizione
 * @property string $Classe
 * @property string $Abilitato
 * @property string $AreaID
 * @property string $Targa
 * @property string $Nationality
 * @property string $NetworkID
 * @property string $UserID
 * @property string $ID1
 * @property string $ID2
 * @property string $ID3
 * @property string $ID4
 * @property string $ID5
 * @property string $epoch
 * @property string $source
 * @property integer $privacy_level
 * @property string $action
 * @property integer $list_code
 * @property string $type
 * @property string $category
 * @property string $note
 * @property PlateAuthorization[] plateAuths
 * @property integer plateAuthsCount
 */
class Vehicle extends ActiveRecord
{

  /**
   * Returns the static model of the specified AR class.
   *
   * @param string $className
   *          active record class name.
   * @return Vehicle the static model class
   */
  public static function model($className = __CLASS__)
  {
    return parent::model ( $className );
  }

  /**
   *
   * @return string the associated database table name
   */
  public function tableName()
  {
    return 'vehicletable';
  }

  /**
   *
   * @return array validation rules for model attributes.
   */
  public function rules()
  {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array (
        array (
            'Targa, Nationality, list_code',
            'required' 
        ),
        array (
            'privacy_level, list_code',
            'numerical',
            'integerOnly' => true 
        ),
        array (
            'Descrizione, Classe, Targa, Nationality',
            'length',
            'max' => 250 
        ),
        array (
            'Abilitato, AreaID, NetworkID, UserID, ID1, ID2, ID3, ID4, ID5',
            'length',
            'max' => 20 
        ),
        array (
            'source, type, category',
            'length',
            'max' => 255 
        ),
        array (
            'epoch, action, note',
            'safe' 
        ),
        array (
            'privacy_level',
            'default',
            'setOnEmpty' => true,
            'value' => 1 
        ),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array (
            'ID, Descrizione, Classe, Abilitato, AreaID, Targa, Nationality, NetworkID, UserID, ID1, ID2, ID3, ID4, ID5, epoch, source, privacy_level, action, list_code, type, category, note, listName',
            'safe',
            'on' => 'search' 
        ) 
    );
  }

  /**
   *
   * @return array relational rules.
   */
  public function relations()
  {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array (
        'plate_list' => array (
            self::BELONGS_TO,
            'PlateList',
            array (
                'list_code' => 'code' 
            ) 
        ),
        'plateAuths' => array (
            self::HAS_MANY,
            'PlateAuthorization',
            'VehicleID' 
        ),
        'plateAuthsCount' => array (
            self::STAT,
            'PlateAuthorization',
            'VehicleID' 
        ) 
    );
  }

  /**
   *
   * @return array customized attribute labels (name=>label)
   */
  public function myAttributeLabels()
  {
    return array (
        'ID' => 'ID',
        'Descrizione' => t ( 'Description' ),
        'Classe' => t ( 'Class' ),
        'Abilitato' => t ( 'Enabled' ),
        'AreaID' => t ( 'Area' ),
        'Targa' => t ( 'License plate' ),
        'Nationality' => t ( 'Nationality' ),
        'NetworkID' => t ( 'Network' ),
        'UserID' => t ( 'User' ),
        'ID1' => 'Id1',
        'ID2' => 'Id2',
        'ID3' => 'Id3',
        'ID4' => 'Id4',
        'ID5' => 'Id5',
        'epoch' => t ( 'Epoch' ),
        'source' => t ( 'Source' ),
        'privacy_level' => t ( 'Privacy Level' ),
        'action' => t ( 'Action' ),
        'list_code' => t ( 'List Code' ),
        'type' => t ( 'Type' ),
        'category' => t ( 'Category' ),
        'note' => t ( 'Note' ),
        'listName' => t ( 'List Name' ) 
    );
  }

  /**
   * Retrieves a list of models based on the current search/filter conditions.
   *
   * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
   */
  public function search()
  {
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.
    $criteria = new CDbCriteria ();
    
    $criteria->compare ( 'ID', $this->ID, true );
    $criteria->compare ( 'Descrizione', $this->Descrizione, true );
    $criteria->compare ( 'Classe', $this->Classe, true );
    $criteria->compare ( 'Abilitato', $this->Abilitato, true );
    $criteria->compare ( 'AreaID', $this->AreaID, true );
    $criteria->compare ( 'Targa', $this->Targa, true );
    $criteria->compare ( 'Nationality', $this->Nationality, true );
    $criteria->compare ( 'NetworkID', $this->NetworkID, true );
    $criteria->compare ( 'UserID', $this->UserID );
    $criteria->compare ( 'ID1', $this->ID1, true );
    $criteria->compare ( 'ID2', $this->ID2, true );
    $criteria->compare ( 'ID3', $this->ID3, true );
    $criteria->compare ( 'ID4', $this->ID4, true );
    $criteria->compare ( 'ID5', $this->ID5, true );
    $criteria->compare ( 'epoch', $this->epoch, true );
    $criteria->compare ( 'source', $this->source, true );
    $criteria->compare ( 'privacy_level', $this->privacy_level );
    $criteria->compare ( 'action', $this->action, true );
    $criteria->compare ( 'list_code', $this->list_code );
    $criteria->compare ( 'type', $this->type, true );
    $criteria->compare ( 'category', $this->category, true );
    $criteria->compare ( 'note', $this->note, true );
    
    return new CActiveDataProvider ( $this, array (
        'criteria' => $criteria 
    ) );
  }

  public function byDescription($what)
  {
    $this->getDbCriteria ()
      ->addCondition ( "(Descrizione LIKE '%$what%' OR Targa LIKE '%$what%')" );
    
    return $this;
  }

  private $_listName = null;

  public function getListName()
  {
    if ($this->_listName === null && $this->plate_list !== null)
    {
      $this->_listName = $this->plate_list->name;
    }
    return $this->_listName;
  }

  public function setListName($value)
  {
    $this->_listName = $value;
  }

  public function isListEditable()
  {
    if ($this->plate_list !== null)
    {
      return $this->plate_list->editable;
    }
    return false;
  }

  public function cercaPerLista()
  {
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.
    ini_set ( 'max_execution_time', 300 ); // 300 seconds = 5 minutes
    
    $criteria = new CDbCriteria ();
    
    $lista = null;
    $codice_liste = array ();
    $liste = PlateList::getAllLists ();
    foreach ( $liste as $l )
    {
      if ($this->listName != null)
      {
        // cerco lista filtro
        if ($lista == null)
        {
          if (strtoupper ( $l->name ) == strtoupper ( $this->listName ))
          {
            $lista = $l;
            break;
          }
        }
      }
      else
      {
        // salvo i codice di tutte le liste
        if ($l->visible)
          $codice_liste [] = $l->code;
      }
    }
    
    // $criteria->compare('Targa',$this->Targa,true);
    if ($this->Targa != null && is_string ( $this->Targa ) && $this->Targa != '')
      $criteria->addCondition ( "MATCH(Targa) AGAINST('*" . $this->Targa . "*' IN BOOLEAN MODE)" );
      // $criteria->addCondition("Targa LIKE '$this->Targa%'");
    
    if ($this->Nationality != null && is_string ( $this->Nationality ) && $this->Nationality != '')
      $criteria->compare ( 'Nationality', $this->Nationality );
    
    if ($lista != null)
      $criteria->compare ( 'list_code', $lista->code );
    else if (count ( $codice_liste ) > 0)
      $criteria->addInCondition ( 'list_code', $codice_liste );
      
      /*
     * $criteria->compare('list_code',202);
     *
     * $criteria->compare('plate_list.name',$this->listName);
     *
     * $criteria->addCondition('plate_list.visible=1');
     * $criteria->with = array('plate_list');
     * $criteria->together=true;
     */
      
    // solo chi ha effettivamente una segnalazione attiva valida
    $criteria->addCondition ( "
        (
        SELECT COUNT(*) FROM whitelisttable wlt 
        WHERE
        wlt.VehicleID=t.ID 
        AND EXISTS (SELECT 1 FROM usertable u WHERE u.id=wlt.userid)
        AND EXISTS (SELECT 1 FROM abbonamentotable a WHERE a.id=wlt.abbonamentoid)
    ) > 0" );
    
    return new CActiveDataProvider ( $this, array (
        'criteria' => $criteria 
    ) );
  }

  public static function getGategoryList($ids)
  {
    $catVehicle = Vehicle::model ()->findAllByPk ( $ids, array (
        'select' => 'category',
        'distinct' => true 
    ) );
    if (is_null ( $catVehicle ))
      return null;
    
    $arr = array ();
    if (! is_array ( $catVehicle ))
      $catVehicle = array (
          $catVehicle 
      );
    
    foreach ( $catVehicle as $cV )
      $arr [] = $cV->category;
    
    return $arr;
  }

  public function deleteByListCode($list_code)
  {
    Vehicle::model ()->deleteAllByAttributes ( array (
        'list_code' => $list_code 
    ) );
  }

  public static function getOrCreate($plate, $nationality, $userId, $list_code)
  {
    $vehicle = self::model()->find ( 'Targa=:plt AND Nationality=:nat AND UserID=:uid AND list_code=:lst', array (
        ':plt' => $plate,
        ':nat' => $nationality,
        ':uid' => $userId,
        ':lst' => $list_code 
    ) );
    if ($vehicle == null)
    {
      $vehicle = new Vehicle ();
      $vehicle->list_code = $list_code;
      $vehicle->UserID = $userId;
      $vehicle->Targa = $plate;
      $vehicle->Nationality = $nationality;
      $vehicle->insert ();
    }
    return $vehicle;
  }
}