<?php

namespace App\Http\Controllers;

use App\Models\Tanque;
use App\Models\TipoCombustible;
use Illuminate\Http\Request;

class TanquesController extends Controller
{
    public function index()
    {
        $items = Tanque::with('tipoCombustible')->orderBy('id_tanque')->get();
        return view('tanques.index', compact('items'));
    }

    public function create()
    {
        $tipos = TipoCombustible::orderBy('nombre')->get();
        return view('tanques.create', compact('tipos'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'id_tipo_combustible' => 'required|integer',
            'nombre' => 'nullable|string|max:100',
            'capacidad' => 'required|numeric',
            'stock_actual' => 'required|numeric',
        ]);

        Tanque::create($data);

        return redirect()->route('tanques.index')->with('success', 'Tanque creado.');
    }

    public function edit(string $id)
    {
        $item = Tanque::findOrFail($id);
        $tipos = TipoCombustible::orderBy('nombre')->get();
        return view('tanques.edit', compact('item', 'tipos'));
    }

    public function update(Request $request, string $id)
    {
        $item = Tanque::findOrFail($id);

        $data = $request->validate([
            'id_tipo_combustible' => 'required|integer',
            'nombre' => 'nullable|string|max:100',
            'capacidad' => 'required|numeric',
            'stock_actual' => 'required|numeric',
        ]);

        $item->update($data);

        return redirect()->route('tanques.index')->with('success', 'Tanque actualizado.');
    }

    public function destroy(string $id)
    {
        $item = Tanque::findOrFail($id);
        $item->delete();
        return redirect()->route('tanques.index')->with('success', 'Tanque eliminado.');
    }
}

