<?php

/**
 * Configuration Controller – VirtualStock Module
 *
 * @category    PortalPeople
 * @package     VirtualStock
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2026 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\virtualstock\controllers;

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

/**
 * ConfigController
 *
 * Provides a web UI for managing VirtualStock module settings, testing the
 * API connection, and triggering an on-demand order import.
 */
class ConfigController extends Controller
{
    /** @inheritdoc */
    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => [
                    'save'            => ['POST'],
                    'test-connection' => ['POST'],
                    'import'          => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Display and process the configuration form.
     *
     * @return string|\yii\web\Response
     */
    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', 'VirtualStock configuration saved successfully.');
                return $this->refresh();
            }
            Yii::$app->session->setFlash('error', 'Failed to save configuration. Check file permissions.');
        }

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

    /**
     * AJAX: test API connection with the submitted form values.
     *
     * @return array
     */
    public function actionTestConnection(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $model = new ConfigForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $result = $model->testConnection();
            return [
                'success' => $result['success'],
                'message' => $result['message'],
            ];
        }

        return [
            'success' => false,
            'message' => 'Invalid configuration data.',
            'errors'  => $model->errors,
        ];
    }

    /**
     * AJAX: return current module status including cursor position.
     *
     * @return array
     */
    public function actionStatus(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        /** @var \PortalPeople\virtualstock\Module $module */
        $module = Yii::$app->getModule('virtualstock');

        if (!$module) {
            return ['success' => false, 'configured' => false, 'cursor' => null];
        }

        $cursor = null;
        try {
            $cursorStore = $module->createCursorStore();
            $cursor      = $cursorStore->get();
        } catch (\Throwable $e) {
            Yii::warning('VirtualStock status: could not read cursor — ' . $e->getMessage(), 'virtualstock');
        }

        return [
            'success'    => true,
            'configured' => $module->isConfigured(),
            'cursor'     => $cursor,
            'pollLimit'  => $module->pollLimit,
        ];
    }

    /**
     * AJAX POST: trigger an on-demand order import (dry-run optional).
     *
     * Accepts: { dryRun: 1|0, limit: <int> }
     *
     * @return array
     */
    public function actionImport(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        /** @var \PortalPeople\virtualstock\Module $module */
        $module = Yii::$app->getModule('virtualstock');

        if (!$module || !$module->isConfigured()) {
            return [
                'success' => false,
                'message' => 'VirtualStock is not configured. Save valid settings first.',
            ];
        }

        $request = Yii::$app->request;
        $dryRun  = (bool) $request->post('dryRun', 0);
        $limit   = (int)  $request->post('limit', $module->pollLimit);

        try {
            $service = $module->createOrderImportService();
            $stats   = $service->run(null, $limit, $dryRun);

            return [
                'success' => true,
                'dryRun'  => $dryRun,
                'stats'   => $stats,
                'message' => $dryRun
                    ? "Dry run complete. {$stats['found']} orders found, {$stats['imported']} would be imported."
                    : "{$stats['imported']} order(s) imported, {$stats['skipped']} skipped.",
            ];
        } catch (\Throwable $e) {
            Yii::error('VirtualStock import error: ' . $e->getMessage(), 'virtualstock');
            return [
                'success' => false,
                'message' => 'Import failed: ' . $e->getMessage(),
            ];
        }
    }
}
