<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Coupon extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'code',
        'type',
        'value',
        'min_purchase',
        'max_discount',
        'starts_at',
        'expires_at',
        'usage_limit',
        'used_count',
        'status'
    ];

    protected $casts = [
        'starts_at' => 'datetime',
        'expires_at' => 'datetime',
        'status' => 'boolean'
    ];

    public function isValid($total = 0)
    {
        if (!$this->status) return false;
        if ($this->isExpired()) return false;
        if ($this->usage_limit && $this->used_count >= $this->usage_limit) return false;
        if ($this->min_purchase && $total < $this->min_purchase) return false;
        
        return true;
    }

    public function isExpired()
    {
        return $this->expires_at && now()->gt($this->expires_at);
    }

    public function calculateDiscount($total)
    {
        $discount = $this->type === 'percentage' 
            ? ($total * ($this->value / 100))
            : $this->value;

        if ($this->max_discount) {
            $discount = min($discount, $this->max_discount);
        }

        return $discount;
    }
}