<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Producer;
use App\Models\Product;
use App\Models\ProductGroup;
use App\Models\ProfitCenter;
use App\Models\Supplier;
use App\Services\StatisticsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class StatisticsController extends Controller
{
    private StatisticsService $Service;

    public function __construct(StatisticsService $Service)
    {
        // parent::__construct();
        $this->Service = $Service;
    }

    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        $suppliers = Supplier::orderBy('name')->get(['id', 'name'])->toArray();
        $profitCenters = ProfitCenter::orderBy('name')->get(['id', 'name'])->toArray();
        $productGroups = ProductGroup::orderBy('name')->get(['id', 'name'])->toArray();
        $producer = Producer::orderBy('name')->get(['id', 'name'])->toArray();
        DB::statement("SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));");
        $hooreycaNames = Product::orderBy('buyerProductName')->where('buyerProductName', '!=', '')->groupBy('buyerProductName')->get(['id', 'buyerProductName as name'])->toArray();
        DB::statement("SET sql_mode=(SELECT CONCAT(@@sql_mode, ',ONLY_FULL_GROUP_BY'));");

        // dd($hooreycaNames);
        // dd(json_encode($service->getAvailableFilters()));
        return view('admin.statistics.index')->with(
            [
                'suppliers' => $suppliers,
                'profitCenters' => $profitCenters,
                'productGroups' => $productGroups,
                'producer' => $producer,
                'hooreycaNames' => $hooreycaNames,
                'formUUID' => \Str::uuid(),
                'availableFilters' => json_encode($this->Service->getAvailableFilters()),
            ]

        );
    }

    /**
     * Display the specified resource.
     */
    public function show(string $viewType): Response|JsonResponse
    {
        return response($viewType);
    }

    /**
     * Display the specified resource.
     *
     * @param  string  $viewType
     */
    public function getStat(Request $request): Response|JsonResponse
    {

        $type = ucfirst($request->input('type'));
        $functionName = 'getStatistics'.ucfirst($request->input('type'));
        $acceptedFieldsArrays = $this->Service->getAvailableFilters($type);
        foreach ($acceptedFieldsArrays as $acceptedField) {
            if ($request->get($acceptedField)) {
                if (is_array($request->get($acceptedField))) {
                    $this->Service->addStatisticsParameter($acceptedField, $request->get($acceptedField));
                } else {
                    $this->Service->setStatisticsParameters($acceptedField, $request->get($acceptedField));
                }
            }
        }
        if (! method_exists($this->Service, $functionName)) {
            return \response()->json([], 500);
        }

        $ret = $this->Service->$functionName();

        return \response()->json(['function' => $functionName, 'parameters' => $this->Service->getStatisticsParameters(), 'ret' => $ret, 'success' => true], 200);

        /*
         *
        $functionName = 'getStat' . ucfirst($request->input('type'));
        if (method_exists($this, $functionName)) {
            return call_user_func_array(array($this, $functionName),[$request]);
        }
        return \response()->json([], 400);

        dd($request);
        return $viewType;
         */
    }

    private function getStatOrderFrequency(Request $request): JsonResponse
    {

        $acceptedFieldsArrays = $this->Service->getAvailableFilters('OrderFrequency');
        foreach ($acceptedFieldsArrays as $acceptedField) {
            if ($request->get($acceptedField)) {
                if (is_array($request->get($acceptedField))) {
                    $this->Service->addStatisticsParameter($acceptedField, $request->get($acceptedField));
                } else {
                    $this->Service->setStatisticsParameters($acceptedField, $request->get($acceptedField));
                }
            }
        }
        /*
                $acceptedFieldsArrays=['suppliers','profitCenters','suppliers','productGroups','products'];
                foreach ($acceptedFieldsArrays as $acceptedField) {
                    if(is_array($request->get($acceptedField))){
                        $this->Service->addStatisticsParameter($acceptedField,$request->get($acceptedField));
                    }
                }
                $acceptedFields=['dateFrom','dateTo'];
                foreach ($acceptedFields as $acceptedField) {
                    if($request->get($acceptedField)){
                        $this->Service->setStatisticsParameters($acceptedField,$request->get($acceptedField));
                    }
                }
        */
        $ret = $this->Service->getStatOrderFrequencyStatistics();

        return \response()->json(['function' => __FUNCTION__, 'parameters' => $this->Service->getStatisticsParameters(), 'ret' => $ret, 'success' => true], 200);
    }

    private function getStatProductAmount(Request $request): JsonResponse
    {
        $ret = [];

        return \response()->json(['function' => __FUNCTION__, 'parameters' => $this->Service->getStatisticsParameters(), 'ret' => $ret, 'success' => true], 200);
    }

    private function getStatPriceChange(Request $request): JsonResponse
    {
        $ret = [];

        return \response()->json(['function' => __FUNCTION__, 'parameters' => $this->Service->getStatisticsParameters(), 'ret' => $ret, 'success' => true], 200);
    }

    public function getProductSearch(Request $request): JsonResponse
    {
        $page = $request->get('page');
        $resultCount = 25;

        $offset = ($page - 1) * $resultCount;

        $items = Product::with('supplier:id,name')->where('name', 'LIKE', '%'.$request->get('term').'%')->orWhere('supplierProductNumber', 'LIKE', '%'.$request->get('term').'%');
        $count = $items->count();
        //        $items=$items->orderBy('name')->skip($offset)->take($resultCount)->get(['supplier_id','id',DB::raw('name as text')]);
        $items = $items->orderBy('name')->skip($offset)->take($resultCount)->get(['supplier_id', 'id', 'name'])->toArray();
        // dd($items);
        foreach ($items as $k => $item) {
            $items[$k]['text'] = $item['name'];
            if ($item['supplier']) {
                $items[$k]['text'] .= ' ['.$item['id'].'/'.$item['supplier']['name'].']';
            }
            $items[$k]['id'] = $item['name'];

        }

        $endCount = $offset + $resultCount;
        $morePages = $endCount < $count;

        $results = [
            'results' => $items,
            'pagination' => [
                'more' => $morePages,
            ],
        ];

        return response()->json($results);
        dd($count, $offset, $endCount, $morePages, $items->toArray());
        dd($request->all());
    }
}
