<?php

namespace App\Http\Controllers;

use App\Models\MetroNode;
use Illuminate\Http\Request;

class MetroNodeController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'metro_line_id' => 'required|exists:metro_lines,id',
            'naam'          => 'required|string|max:255',
            'beschrijving'  => 'nullable|string',
            'x'             => 'required|integer',
            'y'             => 'required|integer',
            'eigenaar_id'   => 'nullable|exists:users,id',
        ]);

        $maxOrder = MetroNode::where('metro_line_id', $validated['metro_line_id'])->max('order') ?? 0;
        $validated['order'] = $maxOrder + 1;
        $validated['status'] = 'active';

        $node = MetroNode::create($validated);

        return back()->with('success', "Node '{$node->naam}' aangemaakt.");
    }

    public function update(Request $request, MetroNode $metroNode)
    {
        $validated = $request->validate([
            'naam'         => 'sometimes|string|max:255',
            'beschrijving' => 'nullable|string',
            'status'       => 'sometimes|string|in:active,completed,parked',
            'x'            => 'sometimes|integer',
            'y'            => 'sometimes|integer',
        ]);

        $metroNode->update($validated);

        return back()->with('success', 'Node bijgewerkt.');
    }

    public function destroy(MetroNode $metroNode)
    {
        $metroNode->delete();

        return back()->with('success', 'Node verwijderd.');
    }
}
