<?php
namespace Core\App\Support;

class DzLocation
{
    private static function statesPath(): string
    {
        return ROOT_PATH . '/storage/data/states_dz.json';
    }

    private static function citiesPath(): string
    {
        return ROOT_PATH . '/storage/data/cities_dz.json';
    }

    public static function normalizeCode($code): string
    {
        $code = trim((string)$code);
        if ($code === '') return '';
        $digits = preg_replace('/\D+/', '', $code);
        if ($digits === '') return '';
        return str_pad($digits, 2, '0', STR_PAD_LEFT);
    }

    public static function states(): array
    {
        $path = self::statesPath();
        if (!is_file($path)) return [];
        $data = json_decode((string)file_get_contents($path), true);
        return is_array($data['states'] ?? null) ? $data['states'] : [];
    }

    public static function citiesByCode($code): array
    {
        $path = self::citiesPath();
        if (!is_file($path)) return [];
        $data = json_decode((string)file_get_contents($path), true);
        $code = self::normalizeCode($code);
        return is_array($data[$code] ?? null) ? $data[$code] : [];
    }


    public static function stateByCode($code): ?array
    {
        return self::findState($code);
    }

    public static function stateByName(string $name): ?array
    {
        $needle = trim(mb_strtolower($name));
        if ($needle === '') return null;
        foreach (self::states() as $state) {
            foreach (['name', 'ar_name', 'code'] as $field) {
                $val = trim(mb_strtolower((string)($state[$field] ?? '')));
                if ($val !== '' && $val === $needle) {
                    return $state;
                }
            }
        }
        return null;
    }

    public static function findState($code): ?array
    {
        $code = self::normalizeCode($code);
        foreach (self::states() as $state) {
            if (self::normalizeCode($state['code'] ?? '') === $code) {
                return $state;
            }
        }
        return null;
    }

    public static function findCityById($stateCode, $cityId): ?array
    {
        $cityId = (int)$cityId;
        if ($cityId <= 0) return null;
        foreach (self::citiesByCode($stateCode) as $city) {
            if ((int)($city['id'] ?? 0) === $cityId) {
                return $city;
            }
        }
        return null;
    }

    public static function findCityByName($stateCode, string $name): ?array
    {
        $needle = trim(mb_strtolower($name));
        if ($needle === '') return null;
        foreach (self::citiesByCode($stateCode) as $city) {
            foreach (['name','ar_name'] as $field) {
                $value = trim(mb_strtolower((string)($city[$field] ?? '')));
                if ($value !== '' && $value === $needle) {
                    return $city;
                }
            }
        }
        return null;
    }
}
