<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "clientes".
 *
 * @property string $id
 * @property string $nombre
 * @property string $apellidop
 * @property string $apellidom
 * @property string $telefono
 * @property string $dnref
 * @property string $email
 * @property string $created
 * @property string $modified
 * @property string $created_by
 * @property string $modified_by
 *
 * @property User $createdBy
 */
class Clientes extends \yii\db\ActiveRecord {

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['nombre', 'apellidop', 'apellidom'], 'required'],
            [['nombre', 'apellidop', 'apellidom'],'filter', 'filter'=>'strtoupper'],
            [['created', 'modified'], 'safe'],
            [['created_by', 'modified_by'], 'integer'],
            [['nombre', 'apellidop', 'apellidom', 'telefono', 'dnref', 'email'], 'string', 'max' => 255],
                // [['created_by'], 'exist', 'skipOnError' => true, 'targetClass' => \common\models\User::className(), 'targetAttribute' => ['created_by' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'nombre' => 'Nombre',
            'apellidop' => 'Apellido Paterno',
            'apellidom' => 'Apellido Materno',
            'telefono' => 'Telefono',
            'dnref' => 'Tel. Adicional',
            'email' => 'Email',
            'created' => 'Fecha creación',
            'modified' => 'Fecha modificación',
            'created_by' => 'Creado por',
            'modified_by' => 'Modificado por',
        ];
    }

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

    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;
    }

}
