<?php

namespace Modules\Admin\app\Models;

use App\Helper\Constant\RequestConstant;
use App\Traits\HasCacheModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Str;
use Modules\Admin\Database\factories\DiscountFactory;

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',
        ];
    }

    public static function createWithDefault(array $data): Discount
    {
        $discount = new self;

        $discount = $discount->create(array_merge([
            'active_date' => now(),
            'code' => Discount::generateCode()
        ], $data));

        return $discount;
    }

    public static function generateCode()
    {
        $code = Str::random(6);
        if (self::where('code', $code)->count()) {
            return static::generateCode();
        }
        return $code;
    }

    // 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');
    }

    public function discountType(): BelongsTo
    {
        return $this->belongsTo(DiscountType::class);
    }
}
