<?php

namespace PortalPeople\magento\services;

use PortalPeople\magento\Module;
use Yii;

class OrderSnapshotService
{
    public function loadOrdersSnapshot(Module $module, bool $refresh = false): array
    {
        $client = new MagentoClient((string) $module->apiUrl, (string) $module->accessToken);
        return $this->downloadAllOrders($client);

    }

    public function loadNewOrdersSnapshot(Module $module, bool $refresh = false): array
    {
        $client = new MagentoClient((string) $module->apiUrl, (string) $module->accessToken);
        return $this->downloadNewOrders($client);
    }

    public function loadPaymentSnapshots(Module $module, ?array $orders = null): array
    {
        return $this->extractPaymentSnapshots($orders['items'] ?? []);
        
    }

    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 downloadNewOrders(MagentoClient $client): array
    {
        $pageSize = 100;
        $currentPage = 1;
        $allItems = [];
        $totalCount = 0;

        do {
            $response = $client->getOrders([
                'searchCriteria[pageSize]' => $pageSize,
                'searchCriteria[currentPage]' => $currentPage,
                'searchCriteria[filterGroups][0][filters][0][field]' => 'ngauge_order_id',
                'searchCriteria[filterGroups][0][filters][0][conditionType]' => 'null',
                'searchCriteria[filterGroups][1][filters][0][field]' => 'total_due',
                'searchCriteria[filterGroups][1][filters][0][conditionType]' => 'eq',
                'searchCriteria[filterGroups][1][filters][0][value]' => 0,
                'searchCriteria[filterGroups][2][filters][0][field]' => 'status',
                'searchCriteria[filterGroups][2][filters][0][conditionType]' => 'nin',
                'searchCriteria[filterGroups][2][filters][0][value]' => 'pending_payment,payment_review',
            ]);

            $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(Module $module): string
    {
        return 'magento.orders.' . sha1(implode('|', [
            (string) $module->apiUrl,
            (string) $module->accessToken,
            (string) $module->storeCode,
        ]));
    }

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

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

    private function extractPaymentSnapshots(array $orders): array
    {
        $payments = [];

        foreach ($orders as $order) {
            if (!is_array($order)) {
                continue;
            }

            $payment = $order['payment'] ?? [];
            $payments[] = [
                'orderId' => $order['entity_id'] ?? null,
                'orderNo' => $order['increment_id'] ?? null,
                'status' => $order['status'] ?? null,
                'createdAt' => $order['created_at'] ?? null,
                'method' => is_array($payment) ? ($payment['method'] ?? '') : '',
                'amount' => $order['base_grand_total'] ?? $order['grand_total'] ?? null,
                'currency' => $order['base_currency_code'] ?? $order['order_currency_code'] ?? null,
                'customerEmail' => $order['customer_email'] ?? null,
                'raw' => $payment,
            ];
        }

        return $payments;
    }
}