<?php

namespace App\Models\Logistica;
use CodeIgniter\Database\BaseBuilder;

use CodeIgniter\Model;

class EnvioModel extends Model
{
    protected $table = 'envios';
    protected $primaryKey = 'id';

    protected $useAutoIncrement = true;
    protected $returnType = \App\Entities\Logistica\EnvioEntity::class;
    protected $useSoftDeletes = false;

    protected $allowedFields = [
        'finalizado',
        'codigo_seguimiento',
        'proveedor_id',
        'comentarios',
        'cliente_id',
        'att',
        'direccion',
        'ciudad',
        'cp',
        'email',
        'telefono',
        'pais_id',
        'mostrar_precios',
        'mostrar_iva',
        'created_at',
        'updated_at',
        'cajas',
        'tipo_envio',
    ];

    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    public function getDatatableQuery($tipo_envio = "estandar"): BaseBuilder
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id, GROUP_CONCAT(DISTINCT t5.id) AS ots, 
                COUNT(t2.id) AS num_lineas,
                t1.att, t1.direccion, t1.ciudad, t3.nombre as pais, t1.cp, t1.email, t1.telefono, t1.finalizado"
            );
        $builder->join("envios_lineas t2", "t2.envio_id = t1.id", "left");
        $builder->join("lg_paises t3", "t3.id = t1.pais_id", "left");
        $builder->join("pedidos t4", "t4.id = t2.pedido_id", "left");
        $builder->join('ordenes_trabajo t5', 't5.pedido_id = t4.id');
        $builder->where("t1.tipo_envio", $tipo_envio);

        $builder->groupBy("t1.id");
        return $builder;
    }

    public function getDatatableQueryFerroPrototipo(): BaseBuilder
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id, GROUP_CONCAT(DISTINCT t5.id) AS ots, 
                t1.att, t1.direccion, t1.ciudad, t3.nombre as pais, t1.cp, t1.email, t1.telefono, t1.finalizado"
            );
        $builder->join("lg_paises t3", "t3.id = t1.pais_id", "left");
        $builder->join("pedidos t4", "t4.id = t2.pedido_id", "left");
        $builder->join('ordenes_trabajo t5', 't5.pedido_id = t4.id');
        $builder->whereIn("t1.tipo_envio", ["estandar"]);

        $builder->groupBy("t1.id");
        return $builder;
    }
}
