<?php

namespace App\Models;

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

class CompanyConfiguration extends Model
{
    use HasFactory;

    protected $table = "tbl_company_configuration";

    protected $fillable = [
        'idcompany',
        'inventory_configuration',
        'credit_terms',
        'cash_options',
        'payment_validation',
        'status'
    ];

    protected $hidden = [
        'created_at',
        'updated_at'
    ];

    protected $casts = [
        'credit_terms' => 'array',
        'cash_options' => 'array'
    ];

    public function company(): HasOne
    {
        return $this->hasOne(Company::class, 'id', 'idcompany');
    }

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

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

    # Filtros
    public function scopeCompanyConfigurationFilters($query)
    {
        #Filtro de Buscador
        $query->when(
            request('search'),
            fn ($query) => $query->whereHas('company',
                fn ($q) => $q->where('rut', 'LIKE', '%' . request('search') . '%')
                    ->orWhere('business_name', 'LIKE', '%' . request('search') . '%'))
        );

        #Filtro de id de compañia
        $query->when(
            request('idcompany'),
            fn ($query) => $query->where('idcompany', request('idcompany'))
        );

        #Filtro de RUT
        $query->when(
            request('rut'),
            fn ($query) => $query->whereHas('company',
                fn ($q) => $q->where('rut', 'LIKE', '%' . request('rut') . '%'))
        );

        #Filtro de nombre
        $query->when(
            request('business_name'),
            fn ($query) => $query->whereHas('company',
                fn ($q) => $q->where('business_name', 'LIKE', '%' . request('business_name') . '%'))
        );

        #Filtro de configuración de inventario
        $query->when(
            request('inventory_configuration'),
            fn ($query) => $query->where('inventory_configuration', request('inventory_configuration'))
        );

        #Filtro de estados
        $query->when(
            request('status'),
            fn ($query) => $query->where('status', request('status'))
        )->when(
            !request('status'),
            fn ($query) => $query->where('status', 1)
        );

    }
}
