<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Voucher extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'name',
        'type', // fixed, percentage
        'value',
        'min_spend',
        'max_discount',
        'start_date',
        'end_date',
        'stock'
    ];

    protected $casts = [
        'start_date' => 'datetime',
        'end_date' => 'datetime',
    ];

    public function isValid(): bool
    {
        $now = now();
        return $this->stock > 0 && $now->between($this->start_date, $this->end_date);
    }

    public function calculateDiscount($subtotal): float
    {
        if ($subtotal < $this->min_spend) {
            return 0.00;
        }

        if ($this->type === 'fixed') {
            return min($this->value, $subtotal);
        }

        $discount = $subtotal * ($this->value / 100);
        if ($this->max_discount) {
            $discount = min($discount, $this->max_discount);
        }

        return round($discount, 2);
    }
}
