<?php

namespace App\Http\Controllers\Api\Platform;

use App\Http\Controllers\Controller;
use App\Models\City;
use App\RequestRules\Api\CityRules;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use PragmaRX\Countries\Package\Countries;
use PragmaRX\Countries\Package\Services\Config;

class CityController extends Controller
{
    /**
     * Create city
     *
     * @param Request $request
     * @return Application|ResponseFactory|Response
     */
    public function create(Request $request): Response|Application|ResponseFactory
    {
        $request->validate(CityRules::create());
        $data = $request->all();
        try {
            $city = City::createCity($data);

            return api_response(100, 'Ok', $city);
        } catch (\Exception $exception) {

            log_debug(exception: $exception, prefix: 'CityController::create');
        }

        return api_response(101, __('errors.unknown_error'));
    }

    /**
     * Get cities by country
     *
     * @param Request $request
     * @return Application|ResponseFactory|Response
     */
    public function getByCountry(Request $request): Response|Application|ResponseFactory
    {
        $request->validate(CityRules::getByCountry());

        try {
            $cities = City::getByCountry($request->get("country_id"));

            return api_response(100, 'Ok', $cities);
        } catch (\Exception $exception) {
            log_debug(exception: $exception, prefix: 'CityController::getByCountry');
        }
        return api_response(101, __('errors.unknown_error'));
    }

    /**
     * Get raw cities by country code
     *
     * @param Request $request
     * @return Response|Application|ResponseFactory
     */
    public function getRawCitiesByCountry(Request $request): Response|Application|ResponseFactory
    {
        $countryCode = $request->{'country_code'};
        $result = [];

        if(filled($countryCode)) {
            $countriesConfig = new Countries(new Config([]));
            $nativeCities =
                $countriesConfig
                    ->where('cca2', mb_strtoupper($countryCode))
                    ->first()
                    ->hydrate('cities')
                    ->{'cities'};

            foreach ($nativeCities as $city) {
                if(is_array($city) && isset($city['name'])) {
                    $result[] = $city['name'];
                }
            }
        }

        return api_response(100, "Okay", $result);
    }
}
