<?php

namespace App\Models;

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

class ProductsImport extends Model
{
    use HasFactory;
    protected $table = "tbl_products_import";

    protected $fillable = [
        'code',
        'barcode',
        'name',
        'description',
        'cost',
        'price',
        'alternativeprice',
        'margin',
        'offerprice',
        'minimumstock',
        'maximumstock',

        'main_image',
        'optional_image1',
        'optional_image2',
        'optional_image3',
        'optional_image4',

        'idattributes',
        'idspecificattributes',
        'iduses',
        'idspecificuses',

        'idcointype',
        'idcategory',
        'idsubcategory',
        'idspecificsubcategory',
        'idtype',
        'idsupplier',
        'idunitmeasure',
        'idunitmeasureoptional',
        'idbusinessarea',
        'idclassification',
        'idwarehouses',

        'idcompany',
        'created_by',
        'status_import',
        'status',
    ];

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

    protected $casts = [
        'idattributes' => 'array',
        'idspecificattributes' => 'array',
        'iduses' => 'array',
        'idspecificuses' => 'array',
        'idwarehouses' => 'array',
    ];

    # Relaciones
    public function cointType(): HasOne
    {
        return $this->hasOne(CoinType::class, 'id', 'idcointype');
    }

    public function category(): HasOne
    {
        return $this->hasOne(Category::class, 'id', 'idcategory');
    }

    public function subcategory(): HasOne
    {
        return $this->hasOne(Subcategory::class, 'id', 'idsubcategory');
    }

    public function specificSubcategory(): HasOne
    {
        return $this->hasOne(SpecificSubcategory::class, 'id', 'idspecificsubcategory');
    }

    public function type(): HasOne
    {
        return $this->hasOne(TypeProduct::class, 'id', 'idtype');
    }

    public function supplier(): HasOne
    {
        return $this->hasOne(Supplier::class, 'id', 'idsupplier');
    }

    public function unitMeasure(): HasOne
    {
        return $this->hasOne(UnitMeasure::class, 'id', 'idunitmeasure');
    }

    public function unitMeasureOptional(): HasOne
    {
        return $this->hasOne(UnitMeasure::class, 'id', 'idunitmeasureoptional');
    }

    public function businessArea(): HasOne
    {
        return $this->hasOne(BusinessArea::class, 'id', 'idbusinessarea');
    }

    public function classification(): HasOne
    {
        return $this->hasOne(ProductClassification::class, 'id', 'idclassification');
    }

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

