<?php

namespace App\Http\Controllers;

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

class GrapeVarietyController extends Controller
{
    /**
     * Display a listing of grape varieties.
     */
    public function index()
    {
        $varieties = GrapeVariety::with('variations', 'wines')->paginate(15);

        return view('grape-varieties.index', compact('varieties'));
    }

    /**
     * Show the form for creating a new grape variety.
     */
    public function create()
    {
        return view('grape-varieties.create');
    }

    /**
     * Store a newly created grape variety in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'variety_name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'origin' => 'nullable|string|max:255',
            'wine_type' => 'nullable|in:red,white,rose',
            'characteristics' => 'nullable|string',
            'image_url' => 'nullable|url',
        ]);

        $variety = GrapeVariety::create($validated);

        return redirect()->route('grape-varieties.show', $variety)
            ->with('success', 'Grape variety created successfully.');
    }

    /**
     * Display the specified grape variety.
     */
    public function show(GrapeVariety $grapeVariety)
    {
        $grapeVariety->load('variations', 'wines');

        return view('grape-varieties.show', compact('grapeVariety'));
    }

    /**
     * Show the form for editing the specified grape variety.
     */
    public function edit(GrapeVariety $grapeVariety)
    {
        return view('grape-varieties.edit', compact('grapeVariety'));
    }

    /**
     * Update the specified grape variety in storage.
     */
    public function update(Request $request, GrapeVariety $grapeVariety)
    {
        $validated = $request->validate([
            'variety_name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'origin' => 'nullable|string|max:255',
            'wine_type' => 'nullable|in:red,white,rose',
            'characteristics' => 'nullable|string',
            'image_url' => 'nullable|url',
        ]);

        $grapeVariety->update($validated);

        return redirect()->route('grape-varieties.show', $grapeVariety)
            ->with('success', 'Grape variety updated successfully.');
    }

    /**
     * Remove the specified grape variety from storage.
     */
    public function destroy(GrapeVariety $grapeVariety)
    {
        $grapeVariety->delete();

        return redirect()->route('grape-varieties.index')
            ->with('success', 'Grape variety deleted successfully.');
    }
}
