<?php

namespace PortalPeople\shippingcosts\controllers;

use PortalPeople\shippingcosts\models\ConfigForm;
use PortalPeople\shippingcosts\Module;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Response;
use yii\widgets\ActiveForm;

class ConfigController extends Controller
{
    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'validate' => ['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', 'Shipping costs configuration saved successfully.');
                return $this->refresh();
            }
            Yii::$app->session->setFlash('error', 'Failed to save shipping costs configuration.');
        }

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

    public function actionValidate(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $model = new ConfigForm();
        $model->loadFromParams();

        if ($model->load(Yii::$app->request->post())) {
            return ActiveForm::validate($model);
        }

        return [];
    }

    public function actionStatus(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $module = Yii::$app->getModule('shippingcosts');
        if (!$module instanceof Module) {
            return [
                'success' => false,
                'message' => 'Module is not available.',
            ];
        }

        $config = $module->getConfig();

        return [
            'success' => true,
            'configured' => $module->isConfigured(),
            'enabled' => $config['enabled'] ?? false,
            'parameterCount' => count($config['parameters'] ?? []),
            'maxShippingCost' => $config['maxShippingCost'] ?? null,
        ];
    }
}
