<?php

namespace PortalPeople\magento\controllers;

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

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,
            ]);
        }

        $refresh = Yii::$app->request->get('refresh', '0') === '1';
        $cacheKey = $this->getOrdersCacheKey($module);
        $cacheTtl = 300;

        $orders = null;
        if (!$refresh && Yii::$app->has('cache', true)) {
            $orders = Yii::$app->cache->get($cacheKey);
        }

        if (!is_array($orders)) {
            $client = new MagentoClient((string) $module->apiUrl, (string) $module->accessToken);
            $orders = $this->downloadAllOrders($client);

            if (Yii::$app->has('cache', true)) {
                Yii::$app->cache->set($cacheKey, $orders, $cacheTtl);
            }
        }

        $items = $orders['items'] ?? [];

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

        return $this->render('/orders/index', [
            'dataProvider' => $dataProvider,
            'totalCount' => (int) ($orders['total_count'] ?? count($items)),
            'isCached' => !$refresh && Yii::$app->has('cache', true),
        ]);
    }

    private function downloadAllOrders(MagentoClient $client): array
    {
        $pageSize = 100;
        $currentPage = 1;
        $allItems = [];
        $totalCount = 0;

        do {
            $response = $client->getOrders([
                'searchCriteria[pageSize]' => $pageSize,
                'searchCriteria[currentPage]' => $currentPage,
            ]);

            $items = $response['items'] ?? [];
            $totalCount = (int) ($response['total_count'] ?? $totalCount);

            if (is_array($items) && $items !== []) {
                $allItems = array_merge($allItems, $items);
            }

            $fetchedCount = is_array($items) ? count($items) : 0;
            $currentPage++;
        } while ($fetchedCount === $pageSize && ($totalCount === 0 || count($allItems) < $totalCount));

        return [
            'items' => $allItems,
            'total_count' => $totalCount > 0 ? $totalCount : count($allItems),
        ];
    }

    private function getOrdersCacheKey(\PortalPeople\magento\Module $module): string
    {
        return 'magento.orders.' . sha1(implode('|', [
            (string) $module->apiUrl,
            (string) $module->accessToken,
            (string) $module->storeCode,
        ]));
    }
}
