<?php

namespace Modules\Project\Entities;

use Illuminate\Database\Eloquent\Model;
use Modules\Project\Services\Counpon\UseCouponInterface;

class Coupon extends Model
{
    protected $fillable = [];

    protected $casts = [
        'config' => 'array',
        'start' => 'datetime',
        'end' => 'datetime',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function users()
    {
        return $this->hasMany(UserCoupon::class);
    }

    /**
     * 用户是否领取过优惠券
     *
     * @param int $user_id
     *
     * @return bool
     */
    public function isCollected($user_id = 0)
    {
        return ($user_id && is_numeric($user_id)) ?
            ($this->users()->where('user_id', $user_id)->count() > 0 ? true : false)
            : false;
    }

    /**
     *
     */
    public static function boot()
    {
        parent::boot();
        static::deleting(function ($model) {
            if ($model->users()->count()) {
                throw new \Exception('已领取过的优惠券不能再删除');
            }
        });
    }

    /**
     * 优惠券列表
     *
     * @return mixed
     */
    public function list()
    {
        return $this->with('users')->where('disabled', 0)->where(function ($query){
            $query->whereNull('end')->orWhere('end', '>=', date("Y-m-d H:i:s"));
        })->get();
        /*
        return $this->where('disabled', 0)->where(function ($query) {
            $query->whereNull('start')->orWhere('start', '>=', date("Y-m-d H:i:s"));
        })->where(function ($query){
            $query->whereNull('end')->orWhere('end', '<=', date("Y-m-d H:i:s"));
        })->get();
        */
    }

    public function canUse(UseCouponInterface $order)
    {
        $couponType = resolve($this->type);

        return $couponType->validate($order, $this->config);
    }
}
