<?php
namespace Incoviba\Controller;

use Incoviba\Common\Implement\Exception\EmptyResult;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Repository;
use Incoviba\Model;

class Regiones
{
    public function provincias(ServerRequestInterface $request, ResponseInterface $response, Repository\Provincia $provinciaRepository, int $region_id): ResponseInterface
    {
        $output = [
            'region_id' => $region_id,
            'provincias' => []
        ];
        try {
            $provincias = $provinciaRepository->fetchByRegion($region_id);
            usort($provincias, function(Model\Provincia $a, Model\Provincia $b) {
                return strcmp($a->descripcion, $b->descripcion);
            });
            $output['provincias'] = $provincias;
        } catch (EmptyResult) {}
        $response->getBody()->write(json_encode($output));
        return $response->withHeader('Content-Type', 'application/json');
    }
}
