<?php

namespace App\Http\Controllers\MasterData;

use App\Http\Controllers\Controller;
use App\Models\Indicator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class IndicatorController extends Controller
{
    public function index()
    {
        $indicators = Indicator::all();
        return view('master-data.indikator.index', compact('indicators'));
    }

    public function update(Request $request, $id)
    {
        $customMessage = [
            "name.required" => "Nama wajib diisi",
            "name.max" => "Nama maksimal 255 karakter",
            "name.string" => "Nama harus berupa string",

            "description.required" => "Deskripsi wajib diisi",
            "description.max" => "Deskripsi maksimal 255 karakter",
            "description.string" => "Deskripsi harus berupa string",

            "ideal_min.required" => "Nilai ideal minimum wajib diisi",
            "ideal_min.numeric" => "Nilai ideal minimum harus berupa angka",

            "ideal_max.required" => "Nilai ideal maksimum wajib diisi",
            "ideal_max.numeric" => "Nilai ideal maksimum harus berupa angka",

            "unit.required" => "Unit wajib diisi",
            "unit.max" => "Unit maksimal 255 karakter",
            "unit.string" => "Unit harus berupa string",
        ];

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'required|string|max:255',
            'ideal_min' => 'required|numeric',
            'ideal_max' => 'required|numeric',
            'unit' => 'required|string|max:255',
        ], $customMessage);

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

        $indicator = Indicator::find($id);
        $indicator->name = $request->name;
        $indicator->description = $request->description;
        $indicator->ideal_min = $request->ideal_min;
        $indicator->ideal_max = $request->ideal_max;
        $indicator->unit = $request->unit;

        try {
            $indicator->save();
            toast('Data berhasil diubah', 'success')->position('top-right')->autoclose(3000);
            return redirect()->back();
        } catch (\Throwable $th) {
            toast('Terjadi kesalahan', 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }
    }
}
