<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Wilayah\DesaKelurahan;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use App\Http\Resources\Wilayah\DesaKelurahanResource;
use App\Http\Resources\Wilayah\DesaKelurahanCollectionResource;

class DesaKelurahanController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): AnonymousResourceCollection
    {
        $size = $request->integer('size') ?: 10;

        $master = DesaKelurahan::with('kecamatan')
            ->when($request->search, function ($q, $search) {
                $search = strtolower($search);
                $q->where(function ($query) use ($search) {
                    $query->whereRaw('lower(kode) like ?', ["%{$search}%"])
                        ->orWhereRaw('lower(nama) like ?', ["%{$search}%"]);
                });
            })
            ->when($request->kecamatan_id, fn($q,$v) => $q->where('kecamatan_id',$v))
            ->when($request->kabupaten_kota_id, fn ($q, $v) =>
                $q->whereHas('kecamatan', fn ($k) =>
                    $k->where('kabupaten_kota_id', $v)
                )
            )
            ->when($request->provinsi_id, fn ($q, $v) =>
                $q->whereHas('kecamatan.kabupatenkota', fn ($k) =>
                    $k->where('provinsi_id', $v)
                )
            );

        if ($request->filled('sort')) {
            $dir = str_starts_with($request->sort, '-') ? 'desc' : 'asc';
            $column = ltrim($request->sort, '-');

            $allowed = ['id', 'kode', 'nama'];

            if (in_array($column, $allowed)) {
                $master->orderBy($column, $dir);
            }
        } else {
            $master->orderBy('kode', 'asc');
        }

        $masterList = $master->paginate($size);

        return DesaKelurahanResource::collection($masterList);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id): JsonResponse
    {
        return response()->json(DesaKelurahanResource::make(DesaKelurahan::with('kecamatan')->findOrFail($id)));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
