<?php

namespace App\Http\Controllers;

use App\Models\DataObat;
use App\Models\DataVaksin;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class DataVaksinController extends Controller
{
    public function index()
    {
        return view('pages.data_vaksin.index', [
            "title" => "Data Obat",
            "heading" => "Data Obat",
            'dataVaksin' => DataObat::all()
        ]);
    }
    public function create()
    {
        return view('pages.data_vaksin.action.tambah', [
            "title" => "Tambah Data Obat",
            "heading" => "Tambah Data Obat",
        ]);
    }


    public function store(Request $request)
    {
        $customMessages = [
            'required' => 'Kolom :attribute wajib diisi.',
            'min' => 'Kolom :attribute minimal harus :min karakter.',
            'max' => 'Kolom :attribute maksimal harus :max karakter.',
            'unique' => 'Nama obat tersebut sudah terdaftar',
        ];

        $validatedData = $request->validate([
            'nama_obat' => 'required|min:3|max:255|unique:data_obat,nama_obat',
            'jenis_obat' => 'required|min:3|max:255',
            'keterangan_obat' => 'required|min:3',

        ], $customMessages);

        DataObat::create($validatedData);
        return redirect('/data_obat')->with('success', 'Data obat Berhasil Ditambah');
    }

    public function edit($id)
    {
        $data = DataObat::findOrFail($id);

        return view('pages.data_vaksin.action.edit', [
            "title" => "Edit Data Obat",
            "heading" => "Edit Data Obat " . $data->nama_obat,
            "data" => $data
        ]);
    }

    public function update(Request $request, $id)
    {
        $data = DataObat::find($id);

        $customMessages = [
            'required' => 'Kolom :attribute wajib diisi.',
            'min' => 'Kolom :attribute maksimal harus :min karakter.',
            'max' => 'Kolom :attribute maksimal harus :max karakter.',
        ];

        $validatedData = $request->validate([
            'nama_obat' => 'required|min:3|max:255',
            'jenis_obat' => 'required|min:3|max:255',
            'keterangan_obat' => 'required|min:3',
        ], $customMessages);

        DataObat::where('id', $data->id)
            ->update($validatedData);

        return redirect('/data_obat')->with('success', 'Data obat berhasil di Update');
    }

    public function destroy($id)
    {
        $data = DataObat::findOrFail($id);

        DataObat::where('id', $data->id)->delete();

        return redirect('/data_obat')->with('success', 'Data Berhasil Dihapus');
    }
}
