<?php

namespace App\Http\Controllers;

use App\Models\Kriteria;
use App\Models\SubKriteria;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SubKriteriaController extends Controller
{
    public function index($kriteria_id)
    {
        $user = Auth::user();

        if (!$user || !in_array($user->role, ['super_admin', 'admin'])) {
            abort(403, 'Anda tidak punya akses.');
        }

        $kriteria = Kriteria::findOrFail($kriteria_id);
        $subkriteria = SubKriteria::where('kriteria_id', $kriteria_id)->get();

        return view('admin.subkriteria', [
            'kriteria' => $kriteria,
            'subkriteria' => $subkriteria,
            'title' => 'Sub-Kriteria - ' . $kriteria->nama_kriteria
        ]);
    }

    public function store(Request $request)
    {
        $user = Auth::user();

        if (!$user || !in_array($user->role, ['super_admin', 'admin'])) {
            abort(403, 'Anda tidak punya akses.');
        }

        $validated = $request->validate([
            'kriteria_id' => 'required|exists:data_kriterias,id',
            'nama_sub_kriteria' => 'required|string|max:255',
            'bobot' => 'required|numeric|between:1,4',
        ]);

        // Hitung jumlah subkriteria yang sudah ada untuk kriteria ini
        $jumlahSub = \App\Models\SubKriteria::where('kriteria_id', $request->kriteria_id)->count();

        if ($jumlahSub >= 4) {
            return redirect()->back()->with('error', 'Subkriteria maksimal hanya 4 untuk setiap kriteria.');
        }

        SubKriteria::create($validated);

        return redirect()->back()->with('success', 'Subkriteria berhasil ditambahkan.');
    }


    public function update(Request $request, $id)
    {
        $user = Auth::user();

        if (!$user || !in_array($user->role, ['super_admin', 'admin'])) {
            abort(403, 'Anda tidak punya akses.');
        }

        $request->validate([
            'nama_sub_kriteria' => 'required|string|max:255',
            'bobot' => 'required|numeric|between:1,4',
        ]);

        $subkriteria = SubKriteria::findOrFail($id);
        $subkriteria->update([
            'nama_sub_kriteria' => $request->nama_sub_kriteria,
            'bobot' => $request->bobot,
        ]);

        return redirect()->back()->with('success', 'Subkriteria berhasil diperbarui.');
    }


    public function destroy($id)
    {
        $user = Auth::user();

        if (!$user || !in_array($user->role, ['super_admin', 'admin'])) {
            abort(403, 'Anda tidak punya akses.');
        }

        $subkriteria = SubKriteria::findOrFail($id);
        $subkriteria->delete();

        return redirect()->route('admin.subkriteria.index', ['kriteria_id' => $subkriteria->kriteria_id])
                         ->with('success', 'Subkriteria berhasil dihapus');
    }
}
