<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Ingredient;
use App\Models\IqImage;
use App\Models\ProductCategory;
use App\Models\ProductIngredient;
use Request;


class IngredientController extends Controller
{


    public function __construct()
    {
        $this->middleware('admin');
    }

    public function index()
    {

        $data = [
            'values' => Ingredient::all(),
        ];
        return view('admin.ingredient.index', $data);
    }

    public function edit($id)
    {
        if($id === "new"){
            $model = new Ingredient();
            $model->active = true;
        }else{
            $model = Ingredient::findOrFail($id);
        }
        $data = [
            'model' => $model,
            //'trans' => array_keys(config('localization.supportedLocales')),

        ];
        return view('admin.ingredient.edit', $data);
    }

    public function store()
    {

        $data = Request::all();
        $data['active'] = isset($data['active']) ? true : false;
        if($data['id'] === "new"){
            $model = Ingredient::create($data);
        }else{
            $model = Ingredient::find($data['id']);
            $model->fill($data)->save();
        }

        \Session()->flash('alert-save', '1');
        return redirect(route('admin_product_ingredients'));


    }

    public function delete($id){

        if(ProductIngredient::where('ingredient_id', $id)->count()) {
            \Session()->flash('alert-error', 'Eintrag wird als Produkt-Inhaltsstoff verwendet');
            return redirect(route('admin_product_ingredients'));
        }
        $model = Ingredient::findOrFail($id);
        $model->delete();
        \Session()->flash('alert-success', 'Eintrag gelöscht');
        return redirect(route('admin_product_ingredients'));
    }


}