<?php

namespace App\Models;

use CodeIgniter\Model;

class UsuarioModel extends Model
{
    protected $table            = 'usuario';
    protected $primaryKey       = 'id';

    protected $useAutoIncrement = true;
    protected $returnType       = 'array';

    protected $useSoftDeletes   = true;

    protected $allowedFields = [
        'nombre',
        'email',
        'password',
        'activo',
        'rut',
        'perfil_id',
    ];

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

    // Método para login
    public function loginUsuario($email, $password)
    {
        $user = $this->where('email', $email)->where('activo',1)->first();

        if (!$user) return null;

        if (!password_verify($password, $user['password'])) return null;

        return $user;
    }

    public function getDatatable($request)
    {
        $columns = [
            0 => 'id',
            1 => 'nombre',
            2 => 'email',
            3 => 'rut',
            4 => 'activo',
        ];

        $searchValue = $request->getPost('search')['value'];
        $start = $request->getPost('start');
        $length = $request->getPost('length');
        $orderColumn = $columns[$request->getPost('order')[0]['column']];
        $orderDir = $request->getPost('order')[0]['dir'];

        // QUERY BASE
        $builder = $this->builder()->where('deleted_at', null);

        // SEARCH
        if (!empty($searchValue)) {
            $builder->groupStart()
                ->like('nombre', $searchValue)
                ->orLike('email', $searchValue)
                ->orLike('rut', $searchValue)
                ->groupEnd();
        }

        // TOTAL FILTRADOS
        $filteredCount = $builder->countAllResults(false);

        // ORDER + LIMIT
        $builder->orderBy($orderColumn, $orderDir)
                ->limit($length, $start);

        $data = $builder->get()->getResultArray();

        // TOTAL SIN FILTRO
        $totalCount = $this->countAll();

        return [
            'draw' => intval($request->getPost('draw')),
            'recordsTotal' => intval($totalCount),
            'recordsFiltered' => intval($filteredCount),
            'data' => $data,
        ];
    }

}
