<?php

namespace App\Models\Clientes;

use CodeIgniter\Shield\Models\UserModel as ShieldUserModel;

class ClienteUsuariosModel extends ShieldUserModel
{
    protected $table = "users";

    /**
     * Whether primary key uses auto increment.
     *
     * @var bool
     */
    protected $useAutoIncrement = true;

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

    protected $allowedFields = ["id", "first_name", "last_name", "email"];
    protected $returnType = "App\Entities\Usuarios\UserEntity";

    protected $useTimestamps = true;
    protected $useSoftDeletes = true;
    protected $deletedField = 'deleted_at';

    protected $createdField = "created_at";

    protected $updatedField = "updated_at";

    public static $labelField = "nombre";

    protected $validationRules = [
        "last_name" => [
            "label" => "ClienteContactos.apellidos",
            "rules" => "trim|max_length[500]",
        ],
       "email" => [
            "label" => "ClienteContactos.email",
            "rules" => "trim|max_length[150]|valid_email|permit_empty",
        ],
        "first_name" => [
            "label" => "ClienteContactos.nombre",
            "rules" => "trim|max_length[100]",
        ],
    ];

    protected $validationMessages = [
        "last_name" => [
            "max_length" => "ClienteContactos.validation.apellidos.max_length",
        ],

        "email" => [
            "max_length" => "ClienteContactos.validation.email.max_length",
            "valid_email" => "ClienteContactos.validation.email.valid_email",
        ],
        "first_name" => [
            "max_length" => "ClienteContactos.validation.nombre.max_length",
        ],
    ];

    public function findAllWithClientes(string $selcols = "*", int $limit = null, int $offset = 0)
    {
        $sql =
            "SELECT t1." .
            $selcols .
            ",  t2.nombre AS cliente_id FROM " .
            $this->table .
            " t1  LEFT JOIN clientes t2 ON t1.cliente_id = t2.id";
        if (!is_null($limit) && intval($limit) > 0) {
            $sql .= " LIMIT " . $limit;
        }

        if (!is_null($offset) && intval($offset) > 0) {
            $sql .= " OFFSET " . $offset;
        }

        $query = $this->db->query($sql);
        $result = $query->getResultObject();
        return $result;
    }

    public function removeClienteFromUser($user_id = -1){

        $this->db->table($this->table)->where('id', $user_id)->update(['cliente_id' => null]);
    }


    public function addUserToClient($user_id = -1, $cliente_id = -1){
        if($user_id < 1 || $cliente_id < 1){
            return;
        }
        $this->db->table($this->table)->where('id', $user_id)->update(['cliente_id' => $cliente_id]);
    }

    /**
     * Get resource data.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource(string $search = "", $cliente_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.first_name AS nombre, t1.last_name AS apellidos,
                t2.secret AS email"
            );

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

        return $builder;
    }
}
