<?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',
    ];

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

    public function getDatatableQuery(): BaseBuilder
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id, GROUP_CONCAT(DISTINCT t2.pedido_id) AS pedidos, 
                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->groupBy("t1.id");
        return $builder;
    }
}
