<?php

namespace App\Controllers;

use App\Models\ValvulasModel;

class Valvulas extends BaseController
{
    protected $ValvulasModel;

    public function __construct()
    {
        $this->ValvulasModel = new ValvulasModel();
    }

    public function index()
    {
        $model = $this->ValvulasModel;
        $search = $this->request->getGet();

        $page = (int) ($this->request->getVar('page') ?? 1);
        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        $total = $model->getFilteredCount($search);
        $items = $model->getFilteredData($perPage, $offset, $search);

        $pager = \Config\Services::pager();
        $pager->makeLinks($page, $perPage, $total);

        return view('valvulas/index', [
            'items' => $items,
            'pager' => $pager,
            'search' => $search
        ]);
    }

    public function create()
    {
        return view('valvulas/create');
    }

    public function store()
    {
        $emptyToNull = fn($v) => trim($v) === '' ? null : $v;

        $data = [
            'id_valvula'    => $this->request->getPost('id_valvula'),
            'este'          => $emptyToNull($this->request->getPost('este')),
            'norte'         => $emptyToNull($this->request->getPost('norte')),
            'cota'          => $emptyToNull($this->request->getPost('cota')),
            'diametro'      => $emptyToNull($this->request->getPost('diametro')),
            'tipo'          => $this->request->getPost('tipo'),
            'funcion'       => $this->request->getPost('funcion'),
            'edad'          => $emptyToNull($this->request->getPost('edad')),
            'estado'        => $this->request->getPost('estado'),
            'tapa'          => $this->request->getPost('tapa'),
            'responsable'   => $this->request->getPost('responsable'),
            'ubicacion'     => $this->request->getPost('ubicacion'),
            'departamento'    => $this->request->getPost('departamento'),
            'provincia'     => $this->request->getPost('provincia'),
            'municipio'     => $this->request->getPost('municipio'),
            'distrito'      => $this->request->getPost('distrito'),
            'otb'           => $this->request->getPost('otb'),
            'descripcion'     => $this->request->getPost('descripcion'),
        ];

        $this->ValvulasModel->insert($data);

        return redirect()->to(base_url('valvulas'))->with('mensaje', 'Válvula registrada exitosamente.');
    }

    public function edit($id)
    {
        $valvula = $this->ValvulasModel->find($id);

        if (!$valvula) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException("Válvula no encontrada: $id");
        }

        return view('valvulas/edit', ['valvula' => $valvula]);
    }

    public function update($id)
    {
        $data = $this->request->getPost();

        $camposEnteros = ['este', 'norte', 'cota', 'diametro', 'edad'];
        foreach ($camposEnteros as $campo) {
            if (isset($data[$campo]) && $data[$campo] === '') {
                $data[$campo] = null;
            } elseif (isset($data[$campo])) {
                $data[$campo] = (int) $data[$campo];
            }
        }

        $this->ValvulasModel->update($id, $data);
        return redirect()->to('/valvulas');
    }

    public function view($id)
    {
        $valvula = $this->ValvulasModel->find($id);

        if (!$valvula) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound("Válvula no encontrada");
        }

        return view('valvulas/view', ['valvula' => $valvula]);
    }

    public function delete($id)
    {
        $this->ValvulasModel->delete($id);
        return redirect()->to('/valvulas')->with('status', 'Registro eliminado correctamente');
    }
}


