<?php

declare(strict_types=1);

namespace App\Models\Usuarios;

use CodeIgniter\Shield\Authentication\Traits\HasAccessTokens;
use CodeIgniter\Shield\Models\UserModel as ShieldUserModel;
use App\Entities\Usuarios\UserEntity;

class UserModel extends ShieldUserModel
{
    use HasAccessTokens;
    
    protected function initialize(): void
    {
        parent::initialize();

        $this->allowedFields = [
            ...$this->allowedFields,
            'first_name',   // Añadido
            'last_name',   // Añadido
            'cliente_id',   // Añadido
            'comments',   // Añadido
        ];
    }

    const SORTABLE = [
        0 => "t1.id",
        1 => "t1.first_name",
        2 => "t1.last_name",
        3 => "t2.secret",
        4 => "t3.nombre",
        5 => "t1.last_active",
    ];

    protected $returnType = UserEntity::class;

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

    protected $validationRules = [
        "first_name" => [
            "label" => "Users.firstName",
            "rules" => "required|trim|max_length[150]",
        ],        
        "last_name" => [
            "label" => "Users.lastName",
            "rules" => "required|trim|max_length[150]",
        ], 
        'new_pwd' => 'permit_empty|min_length[8]',
        'new_pwd_confirm' => 'permit_empty|required_with[new_pwd]|matches[new_pwd]',
        "comments" => "permit_empty|trim|max_length[512]"
    ];

    protected $validationMessages = [
        'first_name' => [
            "max_length" => "Users.validation.first_name.max_length",
            "required" => "Users.validation.first_name.required"
        ],
        'last_name' => [
            "max_length" => "Users.validation.last_name.max_length",
            "required" => "Users.validation.last_name.required"
        ],
        'new_pwd' => [
            'min_length' => "App.profile_rules_password_m"
        ],
        'new_pwd_confirm' => [
            'matches' => "App.profile_rules_password_confirm_m"
        ],
        'comments' => [
            "max_length" => "Users.validation.last_name.max_length",
        ]

    ];

    public function getResource($search = [])
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id as id, t1.first_name AS first_name, t1.last_name AS last_name, 
                t2.secret AS email, t1.last_active AS last_active, t3.nombre AS cliente"
            );

        $builder->join("auth_identities t2", "t1.id = t2.user_id", "left");
        $builder->join("clientes t3", "t1.cliente_id = t3.id", "left");

        $builder->where('t1.deleted_at', null)->groupBy("t1.id");

        if (empty($search))
            return $builder;
        else {
            $builder->groupStart();
            foreach ($search as $col_search) {
                $column = self::SORTABLE[$col_search[0]];
                $value = $col_search[2];
                $builder->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%");
            }
            $builder->groupEnd();
            return $builder;
        }
    }

    public function getComerciales()
    {

        $builder = $this->db
            ->table("users" . " t1")
            ->select(
                "t1.id AS id, CONCAT(t1.first_name, ' ', t1.last_name) AS name"
            );

        $builder->where('t1.deleted_at', null);
        $builder->where("t2.group", "comercial");
        $builder->join("auth_groups_users t2", "t1.id = t2.user_id", "left");

        return $builder->get()->getResult();

    }

    public function getFullName($id=0){
        $builder = $this->db
            ->table("users" . " t1")
            ->select(
                "CONCAT(t1.first_name, ' ', t1.last_name) AS name"
            );

        $builder->where('t1.deleted_at', null);
        $builder->where('t1.id', $id);

        return $builder->get()->getRow()->name;
    }

    // Método para comprobar si el email ya está registrado
    public function isEmailUnique($email)
    {
        $builder = $this->db
            ->table("auth_identities t1") // La tabla correcta
            ->select("t1.secret AS email")
            ->where('secret', $email);

        // Obtener resultados
        $result = $builder->get()->getRow();

        // Devuelve true si no se encuentra el correo (es único), false en caso contrario
        return $result === null;
    }
   

}
