<?php

namespace App\Http\Controllers;

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

class MetroLineController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'project_id' => 'required|exists:projects,id',
            'naam'       => 'required|string|max:255',
            'color'      => 'nullable|string|max:7',
        ]);

        $maxOrder = MetroLine::where('project_id', $validated['project_id'])->max('order') ?? 0;

        $line = MetroLine::create([
            'project_id' => $validated['project_id'],
            'naam'       => $validated['naam'],
            'color'      => $validated['color'] ?? $this->nextColor($validated['project_id']),
            'type'       => 'custom',
            'order'      => $maxOrder + 1,
        ]);

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

    public function destroy(MetroLine $metroLine)
    {
        if ($metroLine->isBuiltIn()) {
            return back()->with('error', 'Ingebouwde lijnen kunnen niet verwijderd worden.');
        }

        $metroLine->delete();

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

    private function nextColor(int $projectId): string
    {
        $colors = ['#ff6b6b', '#ffd93d', '#6bcb77', '#4d96ff', '#ff8fab', '#a8dadc', '#e07a5f', '#81b29a'];
        $used = MetroLine::where('project_id', $projectId)->pluck('color')->toArray();

        foreach ($colors as $c) {
            if (!in_array($c, $used)) {
                return $c;
            }
        }

        return $colors[0];
    }
}
