<?php

namespace App\Services;

use App\Enums\OrderFlag;
use App\Enums\OrderType;
use App\Models\OrderArchive;
use App\Models\OrderArchivesItem;
use App\Models\ProductGroup;
use App\Models\ProfitCenter;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class StatisticsService extends ServiceBase
{
    private array $statisticsParameters = [
        'suppliers' => [],
        'profitCenters' => [],
        'productGroups' => [],
        'products' => [],
        'producers' => [],
        'hooreycaNames' => [],
        'dateFrom' => null,
        'dateTo' => null,
    ];

    private array $availableFilters = [
        'OrderFrequency' => ['suppliers', 'profitCenters', 'date', 'dateFrom', 'dateTo'],
        'PriceChange' => ['suppliers', 'date', 'dateFrom', 'dateTo', 'productGroups', 'products', 'hooreycaNames', 'producers'],
        'ProductAmount' => ['suppliers', 'profitCenters', 'date', 'dateFrom', 'dateTo', 'productGroups', 'products', 'hooreycaNames', 'producers'],
    ];

    private Collection $S;

    public function getAvailableFilters($type = null): array
    {
        if (isset($this->availableFilters[$type])) {
            return $this->availableFilters[$type];
        }

        return $this->availableFilters;
    }

    public function getStatisticsParameters(?string $pointer = null): array
    {
        if ($pointer) {
            return $this->statisticsParameters[$pointer];
        }

        return $this->statisticsParameters;
    }

    public function setStatisticsParameters(?string $pointer, $value): StatisticsService
    {
        if ($pointer) {
            $this->statisticsParameters[$pointer] = $value;

            return $this;
        }
        $this->statisticsParameters = $value;

        return $this;
    }

    public function addStatisticsParameter(string $pointer, array $value): StatisticsService
    {
        if (is_array($this->statisticsParameters[$pointer])) {
            $this->statisticsParameters[$pointer] = array_unique(array_merge($this->statisticsParameters[$pointer], $value));
        }

        return $this;
    }

    public function __construct()
    {
        parent::__construct();

    }

    private function getProductGroupsWithParentName($productGroupIds): array
    {
        $ProductGroup = new \App\Models\ProductGroup;
        $productGroupArray = $ProductGroup->allWithPath(3);
        $productGroupData = [];
        foreach ($productGroupArray as $productGroup) {
            if (in_array($productGroup['id'], $productGroupIds)) {
                $productGroupData[$productGroup['id']] = explode('/', $productGroup['fullPath']);

            }
        }

        return $productGroupData;
    }

    private function parseProductGroupFilter(): void
    {
        $tmp = $this->statisticsParameters['productGroups'];
        if (count($this->statisticsParameters['productGroups']) > 0) {
            $ProductGroup = new ProductGroup;
            $newGroups = [];
            foreach ($this->statisticsParameters['productGroups'] as $productGroupId) {
                $newGroups = array_unique(array_merge($newGroups,
                    ProductGroup::find($productGroupId)->descendants()->get()->pluck('id')->toArray()
                ));
            }
            $this->statisticsParameters['productGroups'] = array_unique(array_merge($this->statisticsParameters['productGroups'], $newGroups));
        }
    }

    public function getStatisticsPriceChange(): array
    {
        $data = [];
        $Model = OrderArchivesItem::where('status', 'active');
        $Model->limit(1);
        $data = $Model->get();

        // dd($Model);
        return ['SQL' => getSql($Model), 'data' => $data->toArray()];
    }

    public function getStatisticsProductAmount(): array
    {
        $data = [];
        $Model = OrderArchivesItem::whereHas('orderArchive', function ($query) {
            $query->where('orderType', OrderType::daily)
                ->where(function ($query) {
                    $query->wherein('orderFlag', [OrderFlag::modifier])
                        ->orWhere('orderFlag', '=', null);
                });
            if (count($this->statisticsParameters['suppliers']) > 0) {
                $query->whereIn('supplier_id', $this->statisticsParameters['suppliers']);
            }
            if (count($this->statisticsParameters['profitCenters']) > 0) {
                $query->whereIn('profit_center_id', $this->statisticsParameters['profitCenters']);
            }
            if ($this->statisticsParameters['dateFrom']) {
                $query->where('deliveryDate', '>=', $this->statisticsParameters['dateFrom']);
            }
            if ($this->statisticsParameters['dateTo']) {
                $query->where('deliveryDate', '<=', $this->statisticsParameters['dateTo']);
            }
            // ->where('orderArchive.orderType',OrderType::daily)
        })
            ->with('orderArchive:id,profit_center_name');

        // csoport szúrő, figyelembe venni ha 1, 2 színtű lekérdezni a gyerekeket
        $this->parseProductGroupFilter();
        if (count($this->statisticsParameters['productGroups']) > 0) {
            $Model->whereIn('product_group_id', $this->statisticsParameters['productGroups']);
        }

        // termÉk szűrő
        if (count($this->statisticsParameters['products']) > 0) {
            $Model->whereIn('name', $this->statisticsParameters['products']);
        }

        // hooreyca name szürő
        if (count($this->statisticsParameters['hooreycaNames']) > 0) {
            $Model->whereIn('buyerProductName', $this->statisticsParameters['hooreycaNames']);
        }

        // gyártó szürő
        if (count($this->statisticsParameters['producers']) > 0) {
            $Model->whereIn('producer_id', $this->statisticsParameters['producers']);
        }

        $Model->limit(2000);
        /*
                $data=$Model->get()->toArray();
                dd($data);
                */

        /*
        product_group_id
  */

        $data = $Model->get();
        $productGroupIds = $data->unique('product_group_id')->pluck('product_group_id')->toArray();
        $productGroupData = $this->getProductGroupsWithParentName($productGroupIds);
        foreach ($data as $k => $item) {
            $data[$k]['productGroupData'] = $productGroupData[$item->product_group_id];
            $data[$k]['sum_quantity'] = $item['quantity'] * $item['unitMultiplier'];
        }
        // $data[0]->xxx='xxx';
        // dd($data[0]->toArray());

        // ->toArray();

        return ['SQL' => getSql($Model), 'data' => $data->toArray()];
    }

    public function getStatisticsOrderFrequency(): array
    {
        // return \response()->json([__FILE__,__LINE__,$this->getStatisticsParameters()], 400);

        $Model = OrderArchive::where('orderType', OrderType::daily)
            ->where(function ($query) {
                $query->wherein('orderFlag', [OrderFlag::modifier])
                    ->orWhere('orderFlag', '=', null);
            });
        // wherein('orderFlag',[OrderFlag::modifier])->orWhere();
        if (count($this->statisticsParameters['profitCenters']) > 0) {
            $Model->whereIn('profit_center_id', $this->statisticsParameters['profitCenters']);
        }
        if (count($this->statisticsParameters['suppliers']) > 0) {
            $Model->whereIn('supplier_id', $this->statisticsParameters['suppliers']);
        }

        if ($this->statisticsParameters['dateFrom']) {
            $Model->where('deliveryDate', '>=', $this->statisticsParameters['dateFrom']);
        }
        if ($this->statisticsParameters['dateTo']) {
            $Model->where('deliveryDate', '<=', $this->statisticsParameters['dateTo']);
        }

        $Model->select(['profit_center_name', 'supplier_name', DB::raw('MAX(sumPrice) AS max_price, MIN(sumPrice) AS min_price, AVG(sumPrice) as avg_price, SUM(sumPrice) as sum_price, count(DISTINCT(deliveryDate)) as count_transaction'),
        ]);
        // ->with(['profitCenter','supplier']);
        $Model->groupBy('profit_center_name', 'supplier_name');
        $Model->orderBy('profit_center_name')->orderBy('supplier_name');

        $data = [];
        $data = $Model->get()->toArray();

        return ['SQL' => getSql($Model), 'data' => $data];

        return $Model->toSql();

        return $Model->get()->toArray();

        return $ProfitCenter->get()->toArray();

        return $this->getStatisticsParameters(null);

    }
}
