<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Plant;
use App\Models\PreferenceResultPlant;
use App\Models\ReferensiAlternatif;
use Illuminate\Http\Request;

class PlantController extends Controller
{
    public function index()
    {
        return view('website.app.list-plant');
    }

    public function getListPlantData()
    {
        $listPlantData = Plant::all();

        return response()->json([
            'listPlantData' => $listPlantData,
        ]);
    }

    public function addPlant(Request $request)
    {
        $request->validate([
            'plant' => 'required|string|max:255|unique:plants,plant',
        ]);

        Plant::create([
            'plant' => $request->input('plant'),
        ]);
        toast('Data tanaman berhasil ditambahkan!', 'success');
        return redirect()->back();
    }

    // public function updatePlant(Request $request)
    // {
    //     $plantById = Plant::find($request->input('plant_id'));

    //     $plantById['plant'] = $request->input('plant');

    //     $plantById->save();
    //     toast('Data tanaman berhasil diubah', 'success');
    //     return redirect()->back();
    // }

    public  function deletePlant($id)
    {
        $plantById = Plant::find($id);

        $referensiAlternatif = ReferensiAlternatif::where('plant_id', '=', $id)->get();
        $preferenceResultPlant = PreferenceResultPlant::where('plant_id', '=', $id)->get();

        // hapus seluruh referensi alternatif dengan plant_id
        foreach ($referensiAlternatif as $key => $value) {
            $value->delete();
        }

        // hapus seluruh hasil preferensi dengan plant_id
        foreach ($preferenceResultPlant as $key => $value) {
            $value->delete();
        }

        // hapus tanaman
        $plantById->delete();
        toast('Data tanaman berhasil dihapus', 'success');
        return redirect()->back();
    }
}
