<?php

namespace Webkul\Core\Http\Controllers;

use Webkul\Core\Repositories\CountryRepository;
use Webkul\Core\Repositories\CountryStateRepository;

/**
 * Country controller
 *
 * @author    Jitendra Singh <jitendra@webkul.com>
 * @copyright 2018 Webkul Software Pvt Ltd (http://www.webkul.com)
 */
class CountryStateController extends Controller
{
    /**
     * Contains route related configuration
     *
     * @var array
     */
    protected $_config;

    /**
     * CountryRepository object
     *
     * @var array
     */
    protected $countryRepository;

    /**
     * StateRepository object
     *
     * @var array
     */
    protected $stateRepository;

    /**
     * Create a new controller instance.
     *
     * @param  \Webkul\Core\Repositories\CountryRepository $countryRepository
     * @param  \Webkul\Core\Repositories\StateRepository   $stateRepository
     * @return void
     */
    public function __construct(
        CountryRepository $countryRepository,
        StateRepository $stateRepository
    )
    {
        $this->countryRepository = $countryRepository;

        $this->stateRepository = $stateRepository;

        $this->_config = request('_config');
    }

    /**
     * Function to retrieve states with respect to countries with codes and names for both of the countries and states.
     *
     * @return \Illuminate\View\View
     */
    public function getCountries()
    {
        $countries = $this->countryRepository->all();

        $states = $this->stateRepository->all();

        $nestedArray = [];

        foreach ($countries as $keyCountry => $country) {
            foreach ($states as $keyState => $state) {
                if ($country->code == $state->country_code) {
                    $nestedArray[$country->name][$state->code] = $state->default_name;
                }
            }
        }

        return view($this->_config['view'])->with('statesCountries', $nestedArray);
    }

    public function getStates($country)
    {
        $countries = $this->countryRepository->all();
        
        $states = $this->stateRepository->all();

        $nestedArray = [];

        foreach ($countries as $keyCountry => $country) {
            foreach ($states as $keyState => $state) {
                if ($country->code == $state->country_code) {
                    $nestedArray[$country->name][$state->code] = $state->default_name;
                }
            }
        }

        return view($this->_config['view'])->with('statesCountries', $nestedArray);
    }
}