<?php

namespace App\Http\Controllers;

use App\Models\Departemen;
use Yajra\DataTables\Facades\DataTables;
use App\Http\Requests\StoreDepartemenRequest;
use App\Http\Requests\UpdateDepartemenRequest;

class DepartemenController extends Controller
{
    public function getData()
    {
        $data = Departemen::orderByDesc('created_at');
        return DataTables::of($data)
            ->addIndexColumn()
            ->make(true);
    }

    public function index()
    {
        return view('menu.departemen.index');
    }

    public function store(StoreDepartemenRequest $request)
    {
        $rules = [
            'departemen' => 'required|unique:departemens,departemen,' . $request->id
        ];
        $validateData = $request->validate($rules, [
            'departemen.required' => 'Maaf, departemen tidak boleh kosong,',
            'departemen.unique' => 'Maaf, Data departemen sudah ada,',
        ]);

        $data = Departemen::where('departemen', '')->get();
        if (isset($data[0])) {
            Departemen::where('id', $data[0]->id)
                ->update(['departemen' => $request->departemen]);
        } else {
            Departemen::create([
                'kategori' => '',
                'departemen' => $request->departemen
            ]);
        }
        return redirect('/departemen')->with('success', 'departemen Baru Berhasil ditambahkan!');
    }

    public function update(UpdateDepartemenRequest $request, Departemen $departemen)
    {
        $departemen->update([
            'departemen' => $request->departemen
        ]);

        return redirect()
            ->route('departemen.index')
            ->with('success', 'departemen berhasil diubah!');
    }
    public function show($id)
    {
        $departemen = Departemen::find($id);

        if (!$departemen) {
            return response()->json(['message' => 'Data tidak ditemukan'], 404);
        }

        return response()->json($departemen);
    }

    public function destroy($id)
    {
        Departemen::findOrFail($id)->delete();

        return redirect()
            ->route('departemen.index')
            ->with('success', 'departemen berhasil dihapus.');
    }
}
