<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%ad}}".
 *
 * @property string $id
 * @property integer $display
 * @property integer $categoryid
 * @property string $title
 * @property string $note
 * @property string $ordid
 * @property string $addtime
 * @property string $starttime
 * @property integer $deadline
 * @property string $img
 * @property string $url
 * @property string $explain
 */
class Ad extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%ad}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['img'], 'required','on'=>'create'],
            [['display', 'categoryid', 'ordid', 'addtime'], 'integer'],
            [['categoryid', 'title', 'starttime', 'url'], 'required'],
            [['title'], 'string', 'max' => 100],
            [['note'], 'string', 'max' => 230],
            [['img', 'url', 'explain'], 'string', 'max' => 255],
            [['deadline'],'safe'],
            [['categoryid'], 'exist', 'skipOnError' => true, 'targetClass' => AdCategory::className(), 'targetAttribute' => ['categoryid' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'display' => '显示/隐藏',
            'categoryid' => '广告位',
            'title' => '广告标题',
            'note' => '备注',
            'ordid' => '排序',
            'addtime' => '添加时间',
            'starttime' => '开始时间',
            'deadline' => '结束时间',
            'img' => '图片',
            'url' => '图片链接',
            'explain' => '图片文字说明',
        ];
    }
    public function beforeSave($insert)
    {
        $timestamp = time();
        if (parent::beforeSave($insert)) {
            if($this->starttime){
                $this->starttime = strtotime($this->starttime);
            }
            if($this->deadline){
                $this->deadline = strtotime($this->deadline);
            }else{
                $this->deadline = 0;
            }
            if($insert) {
                $this->addtime = $timestamp;
                $this->ordid = 0;
            }
            return true;
        } else {
            return false;
        }
    }
    public function afterFind(){
        $this->starttime = date('Y-m-d',$this->starttime);
        $this->deadline = $this->deadline?date('Y-m-d',$this->deadline):'';
        return true;
    }
    public function getCategory()
    {
        return $this->hasOne(AdCategory::className(), ['id' => 'categoryid']);
    }
}
