<?php

namespace PortalPeople\magento\controllers;

use PortalPeople\magento\models\ConfigForm;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;

class ConfigController extends Controller
{
    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    ['allow' => true, 'roles' => ['@']],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => ['index' => ['GET', 'POST']],
            ],
        ];
    }

    public function actionIndex()
    {
        $model = new ConfigForm();
        $model->loadFromParams();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->saveToParams()) {
                Yii::$app->session->setFlash('success', 'Magento integration settings saved.');
                return $this->refresh();
            }
            Yii::$app->session->setFlash('error', 'Failed to save Magento configuration.');
        }

        return $this->render('index', ['model' => $model]);
    }
}
