<?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;

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

        $master = KabupatenKota::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('provinsi_id')) {
            $master->where('provinsi_id', $request->get('provinsi_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)
    {
        return response()->json(KabupatenKota::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)
    {
        //
    }
}
