<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\CriteriaData;
use App\Models\ReferensiAlternatif;
use App\Models\SubDistrictAlternatif;
use App\Models\Village;
use App\Models\VillageAlternatif;
use Illuminate\Http\Request;

class ListDataKriteriaController extends Controller
{
    public function index()
    {
        return view('website.app.list-data-kriteria');
    }

    public function getListCriteriaData()
    {
        $listCriteriaData = CriteriaData::select('id', 'criteria', 'bobot', 'status')->get();

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

    public function addCriteria(Request $request)
    {
        $request->validate([
            'criteria' => 'required|string|max:255',
            'bobot' => 'required|integer|min:1|max:5',
            'keterangan' => 'required|in:benefit,cost',
        ]);

        CriteriaData::create([
            'criteria' => $request->input('criteria'),
            'bobot' => $request->input('bobot'),
            'status' => $request->input('keterangan'),
        ]);
        toast('Data kriteria berhasil ditambahkan!', 'success');
        return redirect()->back();
    }

    public function updateCriteria(Request $request)
    {
        $criteriaById = CriteriaData::find($request->input('criteria_id'));

        $criteriaById['criteria'] = $request->input('criteria');
        $criteriaById['bobot'] = $request->input('bobot');
        $criteriaById['status'] = $request->input('keterangan');

        $criteriaById->save();
        toast('Data kriteria berhasil diubah', 'success');
        return redirect()->back();
    }

    public  function deleteCriteria($id)
    {
        $criteriaById = CriteriaData::find($id);

        $referensiAlternatifs = ReferensiAlternatif::where('criteria_id', '=', $id)->get();
        $subDistrictAlternatifs = SubDistrictAlternatif::where('criteria_id', '=', $id)->get();
        $villageAlternatifs = VillageAlternatif::where('criteria_id', '=', $id)->get();

        // hapus seluruh criteria id yang diambil di tabel referensi alternatifs
        foreach ($referensiAlternatifs as $value) {
            $value->delete();
        }

        // hapus seluruh criteria id yang diambil di tabel sub district alternatif
        foreach ($subDistrictAlternatifs as $value) {
            $value->delete();
        }

        // hapus seluruh criteria id yang diambil di tabel village alternatif
        foreach ($villageAlternatifs as $value) {
            $value->delete();
        }

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