<?php

namespace Shop\Controllers;

use Core\BaseController;
use Core\Form\ControlBuilder;
use Diamond\Application\Content\Exceptions\PageNotFoundException;
use Shop\Application\Office\OfficeService;
use Shop\Repositories\City\CityRepository;
use Shop\Repositories\Region\RegionCriteria;
use Shop\Repositories\Region\RegionRepository;
use Shop\Repositories\Stock\StockCriteria;
use Shop\Repositories\Stock\StockRepository;
use Symfony\Component\HttpFoundation\JsonResponse;

class StockController extends BaseController
{
    protected $repo;
    protected $builder;
    protected $cityRepository;
    protected $officeService;

    public function __construct(StockRepository $repo, OfficeService $officeService,
                                CityRepository $cityRepository,
                                ControlBuilder $cBuilder)
    {
        $this->repo = $repo;
        $this->builder  = $cBuilder;
        $this->cityRepository = $cityRepository;
        $this->officeService = $officeService;
    }

    function index(): JsonResponse
    {
        if(!$city = $this->cityRepository->findById(input_get('city'))){
            throw new PageNotFoundException('city not found by id ' . input_get('city'));
        }

        $stocks = $this->repo->findByCriteria(
            StockCriteria::create()->setFilterByActive(true)->setFilterByCityId($city->getId())
        )->getDropdownList();

        $data [] = [
            'id'    => null,
            'value' => '- не выбранно -'
        ];

        $stockMain = $this->officeService->getMainStock();

        $data[$stockMain->getId()] = [
            'id'    => $stockMain->getId(),
            'value' => $stockMain->getTitle()
        ];

        foreach ($stocks as $key => $value) {

            $data[$key] = [
                'id'    => $key,
                'value' => $value
            ];
        }

        $stocks = $this->repo->findByCriteria(
            StockCriteria::create()->setFilterByActive(true)->setFilterByRegionId($city->getRegionId())
        )->getDropdownList();

        foreach ($stocks as $key => $value) {
            $data[$key] = [
                'id'    => $key,
                'value' => $value
            ];
        }

        return new JsonResponse(array_values($data));
    }
}