<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Wilayah\Kecamatan;
use Illuminate\Http\JsonResponse;

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

        $master = Kecamatan::query();

        if ($request->has('search')) {
            $s = $request->get('search');
            $s = strtolower($s);
            $master->where(function($query) use ($s) {
                $query->whereRaw('lower(kode) like (?)',["%{$s}%"])
                    ->orWhereRaw('lower(nama) like (?)',["%{$s}%"]);
            });
        }
        if ($request->has('sort')) {
            $order = $request->get('sort');
            $d = substr($order, 0, 1);
            $dir = $d === '-' ? 'desc' : 'asc'; 
            $order = $d === '-' ? substr($order, 1) : $order;
            $master->orderBy($order, $dir);
        }
        if ($request->has('kabupaten_kota_id')) {
            $master->where('kabupaten_kota_id', $request->get('kabupaten_kota_id'));
        }

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

        return response()->json($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(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)
    {
        //
    }
}
