<?php
declare(strict_types=1);

namespace App\Modules\Statistics;

use App\Core\Http\Request;
use App\Core\Http\Response;
use App\Core\Security\Csrf;
use App\Core\View\Template;
use App\Core\I18n\Translator;
use App\Modules\Auth\AuthService;
use DateInterval;
use DatePeriod;
use DateTimeImmutable;

final class OrdersStatisticsController
{
    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly OrdersStatisticsRepository $repository
    ) {
    }

    public function index(Request $request): Response
    {
        [$dateFrom, $dateTo] = $this->resolveDateRange($request);

        $statusGroups = $this->repository->listStatusGroups();
        $statusGroupOptions = $this->mapStatusGroupOptions($statusGroups);
        $selectedStatusGroups = $this->resolveSelectedStatusGroups($request, $statusGroupOptions);

        $channelOptions = $this->mapChannelOptions($this->repository->listChannelOptions());
        $selectedChannels = $this->resolveSelectedChannels($request, $channelOptions);

        $statusCodes = $this->repository->statusCodesByGroupIds($selectedStatusGroups);
        $aggregated = $this->repository->aggregateByDay($dateFrom, $dateTo, $selectedChannels, $statusCodes);
        $debugEnabled = (string) $request->input('debug', '') === '1';
        $diagnostics = $debugEnabled
            ? $this->repository->diagnostics($dateFrom, $dateTo, $selectedChannels, $statusCodes)
            : [];

        $table = $this->buildTable($dateFrom, $dateTo, $selectedChannels, $aggregated);

        $html = $this->template->render('statistics/orders', [
            'title' => $this->translator->get('statistics.orders.title'),
            'activeMenu' => 'statistics',
            'activeStatistics' => 'orders',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'filters' => [
                'date_from' => $dateFrom,
                'date_to' => $dateTo,
                'selected_channels' => $selectedChannels,
                'selected_status_groups' => $selectedStatusGroups,
            ],
            'channelOptions' => $channelOptions,
            'statusGroupOptions' => $statusGroupOptions,
            'table' => $table,
            'debugEnabled' => $debugEnabled,
            'diagnostics' => $diagnostics,
            'debugMeta' => [
                'selected_channels' => $selectedChannels,
                'selected_status_groups' => $selectedStatusGroups,
                'status_codes' => $statusCodes,
            ],
        ], 'layouts/app');

        return Response::html($html);
    }

    /**
     * @return array{0:string,1:string}
     */
    private function resolveDateRange(Request $request): array
    {
        $now = new DateTimeImmutable('now');
        $defaultFrom = $now->modify('first day of this month')->format('Y-m-d');
        $defaultTo = $now->modify('last day of this month')->format('Y-m-d');

        $dateFrom = trim((string) $request->input('date_from', $defaultFrom));
        $dateTo = trim((string) $request->input('date_to', $defaultTo));

        if (!$this->isValidDate($dateFrom)) {
            $dateFrom = $defaultFrom;
        }
        if (!$this->isValidDate($dateTo)) {
            $dateTo = $defaultTo;
        }
        if ($dateFrom > $dateTo) {
            [$dateFrom, $dateTo] = [$dateTo, $dateFrom];
        }

        return [$dateFrom, $dateTo];
    }

    private function isValidDate(string $date): bool
    {
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) {
            return false;
        }

        return DateTimeImmutable::createFromFormat('Y-m-d', $date) !== false;
    }

    /**
     * @param array<int, array{id:int,name:string}> $groups
     * @return array<int, array{id:int,name:string}>
     */
    private function mapStatusGroupOptions(array $groups): array
    {
        $options = [];
        foreach ($groups as $group) {
            $groupId = (int) ($group['id'] ?? 0);
            if ($groupId <= 0) {
                continue;
            }

            $options[] = [
                'id' => $groupId,
                'name' => trim((string) ($group['name'] ?? '')),
            ];
        }

        return $options;
    }

    /**
     * @param array<int, array{id:int,name:string}> $statusGroupOptions
     * @return array<int, int>
     */
    private function resolveSelectedStatusGroups(Request $request, array $statusGroupOptions): array
    {
        $allowed = [];
        foreach ($statusGroupOptions as $option) {
            $allowed[] = (int) $option['id'];
        }

        $allInput = $request->all();
        $hasStatusGroupsParam = array_key_exists('status_groups', $allInput);
        $selected = $this->toIntegerList($request->input('status_groups', []));
        if (!$hasStatusGroupsParam) {
            $selected = $this->defaultStatusGroupIds($statusGroupOptions);
        }

        $selected = array_values(array_intersect($selected, $allowed));
        if ($selected !== []) {
            return $selected;
        }

        return $hasStatusGroupsParam ? [] : $this->defaultStatusGroupIds($statusGroupOptions);
    }

    /**
     * @param array<int, array{id:int,name:string}> $statusGroupOptions
     * @return array<int, int>
     */
    private function defaultStatusGroupIds(array $statusGroupOptions): array
    {
        $selected = [];
        foreach ($statusGroupOptions as $group) {
            $name = trim((string) ($group['name'] ?? ''));
            if ($this->isCancelledGroup($name)) {
                continue;
            }
            $selected[] = (int) ($group['id'] ?? 0);
        }

        return array_values(array_filter($selected, static fn (int $id): bool => $id > 0));
    }

    private function isCancelledGroup(string $name): bool
    {
        $normalized = strtr(mb_strtolower(trim($name)), [
            'ą' => 'a',
            'ć' => 'c',
            'ę' => 'e',
            'ł' => 'l',
            'ń' => 'n',
            'ó' => 'o',
            'ś' => 's',
            'ż' => 'z',
            'ź' => 'z',
        ]);

        return in_array($normalized, ['anulowane', 'anulowany', 'cancelled', 'canceled'], true);
    }

    /**
     * @param array<int, array{key:string,label:string}> $channels
     * @return array<int, array{key:string,label:string}>
     */
    private function mapChannelOptions(array $channels): array
    {
        $options = [];
        foreach ($channels as $channel) {
            $key = trim((string) ($channel['key'] ?? ''));
            if ($key === '') {
                continue;
            }
            $options[] = [
                'key' => $key,
                'label' => trim((string) ($channel['label'] ?? $key)),
            ];
        }

        return $options;
    }

    /**
     * @param array<int, array{key:string,label:string}> $channelOptions
     * @return array<int, string>
     */
    private function resolveSelectedChannels(Request $request, array $channelOptions): array
    {
        $allowed = [];
        foreach ($channelOptions as $option) {
            $allowed[] = (string) $option['key'];
        }

        $allInput = $request->all();
        $hasChannelsParam = array_key_exists('channels', $allInput);
        $selected = $this->toStringList($request->input('channels', []));
        if (!$hasChannelsParam) {
            return $allowed;
        }

        return array_values(array_intersect($selected, $allowed));
    }

    /**
     * @param array<int, string> $selectedChannels
     * @param array<int, array{day:string,channel_key:string,orders_count:int,total_net:float,total_gross:float}> $aggregated
     * @return array{rows:array<int,array<string,mixed>>,totals:array<string,mixed>,hasData:bool}
     */
    private function buildTable(string $dateFrom, string $dateTo, array $selectedChannels, array $aggregated): array
    {
        $rows = [];
        foreach ($this->dateRange($dateFrom, $dateTo) as $day) {
            $rows[$day] = [
                'day' => $day,
                'channels' => $this->emptyChannelsRow($selectedChannels),
                'day_total_orders' => 0,
                'day_total_net' => 0.0,
                'day_total_gross' => 0.0,
            ];
        }

        foreach ($aggregated as $item) {
            $day = (string) ($item['day'] ?? '');
            $channelKey = (string) ($item['channel_key'] ?? '');
            if ($day === '' || $channelKey === '' || !isset($rows[$day]['channels'][$channelKey])) {
                continue;
            }

            $ordersCount = (int) ($item['orders_count'] ?? 0);
            $totalNet = (float) ($item['total_net'] ?? 0);
            $totalGross = (float) ($item['total_gross'] ?? 0);

            $rows[$day]['channels'][$channelKey] = [
                'orders_count' => $ordersCount,
                'total_net' => $totalNet,
                'total_gross' => $totalGross,
            ];
            $rows[$day]['day_total_orders'] += $ordersCount;
            $rows[$day]['day_total_net'] += $totalNet;
            $rows[$day]['day_total_gross'] += $totalGross;
        }

        $totals = [
            'channels' => $this->emptyChannelsRow($selectedChannels),
            'orders_count' => 0,
            'total_net' => 0.0,
            'total_gross' => 0.0,
        ];

        $hasData = false;
        foreach ($rows as $row) {
            foreach ($selectedChannels as $channelKey) {
                $channelStats = $row['channels'][$channelKey];
                $totals['channels'][$channelKey]['orders_count'] += (int) ($channelStats['orders_count'] ?? 0);
                $totals['channels'][$channelKey]['total_net'] += (float) ($channelStats['total_net'] ?? 0);
                $totals['channels'][$channelKey]['total_gross'] += (float) ($channelStats['total_gross'] ?? 0);
            }
            $totals['orders_count'] += (int) ($row['day_total_orders'] ?? 0);
            $totals['total_net'] += (float) ($row['day_total_net'] ?? 0);
            $totals['total_gross'] += (float) ($row['day_total_gross'] ?? 0);
            if ((int) ($row['day_total_orders'] ?? 0) > 0) {
                $hasData = true;
            }
        }

        return [
            'rows' => array_values($rows),
            'totals' => $totals,
            'hasData' => $hasData,
        ];
    }

    /**
     * @param array<int, string> $channelKeys
     * @return array<string, array{orders_count:int,total_net:float,total_gross:float}>
     */
    private function emptyChannelsRow(array $channelKeys): array
    {
        $row = [];
        foreach ($channelKeys as $channelKey) {
            $row[$channelKey] = [
                'orders_count' => 0,
                'total_net' => 0.0,
                'total_gross' => 0.0,
            ];
        }

        return $row;
    }

    /**
     * @return array<int, string>
     */
    private function dateRange(string $dateFrom, string $dateTo): array
    {
        $start = new DateTimeImmutable($dateFrom);
        $end = (new DateTimeImmutable($dateTo))->add(new DateInterval('P1D'));
        $period = new DatePeriod($start, new DateInterval('P1D'), $end);

        $dates = [];
        foreach ($period as $date) {
            $dates[] = $date->format('Y-m-d');
        }

        return $dates;
    }

    /**
     * @return array<int, string>
     */
    private function toStringList(mixed $value): array
    {
        $items = is_array($value) ? $value : ($value !== null && $value !== '' ? [$value] : []);
        $list = [];
        foreach ($items as $item) {
            $normalized = trim((string) $item);
            if ($normalized !== '') {
                $list[] = $normalized;
            }
        }

        return array_values(array_unique($list));
    }

    /**
     * @return array<int, int>
     */
    private function toIntegerList(mixed $value): array
    {
        $items = is_array($value) ? $value : ($value !== null && $value !== '' ? [$value] : []);
        $list = [];
        foreach ($items as $item) {
            $number = (int) $item;
            if ($number > 0) {
                $list[] = $number;
            }
        }

        return array_values(array_unique($list));
    }
}
