<?php

namespace App\Http\Controllers;

use App\Models\Karyawan;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class KaryawanController extends Controller
{
    public function index()
    {
        $karyawan = Karyawan::latest()->get();
        $data = [
            'title' => 'Ramizah Store | Karyawan',
            'page' => 'Karyawan',
            'menuActive' => 'karyawan',
            'menuOpen' => 'karyawan',
        ];
        return view('admin.karyawan.karyawan', compact('data', 'karyawan'))->with('no', 1);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate(
            [
                'nm_karyawan' => 'required',
                'hp_karyawan' => 'required|unique:karyawans,hp_karyawan',
                'kelamin_karyawan' => 'required',
                'alamat_karyawan' => 'required',
            ],
            [
                'required' => 'Form wajib diisi!',
                'unique' => 'No HP sudah pernah diinputkan, silahkan input No lain!',
            ]
        );

        Karyawan::create([
            'nm_karyawan' => $request->nm_karyawan,
            'hp_karyawan' => $request->hp_karyawan,
            'kelamin_karyawan' => $request->kelamin_karyawan,
            'alamat_karyawan' => $request->alamat_karyawan,
        ]);

        return redirect()->route('karyawan.index')->with(['success' => 'Data Berhasil Disimpan!']);
    }

    public function update(Request $request): RedirectResponse
    {

        if ($request->hplama != $request->hp_karyawan) {
            $rule = 'required|unique:karyawans,hp_karyawan';
        } else {
            $rule = 'required';
        }

        $request->validate(
            [
                'nm_karyawan' => 'required',
                'hp_karyawan' => $rule,
                'kelamin_karyawan' => 'required',
                'alamat_karyawan' => 'required',
            ],
            [
                'required' => 'Form wajib diisi!',
                'unique' => 'No HP sudah pernah diinputkan, silahkan input No lain!',
            ]
        );

        $id = $request->id;

        $karyawan = Karyawan::findOrFail($id);

        $karyawan->update([
            'nm_karyawan' => $request->nm_karyawan,
            'hp_karyawan' => $request->hp_karyawan,
            'kelamin_karyawan' => $request->kelamin_karyawan,
            'alamat_karyawan' => $request->alamat_karyawan,
        ]);

        return redirect()->route('karyawan.index')->with(['success' => 'Edit Data Berhasil Disimpan!']);
    }

    public function destroy($id)
    {
        Karyawan::findOrFail($id)->delete();
        return redirect()->route('karyawan.index')->with(['success' => 'Data Berhasil Dihapus!']);
    }
}
