<?php

namespace App\Controllers\Api;

use App\Models\RewarderCityModel;
use CodeIgniter\HTTP\ResponseInterface;

class Lookups extends BaseApiController
{
    public function index(): ResponseInterface
    {
        $cities = (new RewarderCityModel())->activeOptionList();

        $popularCityRows = db_connect()->table('rewarder_cities')
            ->select('id, name')
            ->where('status', 1)
            ->where('populercity', 1)
            ->orderBy('name', 'ASC')
            ->limit(12)
            ->get()
            ->getResult();
        $popularCities = array_values(array_map(static function ($r) {
            return (object) ['id' => (int) $r->id, 'label' => (string) $r->name];
        }, $popularCityRows));

        $categoryRows = db_connect()->table('rewarder_shop_categories')
            ->select('id, name, img_type')
            ->where('status', 1)
            ->orderBy('name', 'ASC')
            ->limit(200)
            ->get()
            ->getResult();
        $categories = array_values(array_map(static function ($r) {
            $iconUrl = !empty($r->img_type)
                ? urlUpload('shop_categories/' . (int) $r->id . '.' . $r->img_type, false)
                : admin_assets('img/default-150x150.png');

            return (object) [
                'id' => (int) $r->id,
                'name' => (string) $r->name,
                'img_type' => (string) ($r->img_type ?? ''),
                'icon_url' => (string) $iconUrl,
            ];
        }, $categoryRows));

        return $this->ok([
            'cities' => $cities,
            'popular_cities' => $popularCities,
            'shop_categories' => $categories,
        ]);
    }
}
