<?php

namespace App\Http\Controllers\MasterData;

use App\Http\Controllers\Controller;
use App\Models\Rule;
use Barryvdh\Debugbar\Facades\Debugbar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RuleController extends Controller
{
    public function index()
    {
        $rules = Rule::with('indicator')->get();
        Debugbar::info($rules);
        return view('master-data.aturan.index', compact('rules'));
    }

    public function update(Request $request, $id)
    {
        $customMessage = [
            'range_min.required' => 'Nilai minimum wajib diisi',
            'range_min.numeric' => 'Nilai minimum harus berupa angka',

            'range_max.required' => 'Nilai maksimum wajib diisi',
            'range_max.numeric' => 'Nilai maksimum harus berupa angka',

            'mb.required' => 'Nilai MB wajib diisi',
            'mb.numeric' => 'Nilai MB harus berupa angka',

            'md.required' => 'Nilai MD wajib diisi',
            'md.numeric' => 'Nilai MD harus berupa angka',
        ];

        $validator = Validator::make($request->all(), [
            'range_min' => 'required|numeric',
            'range_max' => 'required|numeric',
            'mb' => 'required|numeric',
            'md' => 'required|numeric',
        ], $customMessage);

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

        $rule = Rule::find($id);
        $rule->range_min = $request->range_min;
        $rule->range_max = $request->range_max;
        $rule->mb = $request->mb;
        $rule->md = $request->md;

        try {
            $rule->save();
            toast('Berhasil mengubah aturan', 'success')->position('top-right')->autoclose(3000);
            return redirect()->back();
        } catch (\Throwable $th) {
            toast('Terjadi kesalahan', 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }
    }
}
