<?php namespace App\Models;

use CodeIgniter\Model;

class FormulariosModel extends Model
{
    protected $table      = 'formularios';
    protected $primaryKey = 'id';

    protected $useAutoIncrement = true;

    // Campos permitidos para insertar/actualizar
    protected $allowedFields = [
        'nombre',
        'fecha_creacion',
        'usuario_creador_id',
        'usuario_modificacion_id',
        'activo',
        'esquema',
        'version_actual',
        'fecha_modificacion',
        'pasos',
        'created_at',
        'modified_at',
        'deleted_at',
        'tipo_derivacion_inicial',
        'usuario_derivacion_inicial',
        'perfil_derivacion_inicial'
    ];

    // Timestamps automáticos de CI4
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'modified_at';
    protected $deletedField  = 'deleted_at';

    // Soft deletes
    protected $useSoftDeletes = true;

    // Validaciones opcionales (puedes editarlas)
    protected $validationRules = [
        'nombre' => 'required'
    ];

    protected $validationMessages = [
        'nombre' => [
            'required' => 'El nombre del formulario es obligatorio.'
        ]
    ];

    public function getDatatable($request)
    {
        $columns = [
            0 => 'id',
            1 => 'nombre',
            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)
                ->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,
        ];
    }
}
