<?php

namespace App\Models;

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

class Vendor extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * The data type of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'string';

    protected $fillable = [
        'user_id',
        'business_name',
        'slug',
        'contact_person',
        'email',
        'phone',
        'address',
        'city',
        'state',
        'country',
        'postal_code',
        'description',
        'logo',
        'website',
        'rating',
        'review_count',
        'is_verified',
        'is_active',
    ];

    protected $casts = [
        'rating' => 'decimal:2',
        'review_count' => 'integer',
        'is_verified' => 'boolean',
        'is_active' => 'boolean',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($vendor) {
            if (empty($vendor->id)) {
                $vendor->id = Str::uuid();
            }
            if (empty($vendor->track_id)) {
                $vendor->track_id = 'VEN_' . strtoupper(Str::random(6));
            }
        });
    }

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

    public function vendorServices()
    {
        return $this->hasMany(VendorService::class);
    }

    public function activeVendorServices()
    {
        return $this->hasMany(VendorService::class)->where('is_active', true);
    }

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

    public function serviceItems()
    {
        return $this->belongsToMany(ServiceItem::class, 'vendor_services')
            ->withPivot(['price', 'min_order_quantity', 'max_order_quantity', 'production_days', 'notes', 'is_active'])
            ->withTimestamps();
    }

    public function activeServiceItems()
    {
        return $this->belongsToMany(ServiceItem::class, 'vendor_services')
            ->wherePivot('is_active', true)
            ->withPivot(['price', 'min_order_quantity', 'max_order_quantity', 'production_days', 'notes'])
            ->withTimestamps();
    }
}
