<?php

namespace PortalPeople\magento\controllers;

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

class OrdersController extends Controller
{
    public function actionImport(): array
    {
        $module = Yii::$app->getModule('magento');
        if (!$module instanceof \PortalPeople\magento\Module || !$module->isConfigured()) {
            Yii::$app->response->statusCode = 400;
            return ['success' => false, 'message' => 'Magento 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 a Magento order payload.'];
        }

        try {
            $result = Cart::newMagentoOrder($payload);
            return ['success' => true, 'message' => 'Magento order imported.', 'result' => $result];
        } catch (\Throwable $e) {
            Yii::error('Magento order import failed: ' . $e->getMessage(), 'magento');
            Yii::$app->response->statusCode = 500;
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    public function actionIndex(): array
    {
        $query = Cart::find()->orderBy(['dateordered' => SORT_DESC]);
        return [
            'success' => true,
            'count' => (int) $query->count(),
            'orders' => $query->limit(100)->all(),
        ];
    }
}
