<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Vendor extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'user_id', 'business_name', 'business_email', 'business_phone',
        'business_address', 'business_logo', 'kyc_status',
        'vendor_type_id', 'commission_rate', 'rating', 'total_orders',
        'rejection_reason', 'admin_remarks', 'approved_at',
        'country', 'currency', 'language', 'referral_code',
        'latitude', 'longitude', 'service_radius', 'profile_status', 'is_online'
    ];

    protected $casts = [
        'commission_rate' => 'decimal:2',
        'rating' => 'decimal:2',
        'approved_at' => 'datetime',
    ];

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

    public function vendorType()
    {
        return $this->belongsTo(VendorType::class);
    }



    public function providerServices()
    {
        return $this->belongsToMany(ProviderService::class, 'vendor_provider_services');
    }

    public function wallet()
    {
        return $this->morphOne(Wallet::class, 'owner');
    }

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

    public function kycDocuments()
    {
        return $this->hasMany(KycDocument::class);
    }

    public function ads()
    {
        return $this->hasMany(Ad::class);
    }

    public function subscriptions()
    {
        return $this->hasMany(UserSubscription::class);
    }

    public function activeSubscription()
    {
        return $this->hasOne(UserSubscription::class)->where('status', 'active')->latest();
    }

    public function bankDetails()
    {
        return $this->hasOne(VendorBankDetail::class);
    }

    public function kycLogs()
    {
        return $this->hasMany(KycLog::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->whereHas('user', fn($q) => $q->where('status', 'active'));
    }

    public function scopePending($query)
    {
        return $query->whereHas('user', fn($q) => $q->where('status', 'pending'));
    }

    // Accessors
    public function getStatusAttribute()
    {
        return $this->user->status;
    }


    public function scopeKycPending($query)
    {
        return $query->where('kyc_status', 'pending');
    }
}
