<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\Wilayah\Provinsi;
use App\Models\Wilayah\KabupatenKota;
use App\Http\Resources\Wilayah\KabupatenKotaResource;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

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

        $master = KabupatenKota::with('provinsi')
            ->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->provinsi_id, fn($q,$v) => $q->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 KabupatenKotaResource::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(KabupatenKotaResource::make(KabupatenKota::with('provinsi')->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)
    {
        //
    }
}
