<?php

namespace App\Models;

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

class Coupon extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'type',
        'amount',
        'product_id',
        'quantity',
        'description',
        'expires_at',
        'is_active',
        'max_uses',
        'used_count'
    ];

    protected $casts = [
        'expires_at' => 'datetime',
        'is_active' => 'boolean',
        'amount' => 'decimal:2'
    ];

    // Relationships
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function redemptions()
    {
        return $this->hasMany(CouponRedemption::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true)
                    ->where(function($q) {
                        $q->whereNull('expires_at')
                          ->orWhere('expires_at', '>', Carbon::now());
                    })
                    ->whereColumn('used_count', '<', 'max_uses');
    }

    // Helper methods
    public function isExpired()
    {
        return $this->expires_at && Carbon::now()->greaterThan($this->expires_at);
    }

    public function isMaxUsesReached()
    {
        return $this->used_count >= $this->max_uses;
    }

    public function canBeUsed()
    {
        return $this->is_active 
            && !$this->isExpired() 
            && !$this->isMaxUsesReached();
    }

    public function hasBeenUsedBy($userId)
    {
        return $this->redemptions()->where('user_id', $userId)->exists();
    }
}