<?php

namespace App\Http\Controllers;

use App\Models\Dinner;
use Illuminate\Http\Request;
use App\Models\Product;

class DinnerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'dinner' => 'required'
        ]);

        $product_list = collect([]);
        foreach ($request->dinner as $dinner) {
            $product = Product::where('name', $dinner)->first();
            if ($product) {
               $product_id = $product->id;
               $product_list->push($product_id);
               $dinner = Dinner::updateOrCreate(['product_id' => $product_id], ['status' => 'today']);
            }
        }

        $all_dinners  = Dinner::all();
        foreach ($all_dinners as $dinner) {
            if (!$product_list->contains($dinner->product_id)) {
                $dinner->delete();
            }
        }

        $products = Product::all()->load(['category']);
        $dinners = Dinner::all()->load(['product']);

        return response()->json([
            'status' => 'success',
            'message' => 'dinner was set successfully',
            'products' => $products,
            'dinners' => $dinners,
        ],200);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Dinner  $dinner
     * @return \Illuminate\Http\Response
     */
    public function show(Dinner $dinner)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Dinner  $dinner
     * @return \Illuminate\Http\Response
     */
    public function edit(Dinner $dinner)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Dinner  $dinner
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Dinner $dinner)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Dinner  $dinner
     * @return \Illuminate\Http\Response
     */
    public function destroy(Dinner $dinner)
    {
        //
    }
}
