<?php

namespace App\Http\Controllers\Admin\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Pegawai;
use App\Models\UnitKerja;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class UnitKerjaController extends Controller
{
    public function index(Request $request)
    {
        $query = UnitKerja::query()
            ->select('unit_kerja.*')
            ->selectSub(function ($query) {
                $query->from('pegawai')
                    ->selectRaw('COUNT(*)')
                    ->whereColumn('pegawai.unit_kerja', 'unit_kerja.nama_unit')
                    ->where('pegawai.status_validasi', 'disetujui');
            }, 'pegawai_count');

        if ($request->filled('search')) {
            $query->where('nama_unit', 'like', '%' . $request->search . '%');
        }

        $unitKerja = $query->orderBy('nama_unit')->paginate(15)->withQueryString();

        return view('admin.unit-kerja.index', compact('unitKerja'));
    }

    public function create()
    {
        return view('admin.unit-kerja.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'nama_unit' => ['required', 'string', 'max:255', Rule::unique('unit_kerja', 'nama_unit')],
        ]);

        UnitKerja::create($validated);

        return redirect()->route('admin.unit-kerja.index')
            ->with('success', 'Unit kerja berhasil ditambahkan.');
    }

    public function edit(UnitKerja $unitKerja)
    {
        return view('admin.unit-kerja.edit', compact('unitKerja'));
    }

    public function update(Request $request, UnitKerja $unitKerja)
    {
        $validated = $request->validate([
            'nama_unit' => [
                'required',
                'string',
                'max:255',
                Rule::unique('unit_kerja', 'nama_unit')->ignore($unitKerja->id),
            ],
        ]);

        $namaUnitLama = $unitKerja->nama_unit;
        $unitKerja->update($validated);

        Pegawai::where('unit_kerja', $namaUnitLama)
            ->update(['unit_kerja' => $validated['nama_unit']]);

        return redirect()->route('admin.unit-kerja.index')
            ->with('success', 'Unit kerja berhasil diperbarui.');
    }

    public function destroy(UnitKerja $unitKerja)
    {
        if (Pegawai::where('unit_kerja', $unitKerja->nama_unit)->exists()) {
            return back()->with('error', 'Tidak dapat menghapus unit kerja yang masih digunakan pegawai.');
        }

        if (User::where('unit_kerja_id', $unitKerja->id)->exists()) {
            return back()->with('error', 'Tidak dapat menghapus unit kerja yang masih digunakan admin.');
        }

        $unitKerja->delete();

        return redirect()->route('admin.unit-kerja.index')
            ->with('success', 'Unit kerja berhasil dihapus.');
    }
}
