<?php

namespace PortalPeople\magento\controllers;

use PortalPeople\magento\services\MagentoClient;
use yii\data\ArrayDataProvider;
use yii\filters\AccessControl;
use yii\web\Controller;
use Yii;

class DefaultController extends Controller
{
    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    ['allow' => true, 'roles' => ['@']],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->renderContent('Magento module is ready.');
    }

    public function actionOrders()
    {
        $module = Yii::$app->getModule('magento');
        if (!$module instanceof \PortalPeople\magento\Module || !$module->isConfigured()) {
            Yii::$app->session->setFlash('error', 'Magento integration is not configured.');

            return $this->render('/orders/index', [
                'dataProvider' => new ArrayDataProvider([
                    'allModels' => [],
                    'pagination' => false,
                ]),
                'totalCount' => 0,
            ]);
        }

        $client = new MagentoClient((string) $module->apiUrl, (string) $module->accessToken);
        $orders = $client->getOrders(['searchCriteria[pageSize]' => 50]);
        $items = $orders['items'] ?? [];

        $dataProvider = new ArrayDataProvider([
            'allModels' => is_array($items) ? $items : [],
            'pagination' => false,
        ]);

        return $this->render('/orders/index', [
            'dataProvider' => $dataProvider,
            'totalCount' => (int) ($orders['total_count'] ?? count($items)),
        ]);
    }
}
