<?php
/**
 * Caterpoint Order Management Controller
 *
 * @category    PortalPeople
 * @package     Caterpoint
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2026 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\caterpoint\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use PortalPeople\caterpoint\Module;

/**
 * Order Management Controller
 * 
 * Provides friendly HTML interfaces for Caterpoint order operations
 * 
 * Routes (for /NGauge/caterpoint/*):
 *   GET    /NGauge/caterpoint/order/index           Order management dashboard
 *   GET    /NGauge/caterpoint/order/fetch-raw       View raw order data from API
 *   POST   /NGauge/caterpoint/order/import          Trigger manual import
 */
class OrderController extends Controller
{
    /**
     * @var Module Module instance
     */
    private ?Module $caterpointModule = null;

    /**
     * Configure controller behaviors
     * 
     * @return array
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'import' => ['POST'],
                    'reset' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Initialize the controller
     * 
     * @throws \Exception
     */
    public function init()
    {
        parent::init();

        try {
            $this->caterpointModule = Yii::$app->getModule('caterpoint');
        } catch (\Exception $e) {
            throw new \yii\web\ServerErrorHttpException('Caterpoint module not configured: ' . $e->getMessage());
        }

        if ($this->caterpointModule === null) {
            throw new \yii\web\ServerErrorHttpException('Caterpoint module not found');
        }
    }

    /**
     * Order management dashboard
     * 
     * @return string HTML response
     */
    public function actionIndex()
    {
        $service = $this->caterpointModule->createOrderImportService();
        $cursor = $service->cursorStore->get();
        
        return $this->render('index', [
            'module' => $this->caterpointModule,
            'currentCursor' => $cursor,
            'configured' => $this->caterpointModule->isConfigured(),
        ]);
    }

    /**
     * View raw order data from Caterpoint API
     * 
     * Query parameters:
     *   - cursor: Optional cursor for pagination
     *   - limit: Limit per request (default 1)
     *   - format: Response format (html, json, xml) - default html
     * 
     * @return string|Response HTML response or raw data
     */
    public function actionFetchRaw()
    {
        $request = Yii::$app->request;
        $cursor = $request->get('cursor');
        $limit = (int) $request->get('limit', 1);
        $format = (string) $request->get('format', 'html');
        $client = null;

        try {
            $client = $this->caterpointModule->createClient();
            $result = $client->getOrdersUpdatedSince($cursor, $limit);
            $sourceFormat = $client->getLastResponseFormat();

            if ($format === 'json') {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return [
                    'success' => true,
                    'message' => 'Raw orders fetched from Caterpoint API',
                    'sourceFormat' => $sourceFormat,
                    'data' => $result,
                ];
            }

            if ($format === 'xml') {
                Yii::$app->response->format = Response::FORMAT_XML;
                return [
                    'success' => true,
                    'message' => 'Raw orders fetched from Caterpoint API',
                    'sourceFormat' => $sourceFormat,
                    'data' => $result,
                ];
            }

            return $this->render('fetch-raw', [
                'result' => $result,
                'sourceFormat' => $sourceFormat,
                'cursor' => $cursor,
                'limit' => $limit,
                'error' => null,
            ]);
        } catch (\Throwable $e) {
            $errorMessage = 'Failed to fetch orders: ' . $e->getMessage();
            $sourceFormat = $client !== null ? $client->getLastResponseFormat() : null;

            if ($format === 'json') {
                Yii::$app->response->format = Response::FORMAT_JSON;
                Yii::$app->response->statusCode = 502;

                return [
                    'success' => false,
                    'message' => $errorMessage,
                    'sourceFormat' => $sourceFormat,
                    'data' => null,
                ];
            }

            if ($format === 'xml') {
                Yii::$app->response->format = Response::FORMAT_XML;
                Yii::$app->response->statusCode = 502;

                return [
                    'success' => false,
                    'message' => $errorMessage,
                    'sourceFormat' => $sourceFormat,
                    'data' => null,
                ];
            }

            return $this->render('fetch-raw', [
                'result' => [],
                'sourceFormat' => $sourceFormat ?? 'unknown',
                'cursor' => $cursor,
                'limit' => $limit,
                'error' => $errorMessage,
            ]);
        }
    }

    /**
     * Trigger manual import
     * 
     * @return Response
     */
    public function actionImport()
    {
        if (!$this->caterpointModule->isConfigured()) {
            Yii::$app->session->setFlash('error', 'Caterpoint module is not configured');
            return $this->redirect(['index']);
        }

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

        try {
            $service = $this->caterpointModule->createOrderImportService();
            $result = $service->run(null, $limit, $dryRun);

            $message = $dryRun ? 'Dry run completed' : 'Import completed';
            $message .= ": {$result['created']} created, {$result['updated']} updated";
            
            Yii::$app->session->setFlash('success', $message);
        } catch (\Throwable $e) {
            Yii::error('Order import failed: ' . $e->getMessage(), 'caterpoint.import');
            Yii::$app->session->setFlash('error', 'Import failed: ' . $e->getMessage());
        }

        return $this->redirect(['index']);
    }

    /**
     * Reset import cursor
     * 
     * @return Response
     */
    public function actionReset()
    {
        try {
            $service = $this->caterpointModule->createOrderImportService();
            $service->cursorStore->clear();
            Yii::$app->session->setFlash('success', 'Import cursor reset successfully');
        } catch (\Throwable $e) {
            Yii::$app->session->setFlash('error', 'Failed to reset cursor: ' . $e->getMessage());
        }

        return $this->redirect(['index']);
    }
}
