<?php
namespace app\models;

use Yii;
use yii\db\ActiveRecord;

class Order extends ActiveRecord
{
    const STATUS_NEW = 'new';
    const STATUS_ACCEPTED = 'accepted';
    const STATUS_COMPLETED = 'completed';

    public static function tableName()
    {
        return 'order';
    }

    public function rules()
    {
        return [
            [['category_id', 'product_id', 'quantity', 'delivery_date', 'delivery_address', 'payment_method'], 'required'],
            [['quantity'], 'integer', 'min' => 1],
            [['delivery_date'], 'date', 'format' => 'php:Y-m-d'],
            [['delivery_address'], 'string', 'max' => 255],
            [['payment_method'], 'in', 'range' => ['cash', 'transfer']],
            [['comment'], 'string'],
            [['status'], 'in', 'range' => [self::STATUS_NEW, self::STATUS_ACCEPTED, self::STATUS_COMPLETED]],
        ];
    }

    public function attributeLabels()
    {
        return [
            'category_id' => 'Категория',
            'product_id' => 'Товар',
            'quantity' => 'Количество',
            'delivery_date' => 'Дата доставки',
            'delivery_address' => 'Адрес доставки',
            'payment_method' => 'Способ оплаты',
            'comment' => 'Пожелания по заказу',
            'status' => 'Статус',
        ];
    }

    public function getUser()
    {
        return $this->hasOne(User::class, ['id' => 'user_id']);
    }

    public function getCategory()
    {
        return $this->hasOne(Category::class, ['id' => 'category_id']);
    }

    public function getProduct()
    {
        return $this->hasOne(Product::class, ['id' => 'product_id']);
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($insert) {
                $this->user_id = Yii::$app->user->id;
            }
            return true;
        }
        return false;
    }
}