<?php

namespace App\Models;

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

class Vendor extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'store_name', 'shop_name', 'slug', 'store_description', 'description', 
        'business_category', 'logo', 'banner',
        'business_email', 'business_phone', 'phone', 
        'address', 'city', 'state', 'country', 'postal_code', 'zip_code',
        'website', 'tax_id', 
        'trade_license_path', 'business_registration_path', 'id_document_path',
        'onboarding_step', 'onboarding_completed_at', 'rejection_reason',
        'commission_rate', 'status', 'total_earnings', 'balance',
    ];

    protected $casts = [
        'commission_rate' => 'decimal:2',
        'total_earnings' => 'decimal:2',
        'balance' => 'decimal:2',
        'onboarding_step' => 'integer',
        'onboarding_completed_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($vendor) {
            if (empty($vendor->slug)) {
                $vendor->slug = Str::slug($vendor->shop_name);
            }
        });
    }

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

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

    public function orderItems()
    {
        return $this->hasMany(OrderItem::class);
    }

    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }

    public function statusHistories()
    {
        return $this->hasMany(VendorStatusHistory::class)->orderBy('created_at', 'desc');
    }

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

    public function getLogoUrlAttribute(): string
    {
        return $this->logo ? asset('storage/' . $this->logo) : asset('images/default-shop.png');
    }

    public function getBannerUrlAttribute(): ?string
    {
        return $this->banner ? asset('storage/' . $this->banner) : null;
    }
}
