<?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;

class Vendor extends Model
{
    use HasFactory, \App\Traits\HotelScopeTrait;

    protected $fillable = [
        'hotel_id',
        'name',
        'contact_person',
        'email',
        'phone',
        'address',
        'tax_number',
        'payment_terms',
        'notes',
        'is_active',
        'category_id' // Added this
    ];

    protected $casts = [
        'is_active' => 'boolean'
    ];

    /**
     * Get the category for the vendor.
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    /**
     * Get the expenses for the vendor.
     */
    public function expenses(): HasMany
    {
        return $this->hasMany(Expense::class);
    }

    /**
     * Scope a query to only include active vendors.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Get the vendor's total expenses amount.
     */
    public function getTotalExpensesAttribute()
    {
        return $this->expenses()->sum('amount');
    }

    /**
     * Get the vendor's pending expenses amount.
     */
    public function getPendingExpensesAttribute()
    {
        return $this->expenses()->where('status', 'pending')->sum('amount');
    }
}