<?php

namespace App\Http\Controllers;

use App\Models\BarangRusak;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class AdminBarangRusakController extends Controller
{
    public function index(Request $request)
    {
        $query = BarangRusak::with('user')
            ->orderByDesc('tanggal')
            ->orderByDesc('created_at');

        // Search by user name
        if ($request->has('q') && !empty($request->q)) {
            $search = $request->q;
            $query->whereHas('user', function($userQuery) use ($search) {
                $userQuery->where('name', 'like', "%{$search}%");
            });
        }

        $items = $query->paginate(15);

        return view('admin.barang-rusak.index', [
            'title' => 'Laporan Barang Rusak',
            'items' => $items,
            'q' => $request->q ?? '',
            'statusOptions' => $this->statusOptions(),
            'editingId' => old('barang_rusak_id'),
        ]);
    }

    public function update(Request $request, BarangRusak $barangRusak)
    {
        $statusOptions = array_keys($this->statusOptions());

        $validated = $request->validate([
            'status' => ['required', 'string', Rule::in($statusOptions)],
            'admin_note' => ['nullable', 'string', 'max:2000'],
            'barang_rusak_id' => ['nullable', 'integer'],
        ]);

        $barangRusak->update([
            'status' => $validated['status'],
            'admin_note' => $validated['admin_note'] ?? null,
        ]);

        return back()->with('success', 'Catatan admin berhasil diperbarui.');
    }

    public function destroy(BarangRusak $barangRusak)
    {
        $barangRusak->delete();

        return back()->with('success', 'Laporan barang rusak berhasil dihapus.');
    }

    protected function statusOptions(): array
    {
        return [
            'dilaporkan' => 'Dilaporkan',
            'diproses' => 'Diproses',
            'selesai' => 'Selesai',
            'dibatalkan' => 'Dibatalkan',
        ];
    }
}
