<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\behaviors\TimestampBehavior;
/**
 * This is the model class for table "m_voting".
 *
 * @property int $id_voting
 * @property string|null $nama_voting
 * @property string|null $periode_awal
 * @property string|null $periode_tutup
 *
 * @property HasilVoting[] $hasilVotings
 * @property TUser[] $users
 * @property TKandidat[] $tKandidats
 */
class MVoting extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'm_voting';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['periode_awal', 'periode_tutup','status_aktif','nama_voting'], 'required'],
            [['periode_awal', 'periode_tutup','created_at','updated_at'], 'safe'],
            [['status_aktif','created_by','updated_by'], 'integer'],
            [['nama_voting'], 'string', 'max' => 500],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id_voting' => 'Id Voting',
            'nama_voting' => 'Deskripsi',
            'periode_awal' => 'Tanggal Mulai Voting',
            'periode_tutup' => 'Tanggal Akhir Voting',
            'status_aktif' => 'Status Voting',
        ];
    }

    public function behaviors()
    {
       return [
           'timestamp' => [
               'class' => TimestampBehavior::className(),
               'attributes' => [
                   ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                   ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
               ],
               'value' => new Expression('NOW()'),
           ],

       ];
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }
        if(ActiveRecord::EVENT_BEFORE_INSERT){
            $this->created_by = Yii::$app->user->identity->id;
            $this->updated_by = Yii::$app->user->identity->id;
        }else if(ActiveRecord::EVENT_BEFORE_UPDATE){
            $this->updated_by = Yii::$app->user->identity->id;
        }

        return true;
    }

    /**
     * Gets query for [[HasilVotings]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getHasilVotings()
    {
        return $this->hasMany(HasilVoting::className(), ['id_voting' => 'id_voting']);
    }

    /**
     * Gets query for [[Users]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getUsers()
    {
        return $this->hasMany(TUser::className(), ['id' => 'id_user'])->viaTable('hasil_voting', ['id_voting' => 'id_voting']);
    }

    /**
     * Gets query for [[TKandidats]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getTKandidats()
    {
        return $this->hasMany(TKandidat::className(), ['id_voting' => 'id_voting']);
    }
}
