<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;

class ProductEntryDetail extends Model
{
    use HasFactory;

    protected $table = "tbl_product_entry_detail";

    protected $fillable = [
        'idproduct_entry',
        'idproduct',
        'quantity',
        'cost_total',
        'status'
    ];

    protected $hidden = [
        'updated_at'
    ];

    # Relaciones
    public function productEntry(): HasOne
    {
        return $this->hasOne(ProductEntry::class, 'id', 'idproduct_entry');
    }

    public function product(): HasOne
    {
        return $this->hasOne(Product::class, 'id', 'idproduct');
    }

    # Query scopes
    public function scopeActiveForID($query, $id)
    {
        return $query->where('id', $id)->where('status', 1);
    }

    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }

    public function scopeCompany($query)
    {
        return $query->when(
            request('idcompany'),
            fn($query) => $query->whereHas(
                'productEntry',
                fn($q) => $q->where('idcompany', request('idcomany'))
            )
        );
    }

    # Filtros
    public function scopeFilters($query)
    {
        $query->when(
            request('idproduct_entry'),
            fn($query) => $query->where('idproduct_entry', request('idproduct_entry'))
        );

        $query->when(
            request('idproduct'),
            fn($query) => $query->where('idproduct', request('idproduct'))
        );

        $query->company();

        $query->when(
            request('status'),
            fn($query) => $query->where('status', request('status'))
        )->when(
            !request('status'),
            fn($query) => $query->where('status', 1)
        );
    }
}
