<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Vendor extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id', 'store_name', 'slug', 'description', 'logo', 'banner',
        'phone', 'address', 'city', 'state', 'country', 'postal_code',
        'status', 'subscription_plan', 'subscription_expires_at',
        'commission_rate', 'balance', 'total_earnings',
        'bank_name', 'bank_account_number', 'bank_routing_number', 'paypal_email',
        'business_documents', 'social_links', 'rejection_reason',
    ];

    protected $casts = [
        'subscription_expires_at' => 'datetime',
        'commission_rate' => 'decimal:2',
        'balance' => 'decimal:2',
        'total_earnings' => 'decimal:2',
        'business_documents' => 'array',
        'social_links' => 'array',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function products(): HasMany
    {
        return $this->hasMany(Product::class);
    }

    public function orders(): HasMany
    {
        return $this->hasMany(Order::class);
    }

    public function categories(): HasMany
    {
        return $this->hasMany(Category::class);
    }

    public function coupons(): HasMany
    {
        return $this->hasMany(Coupon::class);
    }

    public function withdrawRequests(): HasMany
    {
        return $this->hasMany(WithdrawRequest::class);
    }

    public function subscriptionTransactions(): HasMany
    {
        return $this->hasMany(SubscriptionTransaction::class);
    }

    public function isApproved(): bool
    {
        return $this->status === 'approved';
    }

    public function hasActiveSubscription(): bool
    {
        if ($this->subscription_plan === 'free') return true;
        return $this->subscription_expires_at && $this->subscription_expires_at->isFuture();
    }

    public function getMaxProducts(): int
    {
        return config("vendorflow.plans.{$this->subscription_plan}.max_products", 10);
    }

    public function canAddMoreProducts(): bool
    {
        if (!$this->hasActiveSubscription()) return false;
        return $this->products()->count() < $this->getMaxProducts();
    }
}
