<?php

namespace App\Models;

use CodeIgniter\Model;

class OrganizacionModel extends Model
{
    protected $table            = 'organizacion';
    protected $primaryKey       = 'id';

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

    protected $useSoftDeletes   = true;

    protected $allowedFields = [
        'nombre',
        'activo',
        'ficha_id'
    ];

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

  

    public function getDatatable($request)
    {
        $columns = [
            0 => 'id',
            1 => 'nombre',
            2 => 'rut',
            3 => 'correo',
            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 + JOIN
        $builder = $this->builder()
             ->select([
                'organizacion.*',
                'respuestas.data',

                // CAMPOS JSON
                'IFNULL(JSON_UNQUOTE(JSON_EXTRACT(respuestas.data, "$.rut")), "-") AS rut',
                'IFNULL(JSON_UNQUOTE(JSON_EXTRACT(respuestas.data, "$.nombre")), "-") AS nombre_org',
                'IFNULL(JSON_UNQUOTE(JSON_EXTRACT(respuestas.data, "$.correoElectronico")), "-") AS correo',
                'IFNULL(JSON_UNQUOTE(JSON_EXTRACT(respuestas.data, "$.estadoDeVigencia")), "-") AS estado_vigencia',
            ])
            ->join('respuestas', 'respuestas.id = organizacion.ficha_id', 'left')
            ->where('organizacion.deleted_at', null);

        // SEARCH
        if (!empty($searchValue)) {
            $builder->groupStart()
                ->like('organizacion.nombre', $searchValue)
                ->orLike('respuestas.data', $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,
        ];
    }

    public function getListadoActivas()
    {
        return $this->select('id, nombre')
            ->where('activo', 1)
            ->where('deleted_at', null)
            ->orderBy('nombre', 'ASC')
            ->findAll();
    }

}
