<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "pdv".
 *
 * @property string $id
 * @property string $idpdv
 * @property string $nombre
 * @property string $proyecto
 * @property string $created
 * @property string $modified
 * @property integer $created_by
 * @property integer $modified_by
 *
 * @property User[] $users
 */
class Pdv extends \yii\db\ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'pdv';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['created', 'modified'], 'safe'],
            [['created_by', 'modified_by'], 'integer'],
            [['idpdv', 'nombre', 'proyecto'], 'string', 'max' => 45],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'idpdv' => 'ID PDV',
            'nombre' => 'Nombre',
            'proyecto' => 'Proyecto',
            'created' => 'Fecha creación',
            'modified' => 'Fecha modificación',
            'created_by' => 'Creado por',
            'modified_by' => 'Modificado por',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUsers() {
        return $this->hasMany(\common\models\User::className(), ['pdv_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCreatedBy() {
        return $this->hasOne(\common\models\User::className(), ['id' => 'created_by']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getModifiedBy() {
        return $this->hasOne(\common\models\User::className(), ['id' => 'modified_by']);
    }

    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->created = date_create()->format('Y-m-d H:i:s');
                $this->modified = date_create()->format('Y-m-d H:i:s');
                $this->created_by = Yii::$app->user->identity->id;
                $this->modified_by = Yii::$app->user->identity->id;
            } else {
                $this->modified = date_create()->format('Y-m-d H:i:s');
                $this->modified_by = Yii::$app->user->identity->id;
            }
            return true;
        }
        return false;
    }

}
