<?php

namespace App\Models\Etiquetas;

use CodeIgniter\Model;
use App\Entities\Etiquetas\EtiquetaTitulo;

class EtiquetasTitulosModel extends Model
{
    protected $table            = 'etiquetas_titulos';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;

    protected $returnType       = EtiquetaTitulo::class;
    protected $useSoftDeletes   = true;

    protected $allowedFields    = [
        'comentarios',
        'direccion',
        'att',
        'cliente_id',
        'user_created_at',
        'user_updated_at',
        'user_deleted_at',
    ];

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

    protected $validationRules    = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;

    
    protected $beforeDelete = ['addUserDeleted'];
    protected $beforeUpdate = ['addUserUpdated'];

    protected function addUserDeleted(array $data)
    {
        $userId = auth()->user()->id;

        if (!isset($data['data'])) {
            $data['data'] = [];
        }

        if (!empty($data['id'])) {
            $builder = $this->builder();
            $builder->whereIn($this->primaryKey, (array) $data['id'])
                    ->update(['user_deleted_at' => $userId]);
        }
        return $data;
    }

    protected function addUserUpdated(array $data)
    {
        $userId = auth()->user()->id;

        if (!isset($data['data'])) {
            $data['data'] = [];
        }

        if (!empty($data['id'])) {
            $builder = $this->builder();
            $builder->whereIn($this->primaryKey, (array) $data['id'])
                    ->update(['user_updated_at' => $userId]);
        }
        return $data;
    }

    public function getEtiquetasTitulos()
    {
        return $this->db->table('etiquetas_titulos et')
            ->select('et.id, GROUP_CONCAT(DISTINCT etl.ot_id ORDER BY etl.ot_id ASC SEPARATOR ", ") as lista_ots')
            ->select('COUNT(DISTINCT etl.numero_caja) as cajas, et.att, et.direccion')
            ->join('etiquetas_titulos_lineas etl', 'etl.etiqueta_titulos_id = et.id')
            ->where('et.deleted_at IS NULL')
            ->where('etl.deleted_at IS NULL')
            ->groupBy('et.id, et.att, et.direccion');
    }
}
