<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\KodeAksesKantor;
use App\Models\UnitKerja;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class KodeAksesKantorController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->user();
        $query = KodeAksesKantor::with(['unitKerja', 'pembuat'])->latest();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('kode', 'like', "%{$search}%")
                  ->orWhereHas('unitKerja', function ($q) use ($search) {
                      $q->where('nama_unit', 'like', "%{$search}%");
                  });
        }

        return view('admin.kode-akses-kantor.index', [
            'kodeAkses' => $query->paginate(15)->withQueryString(),
            'unitKerjaList' => UnitKerja::orderBy('nama_unit')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $user = auth()->user();
        $validated = $request->validate([
            'unit_kerja_id' => [
                'required',
                'integer',
                Rule::exists('unit_kerja', 'id'),
            ],
            'kode' => ['nullable', 'string', 'min:6', 'max:32', 'alpha_dash', Rule::unique('kode_akses_kantor', 'kode')],
            'batas_penggunaan' => ['required', 'integer', 'min:1', 'max:10000'],
            'kedaluwarsa_pada' => ['required', 'date', 'after:now'],
        ]);

        KodeAksesKantor::create([
            'unit_kerja_id' => $validated['unit_kerja_id'],
            'created_by' => $user->id,
            'kode' => $validated['kode']
                ? Str::upper($validated['kode'])
                : $this->generateUniqueCode(),
            'batas_penggunaan' => $validated['batas_penggunaan'],
            'kedaluwarsa_pada' => $validated['kedaluwarsa_pada'],
            'aktif' => true,
        ]);

        return back()->with('success', 'Kode kantor berhasil dibuat.');
    }

    public function toggle(KodeAksesKantor $kodeAksesKantor)
    {
        $this->authorizeAccess($kodeAksesKantor);
        $kodeAksesKantor->update(['aktif' => ! $kodeAksesKantor->aktif]);

        return back()->with('success', 'Status kode kantor berhasil diperbarui.');
    }

    public function destroy(KodeAksesKantor $kodeAksesKantor)
    {
        $this->authorizeAccess($kodeAksesKantor);
        $kodeAksesKantor->delete();

        return back()->with('success', 'Kode kantor berhasil dihapus.');
    }

    private function authorizeAccess(KodeAksesKantor $kodeAksesKantor): void
    {
        abort_unless(auth()->check() && auth()->user()->isAdmin(), 403);
    }

    private function generateUniqueCode(): string
    {
        do {
            $code = 'SKB-' . Str::upper(Str::random(8));
        } while (KodeAksesKantor::where('kode', $code)->exists());

        return $code;
    }
}
