<?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\Relations\HasManyThrough;

class GasCylinder extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'price',
        'size',
        'type',
        'material',
        'brand',
        'image',
        'gas_office_id',
        'is_available',
        'stock_quantity',
        'weight_kg',
        'safety_instructions',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'is_available' => 'boolean',
        'weight_kg' => 'decimal:2',
    ];

    /**
     * مكتب الغاز الذي يبيع هذا القنينة
     */
    public function gasOffice(): BelongsTo
    {
        return $this->belongsTo(GasOffice::class);
    }

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

    /**
     * طلبات الغاز التي تحتوي على هذه القنينة
     */
    public function gasOrders(): HasManyThrough
    {
        return $this->hasManyThrough(GasOrder::class, GasOrderItem::class, 'gas_cylinder_id', 'id', 'id', 'gas_order_id');
    }

    public function scopeAvailable($query)
    {
        return $query->where('is_available', true)->where('stock_quantity', '>', 0);
    }

    public function scopeBySize($query, $size)
    {
        return $query->where('size', $size);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('type', $type);
    }

    public function scopeByMaterial($query, $material)
    {
        return $query->where('material', $material);
    }

    public function scopeInStock($query)
    {
        return $query->where('stock_quantity', '>', 0);
    }

    /**
     * البحث عن قناني في مكتب غاز معين
     */
    public function scopeByOffice($query, $officeId)
    {
        return $query->where('gas_office_id', $officeId);
    }
}
