<?php

namespace App\Http\Controllers;

use App\Models\Letter;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class OfficerLetterController extends Controller
{
    public function index(Request $request): View
    {
        $query = Letter::query()->orderByDesc('tarikh_surat')->orderByDesc('id');

        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('nombor_surat', 'like', '%' . $search . '%')
                    ->orWhere('nama_surat', 'like', '%' . $search . '%');
            });
        }

        if ($jenis = $request->get('jenis')) {
            $query->where('jenis', $jenis);
        }

        $letters = $query->paginate(20)->withQueryString();

        return view('officer.letters.index', compact('letters'));
    }

    public function create(): View
    {
        return view('officer.letters.form', [
            'letter' => new Letter(),
            'mode' => 'create',
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'nombor_surat' => ['required', 'string', 'max:80'],
            'nama_surat' => ['required', 'string', 'max:255'],
            'jenis' => ['required', 'in:masuk,keluar'],
            'tarikh_surat' => ['required', 'date'],
            'created_by' => ['nullable', 'string', 'max:120'],
        ]);

        Letter::create($data);

        return redirect()->route('officer.letters.index')
            ->with('status', 'Rekod surat berjaya disimpan.');
    }
}
