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

namespace WriteTextAI\WriteTextAI\Model;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use WriteTextAI\WriteTextAI\ViewModel\Settings;

class KeywordIdeaFiltersManager
{
    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var Settings
     */
    protected $settings;

    /**
     * @param ScopeConfigInterface $scopeConfig
     * @param Settings $settings
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        Settings $settings
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->settings = $settings;
    }

    /**
     * Get available countries
     *
     * @return array
     */
    public function getAvailableCountries()
    {
        $locations = $this->settings->getSettings('locations');
        if (!is_array($locations)) {
            $locations = json_decode($locations, true);
        }

        return $locations;
    }

    /**
     * Get default location
     *
     * @param int $storeId
     * @return string
     */
    public function getLocationCode($storeId)
    {
        $countryCode = $this->getCountryCode($storeId);
        $locations = $this->getAvailableCountries();

        foreach ($locations as $location) {
            if ($location['country_iso_code'] == $countryCode) {
                return $location['location_code'];
            }
        }

        return 2840; // Default to United States
    }

    /**
     * Get country code
     *
     * @param int $storeId
     * @return string
     */
    public function getCountryCode($storeId)
    {
        $countryCode =  $this->scopeConfig->getValue(
            'general/country/default',
            ScopeInterface::SCOPE_STORE,
            $storeId
        );

        return $countryCode;
    }
}
