<?php

namespace backendApi\modules\v1\controllers;

use common\helpers\Form;
use common\models\Countries;
use common\models\Currency;
use common\models\CurrencyConversions;
use common\models\forms\CurrenciesConversionsForm;
use common\models\forms\FreeTemplateForm;
use common\models\FreeTemplate;
use yii\db\Exception;
use yii\web\HttpException;

class TransportationController extends BaseController
{
    public $modelClass = FreeTemplate::class;
    public $countiesModelClass = Countries::class;
    public $currencyModelClass = Currency::class;

    public function actionTransportation()
    {
        // 国家列表
        $countries = $this->countiesModelClass::getFromCache();
        // 运费列表
        $transportation = $this->modelClass::getFromCache();
        $transportation = array_column($transportation, NULL, 'country_id');
        // 货币列表
        $currencies = $this->currencyModelClass::getFromCache();
        $currencies = array_column($currencies, NULL, 'ID');

        foreach ($countries as &$country) {
            $country['freight'] = $transportation[$country['ID']]['freight'] ?? 0;
            $country['free_shipping'] = $transportation[$country['ID']]['free_shipping'] ?? 0;
            $country['currency'] = $this->currencyModelClass::getById($country['LOCAL_CURRENCY_ID']);
        }

        return static::notice(['data' => $countries]);
    }

    public function actionSetTransportation()
    {
        if (\Yii::$app->request->isPost) {
            $formModel = new FreeTemplateForm();
            $formModel->scenario = 'setTransportation';
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->setTransportation()) {
                // 更新缓存
                $this->modelClass::updateToCache();

                return static::notice(\Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);

            }
        }

        return static::notice(\Yii::t('ctx', 'illegalRequest'));
    }
}
