<?php

namespace PortalPeople\virtualstock\controllers\api;

use Yii;
use yii\rest\Controller;
use PortalPeople\virtualstock\models\Cart;

class OrdersController extends Controller
{
    public function actionNewOrder(): array
    {
        $module = Yii::$app->getModule('virtualstock');
        if (!$module instanceof \PortalPeople\virtualstock\Module || !$module->isConfigured()) {
            Yii::$app->response->statusCode = 400;
            return [
                'success' => false,
                'message' => 'VirtualStock module is not configured.',
            ];
        }

        $payload = Yii::$app->request->getBodyParams();
        if (!is_array($payload) || $payload === []) {
            Yii::$app->response->statusCode = 400;
            return [
                'success' => false,
                'message' => 'Request body must contain an order payload.',
            ];
        }

        try {
            $result = Cart::NewVirtualStockOrder($payload);

            return [
                'success' => true,
                'message' => 'Order imported successfully.',
                'result' => $result,
            ];
        } catch (\Throwable $e) {
            Yii::error('VirtualStock API new-order import failed: ' . $e->getMessage(), 'virtualstock');
            Yii::error($e->getTraceAsString(), 'virtualstock');

            Yii::$app->response->statusCode = 500;
            return [
                'success' => false,
                'message' => $e->getMessage(),
            ];
        }
    }
}
