<?php

namespace common\models;

use common\behaviors\SaveImgBehavior;
use Yii;

/**
 * This is the model class for table "slider_image".
 *
 * @property integer $slider_image_id
 * @property integer $slider_id
 * @property string $image
 * @property string $alt
 * @property string $title
 * @property string $url
 * @property integer $status
 * @property integer $sort
 * @property integer $end_at
 *
 * @property Slider $slider
 */
class SliderImage extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'slider_image';
    }


    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            [
                'class'     => SaveImgBehavior::className(),
                'fields' => [
                    ['name'=>'image','directory' => 'slider' ]
                ]
            ]
        ];
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['slider_id', 'status', 'sort'], 'integer'],
            [['image', 'alt', 'title', 'url','end_at'], 'string', 'max' => 255],
            [['slider_id'], 'exist', 'skipOnError' => true, 'targetClass' => Slider::className(), 'targetAttribute' => ['slider_id' => 'slider_id']],
        ];
    }


    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {

            $this->end_at = !empty($this->end_at) ? strtotime($this->end_at) : '';
            return true;
        } else {
            return false;
        }
    }

    public function afterFind(){
        $this->end_at = !empty($this->end_at) ? date("Y-m-d", $this->end_at) : '';
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'slider_image_id' => Yii::t('app', 'slider_image_id'),
            'slider_id' => Yii::t('app', 'slider_id'),
            'image' => Yii::t('app', 'image'),
            'alt' => Yii::t('app', 'alt'),
            'title' => Yii::t('app', 'title'),
            'url' => Yii::t('app', 'url'),
            'status' => Yii::t('app', 'status'),
            'sort' => Yii::t('app', 'sort'),
        ];
    }
    public function isActive(){
        if($this->status){

            if(!empty($this->end_at) && (strtotime($this->end_at) <= strtotime(date("Y-m-d")))){
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSlider()
    {
        return $this->hasOne(Slider::className(), ['slider_id' => 'slider_id']);
    }


}
