<?php

namespace App\Models;

use App\Traits\HasCacheModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class Discount extends Model
{
    use HasFactory;
    use HasCacheModel;

    public function __construct()
    {
        $this->table = 'discount';
        $this->guarded = [];
        $this->appends = [
            'discount_type',
            'discount_unit',
        ];
        $this->casts = [
            'active_date' => 'datetime',
            'expiry' => 'datetime',
            'date_used' => 'datetime',
        ];
    }

    // custom display get{field_name}Attribute
    public function getDiscountTypeAttribute()
    {
        return DiscountType::getByCache()
            ->where('id', $this->discount_type_id)
            ->value('name');
    }

    // custom display get{field_name}Attribute
    public function getDiscountUnitAttribute()
    {
        return DiscountType::getByCache()
            ->where('id', $this->discount_type_id)
            ->value('unit');
    }

    /**
     * Check active and get by code
     *
     * @param string $code
     * @return TValue|TFirstDefault
     */
    public static function firstActiveByCode(string|null $code = '')
    {
        return static::getByCache()
            ->where('code', $code)
            ->where('status', 1)
            ->whereNull('date_used')
            ->filter(function($discount) {
                // The active_date can be not null, and greater than or equal with now
                return $discount['active_date'] && now()->greaterThanOrEqualTo($discount['active_date']);
            })
            ->filter(function($discount) {
                // The expiry can be null, or less than or equal with now
                return !$discount['expiry'] || now()->lessThanOrEqualTo($discount['expiry']);
            })
            ->first();
    }
}
