<?php

namespace App\Http\Controllers\Api\RT;

use App\Http\Controllers\Controller;
use App\Models\Surat;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SuratController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Surat::with('warga:id,nama,nik');

        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        if ($request->has('jenis_surat')) {
            $query->where('jenis_surat', $request->jenis_surat);
        }

        if ($request->has('warga_id')) {
            $query->where('warga_id', $request->warga_id);
        }

        $surats = $query->orderBy('tanggal_surat', 'desc')->paginate(20);

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

    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'jenis_surat' => 'required|in:Pengantar KTP,Pengantar KK,Keterangan Domisili,Keterangan Usaha,Keterangan Tidak Mampu,Keterangan Kelahiran,Keterangan Kematian,Lainnya',
            'warga_id' => 'required|exists:wargas,id',
            'tanggal_surat' => 'required|date',
            'keperluan' => 'required|string',
            'keterangan' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        // Generate nomor surat
        $lastSurat = Surat::whereYear('tanggal_surat', date('Y'))->latest('id')->first();
        $urutan = $lastSurat ? (int)substr($lastSurat->nomor_surat, 0, 3) + 1 : 1;
        $nomorSurat = sprintf('%03d/RT/SKT/%s', $urutan, date('Y'));

        $surat = Surat::create([
            ...$request->all(),
            'nomor_surat' => $nomorSurat,
            'user_id' => auth()->id()
        ]);

        return response()->json([
            'message' => 'Surat berhasil dibuat',
            'data' => $surat->load('warga:id,nama,nik')
        ], 201);
    }

    public function show(Surat $surat): JsonResponse
    {
        return response()->json([
            'data' => $surat->load('warga', 'user:id,name')
        ]);
    }

    public function update(Request $request, Surat $surat): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'status' => 'required|in:Pending,Disetujui,Ditolak',
            'keterangan' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $surat->update($request->all());

        return response()->json([
            'message' => 'Status surat berhasil diupdate',
            'data' => $surat
        ]);
    }

    public function destroy(Surat $surat): JsonResponse
    {
        $surat->delete();

        return response()->json([
            'message' => 'Surat berhasil dihapus'
        ]);
    }

    public function generateNomor(): JsonResponse
    {
        $lastSurat = Surat::whereYear('tanggal_surat', date('Y'))->latest('id')->first();
        $urutan = $lastSurat ? (int)substr($lastSurat->nomor_surat, 0, 3) + 1 : 1;
        $nomorSurat = sprintf('%03d/RT/SKT/%s', $urutan, date('Y'));

        return response()->json([
            'nomor_surat' => $nomorSurat
        ]);
    }
}
