<?php namespace App\Controllers;

use App\Models\ValvulasModel;

class Valvulas extends BaseController
{
    public function index()
    {
        $model = new 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()
    {
        $model = new ValvulasModel();
        $model->save($this->request->getPost());
        return redirect()->to('/valvulas');
    }

    public function edit($id)
    {
        $model = new ValvulasModel();
        $data['registro'] = $model->find($id);
        return view('valvulas/edit', $data);
    }

    public function update($id)
    {
        $model = new ValvulasModel();
        $model->update($id, $this->request->getPost());
        return redirect()->to('/valvulas');
    }

    public function view($id)
    {
        $model = new ValvulasModel();
        $data['registro'] = $model->find($id);
        return view('valvulas/view', $data);
    }

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