    public function user(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'created_by');
    }

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

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

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

    public function scopeCode($query, $code, $id = null)
    {
        return $query->when($id, fn ($query) => $query->where('id', '<>', $id))->where('code', $code)->company();
    }

    public function scopeAtributtes($query, $idattributes)
    {
        return $query->whereRaw("JSON_SEARCH(idattributes, 'one', '$idattributes') IS NOT NULL");
    }

    public function scopeUses($query, $iduses)
    {
        return $query->whereRaw("JSON_SEARCH(iduses, 'one', '$iduses') IS NOT NULL");
    }

    public function scopeSpecificUses($query, $idspecificuses)
    {
        return $query->whereRaw("JSON_SEARCH(idspecificuses, 'one', '$idspecificuses') IS NOT NULL");
    }

    public function scopeCreateUser($query, $created_by)
    {
        return $query->where('created_by', $created_by);
    }

    # Filtros
    public function scopeProductFilters($query)
    {
        #Filtro de Buscador
        $query->when(
            request('search'),
            fn ($query) => $query->where('code', 'LIKE', '%' . request('search') . '%')
                ->orWhere('barcode', 'LIKE', '%' . request('search') . '%')
                ->orWhere('name', 'LIKE', '%' . request('search') . '%')
        );

        #Filtro de codigo
        $query->when(
            request('code'),
            fn ($query) => $query->where('code', 'LIKE', '%' . request('code') . '%')
        );

        #Filtro de barras
        $query->when(
            request('barcode'),
            fn ($query) => $query->where('barcode', 'LIKE', '%' . request('barcode') . '%')
        );

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

        #Filtro de atributos
        $query->when(
            request('idattribute'),
            fn ($query) => $query->whereRaw("JSON_SEARCH(idattributes, 'one', '" . request('idattribute') . "') IS NOT NULL")

        );

        #Filtro de atributos especificos
        $query->when(
            request('idspecificattribute'),
            fn ($query) => $query->whereRaw("JSON_SEARCH(idspecificattributes, 'one', '" . request('idspecificattribute') . "') IS NOT NULL")

        );

        #Filtro de usos
        $query->when(
            request('iduse'),
            fn ($query) => $query->whereRaw("JSON_SEARCH(iduses, 'one', '" . request('iduse') . "') IS NOT NULL")

        );

        #Filtro de usos especificos
        $query->when(
            request('idspecificuse'),
            fn ($query) => $query->whereRaw("JSON_SEARCH(idspecificuses, 'one', '" . request('idspecificuse') . "') IS NOT NULL")

        );

        #Filtro de tipo de moneda
        $query->when(
            request('idcointype'),
            fn ($query) => $query->where('idcointype', request('idcointype'))

        );

        #Filtro de categoria
        $query->when(
            request('idcategory'),
            fn ($query) => $query->where('idcategory', request('idcategory'))

        );

        #Filtro de subcategoria
        $query->when(
            request('idsubcategory'),
            fn ($query) => $query->where('idsubcategory', request('idsubcategory'))
        );

        #Filtro de subcategoria especifica
        $query->when(
            request('idspecificsubcategory'),
            fn ($query) => $query->where('idspecificsubcategory', request('idspecificsubcategory'))
        );

        #Filtro de tipo
        $query->when(
            request('idtype'),
            fn ($query) => $query->where('idtype', request('idtype'))
        );

        #Filtro de proveedor
        $query->when(
            request('idsupplier'),
            fn ($query) => $query->where('idsupplier', request('idsupplier'))
        );

        #Filtro de unidad de medida
        $query->when(
            request('idunitmeasure'),
            fn ($query) => $query->where('idunitmeasure', request('idunitmeasure'))
        );

        #Filtro de unidad de medida opcional
        $query->when(
            request('idunitmeasureoptional'),
            fn ($query) => $query->where('idunitmeasureoptional', request('idunitmeasureoptional'))
        );

        #Filtro de area de negocio
        $query->when(
            request('idbusinessarea'),
            fn ($query) => $query->where('idbusinessarea', request('idbusinessarea'))
        );

        #Filtro de clasificación
        $query->when(
            request('idclassification'),
            fn ($query) => $query->where('idclassification', request('idclassification'))
        );

        #Filtro de sucursal
        $query->when(
            request('idbranchoffice'),
            fn ($query) => $query->whereHas('businessArea',
                fn ($q) => $q->where('idbranchoffice', request('idbranchoffice')))
        );

        #Filtro de distrito
        $query->when(
            request('iddistrict'),
            fn ($query) => $query->whereHas('businessArea.branchOffice',
                fn ($q) => $q->where('iddistrict', request('iddistrict')))
        );

        #Filtro de provincia
        $query->when(
            request('idprovince'),
            fn ($query) => $query->whereHas('businessArea.branchOffice',
                fn ($q) => $q->where('idprovince', request('idprovince')))
        );

        #Filtro de departamento
        $query->when(
            request('iddepartment'),
            fn ($query) => $query->whereHas('businessArea.branchOffice',
                fn ($q) => $q->where('iddepartment', request('iddepartment')))
        );

        #Filtro de pais
        $query->when(
            request('idcountry'),
            fn ($query) => $query->whereHas('businessArea.branchOffice',
                fn ($q) => $q->where('idcountry', request('idcountry')))
        );

        #Filtro de usuario creador
        $query->when(
            request('created_by'),
            fn ($query) => $query->where('created_by', request('created_by'))
        );

        #Filtro de estado de importación
        $query->when(
            $query->when(
                request('status_import') !== null,
                fn ($query) => $query->where('status_import', request('status_import'))
            )->when(
                request('status_import') === null,
                fn ($query) => $query->where('status_import', 0)
            ),
        );

        #Filtro de idcompany
        $query->company();

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