<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Coupon extends Model
{
    protected $fillable = [
        'vendor_id', 'created_by', 'scope', 'code', 'description',
        'type', 'value', 'max_discount', 'minimum_order',
        'usage_limit', 'per_user_limit', 'used_count', 'expires_at', 'is_active',
    ];

    protected $casts = [
        'value' => 'decimal:2',
        'max_discount' => 'decimal:2',
        'minimum_order' => 'decimal:2',
        'is_active' => 'boolean',
        'expires_at' => 'date',
    ];

    public function vendor()
    {
        return $this->belongsTo(Vendor::class);
    }

    public function products()
    {
        return $this->belongsToMany(Product::class, 'coupon_product')->withTimestamps();
    }

    public function isValid(): bool
    {
        if (!$this->is_active) return false;
        if ($this->expires_at && $this->expires_at->isPast()) return false;
        if ($this->usage_limit && $this->used_count >= $this->usage_limit) return false;
        return true;
    }

    public function calculateDiscount(float $subtotal): float
    {
        if ($subtotal < $this->minimum_order) return 0;
        if ($this->type === 'percentage') {
            $discount = round($subtotal * ($this->value / 100), 2);
            if ($this->max_discount > 0) {
                $discount = min($discount, $this->max_discount);
            }
            return $discount;
        }
        return min($this->value, $subtotal);
    }

    public function scopeByAdmin($query)
    {
        return $query->where('created_by', 'admin');
    }

    public function scopeByVendor($query, $vendorId = null)
    {
        $q = $query->where('created_by', 'vendor');
        if ($vendorId) {
            $q->where('vendor_id', $vendorId);
        }
        return $q;
    }
}
