<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Recipes;
use Illuminate\Support\Facades\Auth;

class RecipesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $recipes = Recipes::where('user_id', Auth::id())->get();
        return view('resep.resep', compact('recipes'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'category' => 'required|string|max:255',
            'ingredients' => 'required|string',
            'instructions' => 'required|string',
        ], [
            'title.required' => 'Judul tidak boleh kosong.',
            'category.required' => 'Kategori tidak boleh kosong.',
            'ingredients.required' => 'Bahan tidak boleh kosong.',
            'instructions.required' => 'Instruksi tidak boleh kosong.',
        ]);
    
        Recipes::create([
            'user_id' => Auth::id(),
            'title' => $request->title,
            'description' => $request->description,
            'category' => $request->category,
            'ingredients' => $request->ingredients,
            'instructions' => $request->instructions,
        ]);
    
        return redirect()->route('resep.index')->with('status', 'success')->with('message', 'Resep berhasil ditambahkan.');
    }
    
    public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'category' => 'required|string|max:255',
            'ingredients' => 'required|string',
            'instructions' => 'required|string',
        ], [
            'title.required' => 'Judul tidak boleh kosong.',
            'category.required' => 'Kategori tidak boleh kosong.',
            'ingredients.required' => 'Bahan tidak boleh kosong.',
            'instructions.required' => 'Instruksi tidak boleh kosong.',
        ]);
    
        $recipe = Recipes::findOrFail($id);
        $recipe->update([
            'title' => $request->title,
            'description' => $request->description,
            'category' => $request->category,
            'ingredients' => $request->ingredients,
            'instructions' => $request->instructions,
        ]);
    
        return redirect()->route('resep.index')->with('status', 'success')->with('message', 'Resep berhasil diperbarui.');
    }
    

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $recipe = Recipes::findOrFail($id);
        $recipe->delete();

        return redirect()->route('resep.index')->with('success', 'Resep berhasil dihapus.');
    }
}
