<?php

namespace App\Http\Controllers;

use App\Models\Evaluation;
use App\Models\EvaluationDetail;
use App\Models\Indicator;
use App\Models\Land;
use App\Models\Rule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class AssesmentFormController extends Controller
{
    public function index()
    {
        $lands = Land::select('id', 'owner')->whereNotIn('id', function ($query) {
            $query->select('land_id')->from('evaluation');
        })->orderBy('created_at', 'desc')->get();
        $indicators = Indicator::select('id', 'name')->whereIn('id', function ($query) {
            $query->select('indicator_id')->from('rule');
        })->get();
        return view('assessment.form', compact('lands', 'indicators'));
    }

    public function store(Request $request)
    {
        $customMessages = [
            'land.required' => 'Lahan tidak boleh kosong',
            'land.exists' => 'Lahan tidak ditemukan',
        ];

        $validator = Validator::make($request->all(), [
            'land' => ['required', 'exists:land,id'],
        ], $customMessages);

        if ($validator->fails()) {
            toast($validator->messages()->all()[0], 'error')->position('top-right')->autoclose(3000);
            return redirect()->back()->withInput();
        }

        $indicators = $request->except('_token', 'land');
        if (count($indicators) == 0) {
            toast('Harap pilih jawaban untuk nilai indikator', 'error')->position('top-right')->autoclose(3000);
            return redirect()->back();
        }

        $rules = Rule::whereIn('indicator_id', array_keys($indicators))->get()->keyBy('indicator_id');

        $cfValue = [];
        foreach ($indicators as $id => $value) {
            if (isset($rules[$id])) {
                $rule = $rules[$id];
                $cfValue[$id] = $rule->mb * $value;
            } else {
                toast("Rule untuk indikator ID {$id} tidak ditemukan.", 'error')->position('top-right')->autoclose(3000);
                return redirect()->back();
            }
        }

        $cfCombine = array_shift($cfValue);

        foreach ($cfValue as $cf) {
            $cfCombine = $cfCombine + $cf * (1 - $cfCombine);
        }

        DB::beginTransaction();
        try {
            $evaluation = new Evaluation;
            $evaluation->land_id = $request->land;
            $evaluation->cf_value = $cfCombine;
            $evaluation->user_id = auth()->user()->id;
            $evaluation->save();

            foreach ($indicators as $id => $value) {
                $evaluationDetail = new EvaluationDetail();
                $evaluationDetail->evaluation_id = $evaluation->id;
                $evaluationDetail->indicator_id = $id;
                $evaluationDetail->md_value = $value;
                $evaluationDetail->save();
            }
            DB::commit();
            $presentase = round($cfCombine * 100, 2);
            toast('Data berhasil disimpan', 'success')->position('top-right')->autoclose(3000);
            return redirect()->back()->with('presentase', $presentase);
        } catch (\Throwable $th) {
            DB::rollBack();
            toast('Terjadi kesalahan', 'error')->position('top-right')->autoclose(3000);
            return redirect()->back();
        }
    }
}
