<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\ViewModel;

use WriteTextAI\WriteTextAI\Helper\Data;
use WriteTextAI\WriteTextAI\Model\KeywordIdeaFiltersManager;

class Locations implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
    /**
     * @var Data
     */
    protected $helper;

    /**
     * @var KeywordIdeaFiltersManager
     */
    protected $keywordIdeaFiltersManager;

    /**
     * @var array
     */
    protected $availableCountries = [];

    /**
     * Constructor
     *
     * @param Data $helper
     * @param KeywordIdeaFiltersManager $keywordIdeaFiltersManager
     */
    public function __construct(
        Data $helper,
        KeywordIdeaFiltersManager $keywordIdeaFiltersManager
    ) {
        $this->helper = $helper;
        $this->keywordIdeaFiltersManager = $keywordIdeaFiltersManager;
    }

    /**
     * Get available countries
     *
     * @return array
     */
    public function getAvailableCountries()
    {
        if (!empty($this->availableCountries)) {
            return $this->availableCountries;
        }

        $countries = $this->keywordIdeaFiltersManager->getAvailableCountries();

        usort($countries, function ($item1, $item2) {
            return $item1['location_name'] <=> $item2['location_name'];
        });

        $this->availableCountries = $countries;
        
        return $this->availableCountries;
    }

    /**
     * Get options
     *
     * @return array
     */
    public function getCountryOptions()
    {
        try {
            $locations = $this->getAvailableCountries();
        } catch (\Exception $e) {
            $locations = [];
        }

        $options = [];

        foreach ($locations as $location) {
            $options[] = [
                'value' => $location['country_iso_code'],
                'label' => $location['location_name']
            ];
        }

        return $options;
    }
}
