<?php

namespace App\Http\Controllers;

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

class VesselController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $vessels = Vessel::withCount('records')->orderBy('name')->get();
        return view('vessels.index', compact('vessels'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('vessels.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:100|unique:vessels,name',
        ]);

        Vessel::create([
            'name' => $request->name,
            'created_by' => auth()->id(),
        ]);

        return redirect()->route('vessels.index')->with('success', 'Vessel created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Vessel $vessel)
    {
        $vessel->load(['records.status', 'records.attachments']);
        return view('vessels.show', compact('vessel'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Vessel $vessel)
    {
        return view('vessels.edit', compact('vessel'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Vessel $vessel)
    {
        $request->validate([
            'name' => 'required|string|max:100|unique:vessels,name,' . $vessel->id,
        ]);

        $vessel->update([
            'name' => $request->name,
        ]);

        return redirect()->route('vessels.index')->with('success', 'Vessel updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Vessel $vessel)
    {
        $vessel->delete();
        return redirect()->route('vessels.index')->with('success', 'Vessel deleted successfully.');
    }
}
