<?php

namespace App\Models;

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

class Coupon extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'type',
        'value',
        'uses',
        'max_uses',
        'starts_at',
        'expires_at',
        'is_active'
    ];

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

    /**
     * Check if the coupon is valid
     * 
     * @return bool
     */
    public function isValid()
    {
        // Check if active
        if (!$this->is_active) {
            return false;
        }

        // Check if max uses reached
        if ($this->max_uses !== null && $this->uses >= $this->max_uses) {
            return false;
        }

        // Check if expired
        if ($this->expires_at !== null && now()->gt($this->expires_at)) {
            return false;
        }

        // Check if started
        if ($this->starts_at !== null && now()->lt($this->starts_at)) {
            return false;
        }

        return true;
    }

    /**
     * Calculate discount amount based on original price
     * 
     * @param float $originalPrice
     * @return float
     */
    public function calculateDiscount($originalPrice)
    {
        if ($this->type === 'percentage') {
            return ($originalPrice * $this->value) / 100;
        }
        
        // Fixed amount discount
        return min($this->value, $originalPrice); // Don't discount more than the price
    }

    /**
     * Increment the uses counter
     */
    public function incrementUses()
    {
        $this->increment('uses');
    }
}