<?php

namespace App\Http\Controllers;

use App\Enums\OrderFlag;
use App\Enums\OrderStatusEnum;
use App\Exports\ExportOrderInvoiceExcel;
use App\Models\Address;
use App\Models\Attachment;
use App\Models\Order;
use App\Models\OrderArchive;
use App\Models\OrderArchivesItem;
use App\Models\OrderNumber;
use App\Models\Product;
use App\Models\ProductGroup;
use App\Models\ProfitCenter;
use App\Models\Supplier;
use App\Models\SupplierNotifier;
use App\Models\Test;
use App\Repositories\ProductRepository;
use App\Repositories\SupplierRepository;
use App\Services\OrderService;
use App\Services\ProfitCenterService;
use ArrayObject;
use Barryvdh\DomPDF\Facade as PDF;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\App;
use Illuminate\View\View;
use Log;
use Maatwebsite\Excel\Facades\Excel;

class OrderController extends Controller
{
    protected OrderService $service;

    protected bool $testMode = false;

    public function __construct(OrderService $service)
    {
        $this->service = $service;
    }

    private function convertWeekProductSelectArrayToDays($Order, $indexed = 'weekDayPointer')
    {
        $orderItemsArray = (array) json_decode($Order->productSelected, true);
        $daysArray = [];
        foreach ($orderItemsArray as $productIndex => $productArray) {
            foreach ($productArray as $dayIndex => $value) {
                $daysArray[$dayIndex][$productIndex] = $value;
            }
        }
        if ($indexed == 'weekDayDate') {
            $ret = [];
            foreach ($daysArray as $dayNum => $dayData) {
                $deliveryDate = Carbon::parse($Order->deliveryDate);
                // var_export($dayNum-1);
                $deliveryDate->addDays($dayNum - 1);
                $ret[$deliveryDate->format('Y-m-d')] = $dayData;
            }
        } else {
            $ret = $daysArray;
        }
        ksort($ret);

        return $ret;
    }

    /**
     * Display a listing of the resource.
     */
    public function index(): View|Response|JsonResponse
    {
        // test mode

        /*
        $productRepo=new ProductRepository();
        $productsGroupIds=$productRepo->getSupplierProductGroupsIdFromPriceList(7,'2021-11-19',37);
        $ProductGroups=new ProductGroup();
        //dd($ProductGroups->allToTreeArray());
        dd($ProductGroups->nodesWithParentToTree($productsGroupIds));
*/
        /*     $productRepo=new ProductRepository();
             $products=$productRepo->getSupplierProductFromPriceList(7,'2021-11-19',37);
             dd($products);*/
        // debug('itt'.__LINE__);
        if (\request()->input('t') == 1) {
            if (\request()->input('w') == 1) {
                $testOrderId = 16497; // heti
                $testOrderId = 16467; // heti

                $testOrderId = 16507; // heti
                // $testOrderId=16512; //heti

            } else {
                $testOrderId = 12140; // napi
                $testOrderId = 16506; // napi
                $testOrderId = 16571; // napi
            }

            /******** create Excel ***********/
            return $this->testExcelCreate($testOrderId);

            /******** invoiceView test ***********/
            return $this->testInvoiceView($testOrderId);

            return response()->noContent();

            /******** set session order data***********/
            return $this->updateSend(\request(), $testOrderId);

            return response()->noContent();
            echo '<pre>';
            $this->updateSend(new Request, $testOrderId);

            $testOrderId = 62;

            /******** create Excel ***********/
            return $this->testExcelCreate($testOrderId);

            /******** create Pdf from oder ***********/
            return $this->testPdfCreate($testOrderId);

            /******** archiveOrder ***********/
            return $this->archiveOrder(null, $testOrderId);

            /******** Eamil send ***********/
            return $this->testSendEmail($testOrderId);

            /******** invoiceView test ***********/
            return $this->testInvoiceView($testOrderId);

            return response()->noContent();

            /******** getgumanId ***********/
            var_dump($this->getOrderHumanId($testOrderId));

            return response()->noContent();

            /******** createSupplierOrderNumber ***********/
            dd($this->createSupplierOrderNumber(244));

            return response()->noContent();

            /******** OrderHumanId test data***********/
            var_dump($this->getOrderHumanId(null, 1212, 'JANER', '2021-11-18', 'HAN'));
            var_dump($this->getOrderHumanId(1));

            return response()->noContent();

            /******** set session order data***********/
            return $this->testGetSessionData();

            /******** set session order data***********/
            return $this->testSetSessionData();

            debug($this->testMode);
            $orders = Order::where('profit_center_id', 1)->where('orderStatus', '!=', 'sent')->orderBY('deliveryDate')->get();
            if (count($orders->toArray()) > 0) {
                dd($orders->toArray());
            }
            dd('vege itt L:'.__LINE__);
        }

        if (! \request()->input('force')) {
            // dd(auth()->user()->id);
            $profitCenterId = auth()->user()->profitCenters()->first()->id;
            $orders = Order::with('supplier')->where('profit_center_id', $profitCenterId)->whereNotIn('orderStatus', ['sent', 'confirmed', 'archived'])->orderBY('deliveryDate')->get();
            debug($orders);
            if (count($orders->toArray()) > 0) {
                /*            $orders=$orders->sortBy(function($value,$key){
                                if(!$value->deliveryDate){
                                    return '9999-12-31';
                                }
                                return ($value->deliveryDate);
                            });*/
                // dd($orders->toArray());

                foreach ($orders as $order) {
                    $today = Carbon::parse(\Carbon\Carbon::now()->format('Y-m-d'));
                    $deliveryDate = \Carbon\Carbon::parse($order->deliveryDate);
                    // $order->a=$today->toString();
                    // $order->aa=\Carbon\Carbon::parse($order->deliveryDate)->toString();
                    $order->diffInHours = \Carbon\Carbon::parse($order->deliveryDate)->diffInHours($today);
                    $order->diffInDays = \Carbon\Carbon::parse($order->deliveryDate)->diffInDays($today);
                    $order->diffForHumans = \Carbon\Carbon::parse($order->deliveryDate)->diffForHumans($today);

                    if (! $order->deliveryDate) {
                        $order->diffWarningLevel = 99;

                        continue;
                    }
                    if ($order->deliveryDate < $today || $order->deliveryDate == $today) {
                        $order->diffWarningLevel = 0;

                        continue;
                    }
                    if ($order->diffInDays >= 1 && $order->diffInDays <= 3) {
                        $order->diffWarningLevel = 1;

                        continue;
                    }
                    $order->diffWarningLevel = 98;
                }
                $orders = $orders->sortBy(['diffWarningLevel', 'deliveryDate']);
                // dd($orders->toArray());

                return view('modules.order.indexSelect')->with([
                    'testMode' => $this->testMode,
                    'orders' => $orders,

                ]
                );
            }
            // dd(\request()->input('force'));
        }

        return view('modules.order.indexStepper')->with('testMode', $this->testMode);
    }

    private function testGetSessionData(): void
    {
        echo '<pre>';
        echo 'testGetSessionData';
        echo 'session_status():'.var_export(session_status(), true).PHP_EOL;
        echo "var_export(session()->get('orderData'),true):".PHP_EOL.var_export(session()->get('orderData'), true).PHP_EOL;
        echo 'var_export(session()->all(),true):'.PHP_EOL.var_export(session()->all(), true).PHP_EOL;

    }

    private function testSetSessionData(): void
    {
        echo '<pre>';
        echo 'testSetSessionData';
        $this->testGetSessionData();
        /******** set session order data***********/
        $orderDataForSession = [
            'productSelected' => [
                34 => '2',
                116 => '1',
            ],
            'supplierId' => '7',
            'contactName' => 'Contact Name',
            'note' => 'Note',
            'type' => 'daily',
            'deliveryDate' => '2021-11-15',
            'deliveryAddress' => '12',
        ];
        // print ":"..PHP_EOL;
        session()->put('orderData', $orderDataForSession);
        session()->save();
        echo "var_export(session()->get('orderData'),true):".PHP_EOL.var_export(session()->get('orderData'), true).PHP_EOL;
        \response();

        /************************/

    }

    private function testPdfCreate($orderId = null)
    {
        if (! $orderId) {
            $orderId = 1;
        }
        if (! $Order = Order::find($orderId)) {
            return \response()->json(['success' => false], 500);
        }
        $orderData = $this->getOrderData($Order->id);
        $pdf = PDF::loadView('modules.order.invoiceEmail', $orderData);

        return $pdf->stream();

        $attachmentFile = new Attachment;
        $ret = $attachmentFile->addStreamedFile($pdf->output());

        // $orderData=$this->getOrderData(null,$Order);
        // $ret=$attachmentFile->addStreamedFile(Excel::raw(new ExportOrderInvoiceExcel($orderData), \Maatwebsite\Excel\Excel::XLSX)) ;

        // $ret=$attachmentFile->addStreamedFile(Excel::raw(new ExportOrderInvoiceExcel($orderData), \Maatwebsite\Excel\Excel::XLSX)) ;
        /*
         * XLS formatumot tesztelni
         */
        dd($ret);

        return $pdf->stream();

    }

    private function testPdfCreateBlank()
    {
        \Debugbar::disable();

        $HTMLStr = '<html>
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 </head>
 <body>
     <p >árvíztűrő tükörfúrógép</p>
 </body>
 </html>';
        $HTMLStr = '<html>
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
     <style>
     body{
     font-family: DejaVu Sans
     }

 </style>
 </head>
 <body>
     <p >árvíztűrő tükörfúrógép</p>
 </body>
 </html>';

        //        return \response($HTMLStr);
        $pdf = PDF::loadHTML($HTMLStr);

        // $pdf->loadHTML('<h1>proba</h1>');
        return $pdf->stream('probacska.pdf');

    }

    private function testExcelCreate($orderId = null)
    {

        $orderData = $this->getOrderData($orderId);
        $orderData['feedBackIdLinkParam'] = base64_encode($orderData['feedBackId']);
        $orderData['sentTime'] = Carbon::now()->toDateTimeString();
        $orderData['noPrintButton'] = true;

        //        return view('modules.order.excelExport')->with($orderData);
        return Excel::download(new ExportOrderInvoiceExcel($orderData), 'invoices'.time().'.xlsx');

        // dd($orderData);
        return view('modules.order.excelExport')->with($orderData);
        dd($orderData['deliveryDate'], formatterDate($orderData['deliveryDate']));
        dd(formatterDate($orderData['deliveryDate']));
    }

    private function testSendEmail($orderId = null)
    {
        if (! $orderId) {
            $orderId = 1;
        }
        if (! $Order = Order::find($orderId)) {
            return \response()->json(['success' => false], 500);
        }
        $orderData = $this->getOrderData($orderId);
        $orderData['feedBackIdLinkParam'] = base64_encode($orderData['feedBackId']);

        // \Debugbar::disable();
        // return view('modules.order.invoiceEmail')->with($orderData);
        $orderData['noPrintButton'] = true;
        $HTMLInvoice = view('modules.order.invoice')->with($orderData
        )->render();
        $profitCenterName = 'Hankook - Delirest Étterem';
        $attach = null;
        $fileType = 'pdf';
        $fileType = 'excel';

        $fileName = preg_replace('/[^a-zA-Z0-9\-\._]/', '_', $orderData['humanId']);

        if ($fileType == 'pdf') {
            $pdf = PDF::loadView('modules.order.invoiceEmail', $orderData);
            $fileNameWithExt = $fileName.'.pdf';
            $attach = $pdf->output();
        } elseif ($fileType == 'excel') {
            $fileNameWithExt = $fileName.'.xlsx';
            /*            $fileExcel=Excel::download(new ExportOrderInvoiceExcel($orderData), $fileNameWithExt);
                        $attach=$fileExcel->getFile();
            */
            $attach = Excel::raw(new ExportOrderInvoiceExcel($orderData), \Maatwebsite\Excel\Excel::XLSX);
        }

        $send = \Mail::send('email.order', [
            'orderHTMLInvoice' => $HTMLInvoice,
            'orderData' => $orderData,
            'profitCenterName' => $profitCenterName,
        ], function ($m) use ($orderData, $attach, $fileNameWithExt) {
            $m->subject('Delirest - Hankook - '.$orderData['humanId']);
            // $m->to('beszerzes@eurest.hu');
            $m->to(config('mail.MailToOrderAddress'));
            if (config('mail.MailToOrderAddress') != 'city@e98.hu') {
                $m->bcc('city@e98.hu');
            }
            // $m->attach($attach,['as'=>$fileNameWithExt]);
            $m->attachData($attach, $fileNameWithExt);
        });
        debug($send);

        return \response('okes');

        return $pdf->stream($fileName);

        return \response($HTMLInvoice);

    }

    private function testInvoiceView($orderId = null)
    {

        if (! $orderId) {
            $orderId = 1;
        }
        if (! $Order = Order::find($orderId)) {
            return \response()->json(['success' => false], 500);
        }

        $orderData = $this->getOrderData($orderId);

        // print "<pre>";var_dump($orderData);print "</pre>";
        /*        $HTMLInvoice=view('modules.order.invoice')->with($orderData
                )->render();*/
        // $orderData['noPrintButton']=true;
        return view('modules.order.invoice')->with($orderData
        );

    }

    private function createSupplier(Request $request)
    {
        // select('name')->
        $profitCenterId = auth()->user()->profitCenters->first()->id;
        $accessSupplier = ProfitCenter::with('suppliers')->find($profitCenterId)->suppliers->pluck('id')->toArray();
        // $suppliers=Supplier::all()->toArray();
        $repo = new SupplierRepository;
        $suppliers = $repo->allWithRelations();
        $suppliers = array_filter($suppliers, function ($item) use ($accessSupplier) {
            if (in_array($item['id'], $accessSupplier)
                && $item['canSeeInOrder'] == 1) {
                return true;
            }

            return false;
        });

        return view('modules.order.supplier')->with([
            'suppliers' => $suppliers,
        ]);
    }

    private ?ProfitCenterService $ServiceProfitCenter = null;

    private function initProfitCenterService()
    {
        if (! $this->ServiceProfitCenter) {
            $this->ServiceProfitCenter = App::make(ProfitCenterService::class);
        }

        return $this->ServiceProfitCenter;
    }

    private function getProfitCenterAddress($ProfitCenter = null)
    {
        if (! $ProfitCenter) {
            $ProfitCenter = $this->initProfitCenterService()->getWithAllRelations(auth()->user()->profitCenters()->first()->id);
        }
        if ($ProfitCenter['addressEqual']) {
            $ProfitCenterAddress = $ProfitCenter['fullAddress'];
        } else {
            $address = $ProfitCenter['address'][0];
            $ProfitCenterAddress = "{$address['postCode']} {$address['city']} {$address['street']}";
        }

        return $ProfitCenterAddress;
    }

    private function createParameter(Request $request)
    {

        // $this->initProfitCenterService();
        // kiveheto innen??? vagy nem mert kell a multiaddresshez
        if (! $Order = Order::with('supplier')->find($request->get('id'))) {
            return false;
        }
        $supplierNote = null;
        if ($Order->supplier->note) {
            $supplierNote = $Order->supplier->note;
        }

        $ProfitCenter = $this->initProfitCenterService()->getWithAllRelations(auth()->user()->profitCenters()->first()->id);
        $oneAddress = true;
        $ProfitCenterAddress = '';
        if ($ProfitCenter['multiAddress']) {
            $oneAddress = false;
            $ProfitCenterAddress = [];
            foreach ($ProfitCenter['address'] as $address) {
                $ProfitCenterAddress[] = [
                    'id' => $address['id'],
                    'address' => $address['name'].' - '.$address['fullAddress'],
                ];
            }
        } else {
            $ProfitCenterAddress = $this->getProfitCenterAddress($ProfitCenter);

        }

        $hasCustomNotificationEmail = false;
        $CustomNotificationEmailData = [];
        $Supplier = Supplier::with('contactOrderMail')->find($Order->supplier->id);
        if (count($Supplier->contactOrderMail->toArray()) > 0) {
            $hasCustomNotificationEmail = true;
            $CustomNotificationEmailData = $Supplier->contactOrderMail->toArray();
        }

        return view('modules.order.parameter')->with([
            // 'supplier'=>$ProfitCenter[''],
            'oneAddress' => $oneAddress,
            'hasCustomNotificationEmail' => $hasCustomNotificationEmail,
            'CustomNotificationEmailData' => $CustomNotificationEmailData,
            'supplierNote' => $supplierNote,
            'profitCenterAddress' => $ProfitCenterAddress,

        ]);
    }

    private function createProductSelect(Request $request)
    {
        if (! $Order = Order::with('supplier', 'profitCenter')->find($request->get('id'))) {
            return false;
        }

        $productRepo = new ProductRepository;
        $productsGroupIds = $productRepo->getSupplierProductGroupsIdFromPriceList(
            $Order->supplier_id, $Order->deliveryDate);
        debug($productsGroupIds);
        $productGroupArray = [];
        if ($productsGroupIds && count($productsGroupIds) > 0) {
            $ProductGroups = new ProductGroup;
            $productGroupArray = $ProductGroups->nodesWithParentToTree($productsGroupIds);
        }

        return view('modules.order.productSelect')->with('productGroup', $productGroupArray);

        $ProductGroup = new ProductGroup;

        return view('modules.order.productSelect')->with('productGroup', $ProductGroup->allToTreeArray());
    }

    private function getOrderItemsProductIds(Order $Order)
    {
        $orderItemsArray = (array) json_decode($Order->productSelected);

        return array_keys($orderItemsArray);
    }

    private function getOrderItemsFromOrderData(?int $orderId = null, ?Order $Order = null)
    {
        if ($orderId) {
            $Order = Order::find($orderId);
        }
        if (! $Order) {
            return null;
        }
        $items = [];

        if ($Order->productSelected) {
            $productRepo = new ProductRepository;
            $productRepo->setNeedPrice(true);
            $productRepo->setDeliveryDate($Order->deliveryDate);

            $orderItemsArray = (array) json_decode($Order->productSelected, true);

            // $items=$productRepo->getWithRelations(array_keys($orderItemsArray));
            $items = $productRepo->getWithRelations($this->getOrderItemsProductIds($Order));
            if ($Order->productComment) {
                $orderItemsCommentArray = (array) json_decode($Order->productComment);
            } else {
                $orderItemsCommentArray = [];
            }
            if ($Order->orderType == 'daily') {
                foreach ($items as $key => $product) {

                    $quantity = $orderItemsArray[$product['id']];
                    $quantity = str_replace(',', '.', $quantity);
                    // debug($orderItemsArray[$product['id']],floatval($quantity));
                    if ($quantity > 0.01 || $quantity < 0.01) {
                        // $price=$product['last_price'][0]['pivot']['price'];
                        // $price=$product->price($Order->deliveryDate);
                        $items[$key]['quantity'] = $quantity;
                        // $items[$key]['price']=$price;
                        // $items[$key]['amount']=$quantity*$product['unitMultiplier']* $price;
                        $items[$key]['amount'] = floatval($quantity) * $product['unitMultiplier'] * $product['price'];
                        // unset($items[$key]['last_price']);
                        // debug($product['id']);
                        // debug($orderItemsCommentArray[$key]);
                        if (isset($orderItemsCommentArray[$product['id']])) {
                            $items[$key]['comment'] = $orderItemsCommentArray[$product['id']];
                        } else {
                            // $items[$key]['comment'] ='';
                        }
                    } else {
                        unset($items[$key]);
                    }
                }
            } elseif ($Order->orderType == 'weekly') {
                // print "<pre>";
                $weekDayItems = [];
                $deliveryDate = Carbon::parse($Order->deliveryDate);
                for ($i = 1; $i <= 7; $i++) {
                    $weekDayItem = [];
                    $weekDayItem['date'] = formatterDate($deliveryDate);
                    $weekDayItem['sumPrice'] = 0;
                    $weekDayItem['items'] = [];
                    foreach ($items as $key => $product) {
                        // dd([$orderItemsArray,$product['id'],$orderItemsArray[$product['id']][$i]]);
                        if (isset($orderItemsArray[$product['id']][$i])) {
                            // var_export([$key,$product['name']]);
                            $quantity = $orderItemsArray[$product['id']][$i];
                            $currentItemData = [
                                'quantity' => $quantity,
                                'amount' => floatval($quantity) * $product['unitMultiplier'] * $product['price'],
                                'name' => $product['name'],
                                'id' => $product['id'],
                            ];
                            if (isset($orderItemsCommentArray[$product['id']])) {
                                $currentItemData['comment'] = $orderItemsCommentArray[$product['id']];
                            }

                            $weekDayItem['items'][] = $currentItemData;
                            $weekDayItem['sumPrice'] += $currentItemData['amount'];
                        }
                    }
                    if (count($weekDayItem['items']) > 0) {
                        $weekDayItems[$i] = $weekDayItem;
                    }
                    $deliveryDate->addDays(1);
                }
                $products = $items;
                $items = [];
                foreach ($products as $product) {
                    $items['products'][$product['id']] = $product;
                }
                $items['weekDayItems'] = $weekDayItems;
                /*
                var_export($items['weekDayItems']);
                dd($items['weekDayItems']);
                dd($items);
                */
            }

        }

        return $items;
    }

    /*
     * @todo: deprecate ki kell vezetni, csak bemutatohoz hasznaltuk
     */
    private function getParsedOrderDataFromSession()
    {
        $orderData = session()->get('orderData');
        if (! $orderData) {
            $orderData = [
                'contactName' => '-',
                'note' => '',
                'deliveryDate' => '',
                'orderIdHuman' => '',
                'sumPrice' => 0,
                'items' => [],
                'productSelected' => [],
                'created_by' => Carbon::today(),
            ];

            return $orderData;
        }
        /*
        print "<pre>";
        var_dump($orderData);
        exit();

        */
        $orderData['created_by'] = \Carbon\Carbon::now();
        $productRepo = new ProductRepository;
        $productRepo->setRelation(
            'LastPrice');

        // var_dump(array_keys($orderData['productSelected']);
        $products = [];
        if (isset($orderData['productSelected']) && is_array($orderData['productSelected'])) {
            $products = $productRepo->getWithRelations(array_keys($orderData['productSelected']));
            $orderData['sumPrice'] = 0;
            foreach ($products as $key => $product) {
                $quantity = $orderData['productSelected'][$product['id']];
                if ($quantity > 0) {
                    $price = $product['last_price'][0]['pivot']['price'];

                    $products[$key]['quantity'] = $quantity;
                    $products[$key]['price'] = $price;
                    $products[$key]['amount'] = $quantity * $product['unitMultiplier'] * $price;
                    $orderData['sumPrice'] += $products[$key]['amount'];
                    unset($products[$key]['last_price']);
                } else {
                    unset($products[$key]);
                }

            }
        }

        /*            print "<pre>";
                    var_dump($products[0]);
                    print "</pre>";*/
        $orderData['items'] = $products;

        return $orderData;
    }

    private function createSupplierOrderNumberOLD(int $orderId): ?array
    {
        $ret = [];
        if ($Order = Order::find($orderId)) {
            if ($o = OrderNumber::where('order_id', $orderId)->get()->first()) {
            } else {
                $o = OrderNumber::create([
                    'year' => Carbon::createFromDate($Order->deliveryDate)->format('y'),
                    'supplier_id' => $Order->supplier_id,
                    'order_id' => $Order->id,
                ]);
            }
            $ret = $o->toArray();
        } else {
            $ret = null;
        }

        return $ret;
    }

    private function createSupplierOrderNumber(int $orderId): ?array
    {
        $ret = [];
        if ($Order = Order::find($orderId)) {
            // dd($Order->toArray());
            if ($o = OrderNumber::where('order_id', $orderId)->get()->first()) {
            } else {
                $orderYear = Carbon::createFromDate($Order->deliveryDate)->format('y');
                $maxSupplierOrderNumber = OrderNumber::where('supplier_id', $Order->supplier_id)
                    ->where('year', $orderYear)
                    ->max('supplier_order_number');
                $nextSupplierOrderNumber = $maxSupplierOrderNumber ? ($maxSupplierOrderNumber + 1) : 1;
                LOG::info(__FUNCTION__." OrderId: $orderId SupplierId:".$Order->supplier_id." maxSupplierOrderNumber> $maxSupplierOrderNumber nextSupplierOrderNumber>$nextSupplierOrderNumber");

                $maxRetry = 5;
                while ($maxRetry > 0) {
                    try {
                        $o = OrderNumber::create([
                            'supplier_order_number' => $nextSupplierOrderNumber,
                            'year' => $orderYear,
                            'supplier_id' => $Order->supplier_id,

                        ]);
                        $o->order_id = $orderId;
                        $o->save();
                        break;
                    } catch (\Exception $e) {
                        LOG::error('Error creating OrderNumber for supplier:'.$Order->supplier_id.' - '.$e->getMessage());
                        $maxRetry--;
                        $nextSupplierOrderNumber++;
                        usleep(rand(400, 600));
                    }
                }
                if (! $o) {
                    LOG::error('Error creating OrderNumber for supplier:'.$Order->supplier_id.' - maxRetry');
                    throw new \Exception('Error creating OrderNumber for supplier:'.$Order->supplier_id);

                    return null;
                }
            }
            $ret = $o->toArray();
        } else {
            $ret = null;
        }

        return $ret;
    }

    private function getOrderSumPrice(?int $orderId = null, ?Order $Order = null, ?array $itemsArray = null)
    {
        if ($orderId) {
            $Order = $Order->find($orderId);
        }
        if ($Order) {
            $itemsArray = $this->getOrderItemsFromOrderData(null, $Order);
        }
        $sumPrice = 0;
        if (is_array($itemsArray)) {
            foreach ($itemsArray as $item) {
                $sumPrice += $item['amount'];
            }
        }

        return $sumPrice;
    }

    public function getOrderData(?int $orderId = null, ?Order $Order = null): array
    {

        if (! $orderId) {
            $orderId = $Order->id;
        }

        if (! $Order = Order::with('supplier', 'profitCenter')->find($orderId)) {
            return false;
        }

        $orderData = $Order->toArray();

        if ($Order->orderType == 'weekly') {
            $orderData['items'] = $this->getOrderItemsFromOrderData(null, $Order);
            if (is_array($orderData['items']['weekDayItems'])) {
                $orderData['sumPrice'] = 0;
                foreach ($orderData['items']['weekDayItems'] as $weekDayItem) {
                    $orderData['sumPrice'] += $weekDayItem['sumPrice'];
                }
            }
        } else {
            $orderData['items'] = $this->getOrderItemsFromOrderData(null, $Order);
            $orderData['sumPrice'] = $this->getOrderSumPrice(null, null, $orderData['items']);
        }

        // dd($orderData);
        return $orderData;
    }

    private function getOrderStatus(int $orderId)
    {
        if ($Order = Order::find($orderId)) {
            return $Order->orderStatus;
        }

        return false;
    }

    private function updateStatus(int $orderId, string $status): bool
    {
        if ($Order = Order::find($orderId)) {
            $Order->orderStatus = $status;
            $Order->save();

            return true;
        }

        return false;
    }

    private function updateStatusFromRequest(): bool
    {
        if (\request()->input('id')) {
            if ($Order = Order::find(\request())) {
                if (\request()->input('type') &&
                    in_array(\request()->input('type'), OrderStatusEnum::getValues())
                ) {
                    return $this->updateStatus(\request()->input('id'),
                        \request()->input('type'));
                }
            }
        }

        return false;
    }

    private function createInvoice(Request $request)
    {
        // $orderData=$this->getParsedOrderDataFromSession();
        // $orderData['humanId']=$this->getOrderHumanId($orderData['id']);
        // debug($request->all());
        $orderData = [];
        if ($request->input('id')) {
            $orderData = $this->getOrderData($request->input('id'));
        }

        return view('modules.order.invoice', $orderData);
    }

    private function createSend(Request $request)
    {
        $orderData = [];
        if ($request->input('id')) {
            $orderData = $this->getOrderData($request->input('id'));
        }

        return view('modules.order.send', $orderData);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(Request $request): View|Response|JsonResponse
    {
        $functionName = 'create'.ucfirst($request->input('type'));
        if (method_exists($this, $functionName)) {
            if ($request->input('id')) {
                $orderStatus = $this->getOrderStatus($request->input('id'));
                if ($orderStatus && $orderStatus !== 'archived') {
                    $this->updateStatusFromRequest();
                } else {
                    return \response()->json([], 400);
                }
            }

            $result = call_user_func([$this, $functionName], $request);

            if ($result === false) {
                return \response()->json([], 400);
            }

            return $result;
        }

        return \response()->json([], 400);
    }

    private function getOrderHumanId(?int $orderId = null,
        ?int $orderNum = null,
        ?string $supplierShortName = null,
        ?string $deliveryDate = null,
        ?string $profitCenterName = null,
        ?string $orderType = null,
        ?string $orderPostfix = null

    ): string {
        $year = '';
        $orderTypeSign = [
            'weekly' => 'H',
            'weeklyDay' => 'H',
        ];
        if ($orderId) {
            $supplierShortName = '';
            $profitCenterName = '';
            $deliveryDate = '';
            if ($Order = Order::find($orderId)) {
                if ($Order->orderNumber) {
                    $orderNum = $Order->orderNumber->supplier_order_number;
                    $year = $Order->orderNumber->year;
                } else {
                    $deliveryDate = $Order->deliveryDate;
                }
                $supplierShortName = $Order->supplier->nameId;
                if ($Order->profitCenter) {
                    $profitCenterName = $Order->profitCenter->hooreycaId;
                }
                $orderType = $Order->orderType;
                if ($Order->orderType == 'weekly') {
                    $orderPostfix = $orderTypeSign[$Order->orderType];
                } elseif (! is_null($Order->parent_id)) {
                    /*
                     * ez csak akkor lehet igaz ha közvetlen heti rendeléshez kapcsolodik
                     * ha heti rendelés napjanak modositoja akkor mashogy kell kezelni!!!
                     */
                    $orderPostfix = $orderTypeSign['weeklyDay'];
                }
            }
        }

        if ($deliveryDate) {
            $year = substr($deliveryDate, 2, 2);
        }

        $humanId = "$supplierShortName/$profitCenterName/$year/"; // 'JANER/HANKOK/21/'

        if ($orderNum) {
            $humanId .= \Str::padLeft($orderNum, 4, '0'); // 'JANER/HANKOK/21/'.sprintf('%04d',$orderNum);
        }

        if ($orderType) {
            if (isset($orderTypeSign[$orderType])) {
                $orderPostfix = $orderTypeSign[$orderType];
            }
        }

        if (strlen($orderPostfix) > 0) {
            $humanId .= $orderPostfix;
        }

        return $humanId;
    }

    private function createOrder($supplierId, $parent_id = null, $orderType = null): Order
    {
        $Supplier = Supplier::find($supplierId);

        $Order = new Order;
        // debug(auth()->user()->profitCenters()->first()->id);
        $Order->profit_center_id = auth()->user()->profitCenters()->first()->id;
        $Order->supplier()->associate($Supplier);
        $Order->orderStatus = OrderStatusEnum::supplierSelect;
        if ($parent_id) {
            $Order->parent_id = $parent_id;
        }
        if ($orderType) {
            $Order->orderType = $orderType;
        }
        $Order->save();

        return $Order;
    }

    private function storeSupplierSelect($request)
    {
        if (! $request->get('supplierId')) {
            return \response()->json('need Supplier', 400);
        }

        /*
                $Supplier=Supplier::find($request->get('supplierId'));
                $Order=new Order();
                //debug(auth()->user()->profitCenters()->first()->id);
                $Order->profit_center_id=auth()->user()->profitCenters()->first()->id;
                $Order->supplier()->associate($Supplier);
                $Order->orderStatus=OrderStatusEnum::supplierSelect;
                $Order->save();
        */

        $Order = $this->createOrder($request->get('supplierId'));
        $orderData = $Order->toArray();

        return \response()->json(['success' => true, 'data' => $orderData]);

    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): Response|JsonResponse
    {
        debug($request->get('storeType'));
        if (strlen($request->input('storeType')) < 1) {
            return \response()->json([], 400);
        }
        $functionName = 'store'.ucfirst($request->input('storeType'));
        if (method_exists($this, $functionName)) {
            return call_user_func([$this, $functionName], $request);
        }

        return \response()->json([], 400);
    }

    /**
     * Display the specified resource.
     */
    public function show(int $OrderId): Response|JsonResponse
    {
        return response()->noContent();
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(int $OrderId): View
    {
        $orderData = [];
        if ($Order = Order::find($OrderId)) {
            $orderData = $Order->toArray();
        }
        $orderData['supplierId'] = $orderData['supplier_id'];
        if (! $orderData['productSelected']) {
            $orderData['productSelected'] = [];
        } else {
            // debug($orderData['productSelected']);
            $orderData['productSelected'] = json_decode($orderData['productSelected']);
        }
        if (! $orderData['productComment']) {
            $orderData['productComment'] = [];
        } else {
            // debug($orderData['productSelected']);
            $orderData['productComment'] = json_decode($orderData['productComment']);
        }

        unset($orderData['supplier_id']);
        $orderData['supplierName'] = $Order->supplier->name;

        return view('modules.order.indexStepper')->with([
            'testMode' => $this->testMode,
            'orderData' => $orderData,
        ]);
    }

    private function updateParameter(Request $request, int $orderId): JsonResponse
    {
        $ret = new ArrayObject;
        $ret['success'] = false;
        $acceptedIndex = [
            'contactName',
            'note',
            'orderType',
            'deliveryDate',
            'deliveryAddressId',
            'customNotificationEmail',
        ];
        $orderData = $request->all($acceptedIndex);
        $Order = Order::find($orderId);
        // $orderData->de
        if (! $orderData['deliveryAddressId']) {
            $orderData['deliveryAddressId'] = null;
            $deliveryAddress = $this->getProfitCenterAddress();
            if (! $Order->deliveryAddress || $Order->dedeliveryAddress != $deliveryAddress) {
                $orderData['deliveryAddress'] = $deliveryAddress;
            }
        } else {
            if ($Order['deliveryAddressId'] !== $orderData['deliveryAddressId']) {
                $addressData = Address::find($orderData['deliveryAddressId']);
                $orderData['deliveryAddress'] = $addressData->fullAddress;
                $orderData['deliveryAddressName'] = $addressData->name;
            }
        }
        if (! $orderData['customNotificationEmail']) {
            $orderData['customNotificationEmail'] = null;
        } else {
            if ($orderData['customNotificationEmail'] == '') {
                $orderData['customNotificationEmail'] = null;
            }
        }

        $diffDay = Carbon::parse($orderData['deliveryDate'])->diffInDays(Carbon::now(), false);
        if ($diffDay > 0) {
            return \response()->json([
                'success' => false,
                'errors' => ['Nem megfelelő dátum'],
            ], 500);
        }

        // var_export($Order->toArray());
        $Order->fill($orderData);
        // var_export($Order->toArray());die();

        $Order->orderStatus = OrderStatusEnum::parameter;
        $Order->save();
        $ret['orderData'] = $Order->toArray();
        $ret['success'] = true;

        return \response()->json($ret);
    }

    private function updateProductSelect(Request $request, int $orderId): JsonResponse
    {
        $acceptedIndex = [
            'productSelected',
            'productComment',
            'supplierId',
            'contactName',
            'note',
            'orderType',
            'deliveryDate',
            'deliveryAddress',
        ];
        $orderData = $request->all($acceptedIndex);
        debug($orderData);
        // session()->forget('orderData');
        session()->put('orderData', $orderData);
        session()->save();
        $Order = Order::find($orderId);
        if (isset($orderData['productSelected']) && is_array($orderData['productSelected'])) {
            $Order->productSelected = json_encode($orderData['productSelected']);
        } else {
            $Order->productSelected = null;
        }
        if (isset($orderData['productComment']) && is_array($orderData['productComment'])) {
            $Order->productComment = json_encode($orderData['productComment']);
        } else {
            $Order->productComment = null;
        }

        $Order->orderStatus = OrderStatusEnum::productSelect;
        $Order->save();

        // sleep(2);
        return \response()->json(['success' => true, 'data' => $orderData]);
    }

    private function storeAttachedFile(): void {}

    private function OrderStorno(Order $OrderOriginal): Order
    {
        if (true) {
            $OrderStorno = $OrderOriginal->replicate([
                'archive_id',
                'productSelected',
                'humanId',
                'supplierOrderNumber',
                'feedBackId',
                'confirmed',
                'created_by',
                'updated_by',
                'deleted_by',
                'deleted_at',
            ])->fill([
                'sentTime' => Carbon::now(),
                'orderFlag' => OrderFlag::storno,
                'rel_id' => $OrderOriginal->id,
                'sumPrice' => (0 - $OrderOriginal->sumPrice),
                'orderStatus' => OrderStatusEnum::sent,
            ]);
            $productSelected = [];
            foreach (json_decode($OrderOriginal->productSelected) as $index => $item) {
                $productSelected[$index] = 0 - $item;
            }
            $OrderStorno->productSelected = json_encode($productSelected);
            $OrderStorno->save();
            $OrderStorno = $this->createOrderIds($OrderStorno);
        } else {
            $OrderStorno = Order::find(16515);
            $OrderStorno->sentTime = Carbon::now();
            $OrderStorno = $this->createOrderIds($OrderStorno);
            $OrderStorno->save();
        }

        return $OrderStorno;
        /*
         * ha kell itt lehet ay OrderOriginalra raragasztani a rel_id hogy meglegyen hol lett stornozva
         */
        // dd($OrderOriginal->toArray(),$OrderStorno->toArray());
    }

    private function modifierOrder($Order): OrderArchive
    {
        // create new storno order
        // archive storno order
        $originalArchiveOrder = OrderArchive::find($Order->rel_id);
        $originalOrder = Order::where('humanId', $originalArchiveOrder->humanId)->first();
        /*
         * create storno Order
         */
        $OrderStorno = $this->OrderStorno($originalOrder);
        $orderStornoArchive = $this->archiveOrder($OrderStorno);
        $orderStornoArchive->rel_id = $originalArchiveOrder->id;
        $orderStornoArchive->save();

        return $orderStornoArchive;
        dd($Order->toArray());
    }

    private function archiveOrder(?Order $Order = null, ?int $orderId = null, ?int $parentId = null): OrderArchive|false
    {

        debug('archivalas indul');
        /*        print "\n*****************************\n";
                var_dump('archivalas indul');*/
        if (! $Order) {
            debug('Nincs order');
            // var_dump('Nincs order');
            if (! $Order = Order::find($orderId)) {
                return false;
            }
        }

        // var_dump($Order->toArray());
        if ($Order->orderStatus !== OrderStatusEnum::sent) {
            // var_dump('nem jo status');
            debug('nem jo status');

            return false;
        }

        if ($Order->orderFlag == 'modifier') {
            $this->modifierOrder($Order);
        }

        debug('archivalunk');
        // var_dump('**uj archiv nyitasa kezdet');
        $debugArray = [];
        // array_unshift($debugArray,$Order->toArray());
        $orderData = $this->getOrderData($Order->id);
        array_unshift($debugArray, $orderData);
        // dd('tova'.__LINE__,$Order->toArray(),$orderData);

        /**
         * uj archiv nyitasa
         */
        $OrderArchive = new OrderArchive;
        $exclude = ['id'];
        $prefixed = ['created_by', 'updated_by', 'deleted_by', 'created_by', 'updated_by', 'deleted_by'];
        foreach ($Order->toArray() as $k => $v) {
            if (! in_array($k, $exclude)) {
                if (in_array($k, $prefixed)) {
                    $k = 'original_'.$k;
                }
                $OrderArchive->$k = $v;
            }
        }
        $OrderArchive->profit_center_name = $orderData['profit_center']['name'];
        $OrderArchive->supplier_name = $orderData['supplier']['name'];
        $OrderArchive->supplier_emailAttachmentType = $orderData['supplier']['emailAttachmentType'];
        if ($parentId) {
            $OrderArchive->parent_id = $parentId;
        }

        $OrderArchive->save();
        if ($Order->orderFlag == 'modifier') {
            $originalArchiveOrder = OrderArchive::find($Order->rel_id);
            $originalArchiveOrderId = $originalArchiveOrder->id;
            $originalArchiveOrder->orderFlag = OrderFlag::modified;
            $originalArchiveOrder->rel_id = $OrderArchive->id;
            $originalArchiveOrder->save();
        }

        array_unshift($debugArray, $OrderArchive->toArray());
        // dd($orderData);
        // var_dump('**csatolmany mentes kezdet');
        /**
         * csatolmany elmentese
         */
        $fileType = $orderData['supplier']['emailAttachmentType'];
        if ($fileType !== 'nincs') {
            $fileName = preg_replace('/[^a-zA-Z0-9\-\._]/', '_', $orderData['humanId']);
            if ($fileType == 'pdf') {
                $pdf = PDF::loadView('modules.order.invoiceEmail', $orderData);
                $fileNameWithExt = $fileName.'.pdf';
                $attach = $pdf->output();
            } elseif ($fileType == 'excel') {
                $attach = Excel::raw(new ExportOrderInvoiceExcel($orderData), \Maatwebsite\Excel\Excel::XLSX);
                $fileNameWithExt = $fileName.'.xlsx';
            }
            // file eltarolasa
            $attachmentFile = new Attachment;
            $attachmentFile->addStreamedFile($attach, $fileNameWithExt);
            // fajl csatolasa
            $attachmentFile->attachable()->associate($OrderArchive);
            $attachmentFile->save();
            array_unshift($debugArray, $attachmentFile->toArray());

        }
        // var_dump('**tetelek mentes kezdet');

        if ($Order->orderType !== 'weekly') {
            /**
             * tetelek elmentese
             */
            array_unshift($debugArray, $orderData['items']);
            $exclude = ['id', 'created_at', 'updated_at', 'deleted_at', 'created_by', 'updated_by', 'deleted_by',
            ];
            $exclude = array_merge($exclude, Product::getRelationshipsNames(true, 'snake_case'));
            foreach ($orderData['items'] as $orderItem) {
                $OrderArchiveItem = new OrderArchivesItem;
                foreach ($orderItem as $k => $v) {
                    if (! in_array($k, $exclude)) {
                        if (! is_array($v)) {
                            $OrderArchiveItem->$k = $v;
                        }
                    }
                }
                $OrderArchiveItem->order_archive_id = $OrderArchive->id;
                $OrderArchiveItem->supplier_name = $orderItem['supplier']['name'];
                if (isset($orderItem['producer'])) {
                    $OrderArchiveItem->producer_name = $orderItem['producer']['name'];
                }
                if (isset($orderItem['product_group'])) {
                    $OrderArchiveItem->product_group_name = $orderItem['product_group']['name'];
                }
                $OrderArchiveItem->price = $orderItem['price'];
                $OrderArchiveItem->quantity = $orderItem['quantity'];
                $OrderArchiveItem->amount = $orderItem['amount'];
                $OrderArchiveItem->save();
            }
            // array_unshift($debugArray,$OrderArchiveItem->toArray());
        }

        // dd($debugArray);
        return $OrderArchive;
    }

    private function createOrderIds($Order = null, $orderId = null, $parentId = null): Order|false
    {
        if (! $Order) {
            $Order = Order::find($orderId);
        }
        if (! is_null($Order->supplierOrderNumber)) {
            return $Order;
        }
        $supplierOrderID = $this->createSupplierOrderNumber($Order->id);
        // debug($supplierOrderID);
        $Order->supplierOrderNumber = $supplierOrderID['supplier_order_number'];
        $Order->humanId = $this->getOrderHumanId($Order->id);
        $Order->feedBackId = (string) \Str::orderedUuid();
        if ($parentId) {
            $Order->parentId = $parentId;
        }
        $Order->save();

        return $Order;
    }

    private function createWeekDayOrders(Order $Order, $status = 'send')
    {
        // $orderData=$this->getOrderData($Order->id);
        $orderData = [];
        $needCopyFromOriginalOrderPointers = [
            'contactName',
            'note',
            'deliveryAddressId',
            'deliveryAddressName',
            'deliveryAddress',
            'customNotificationEmail',
            'productComment',
        ];
        $productDaysArray = $this->convertWeekProductSelectArrayToDays($Order, 'weekDayDate');
        foreach ($productDaysArray as $dayDate => $dayData) {
            // check if exist
            $dayOrder = Order::where('parent_id', $Order->id)->where('deliveryDate', $dayDate)->get();
            if (count($dayOrder) > 0) {
                continue;
            }
            // create day Order
            $dayOrder = $this->createOrder($Order->supplier_id, $Order->id);
            foreach ($needCopyFromOriginalOrderPointers as $pointer) {
                $dayOrder->setAttribute($pointer, $Order->getAttribute($pointer));
            }
            $dayOrder->deliveryDate = $dayDate;
            $dayOrder->productSelected = json_encode($dayData);
            $dayOrder->save();
            $orderData = $this->getOrderData(null, $dayOrder);
            $dayOrder->sumPrice = $orderData['sumPrice'];
            $dayOrder = $this->createOrderIds($dayOrder);
            $dayOrder->orderStatus = $status;
            $dayOrder->save();
        }
    }

    private function makeEmailAttachment($orderData, $fileType): array
    {
        $ret = [];
        $fileName = preg_replace('/[^a-zA-Z0-9\-\._]/', '_', $orderData['humanId']);
        if ($fileType == 'pdf') {
            $pdf = PDF::loadView('modules.order.invoiceEmail', $orderData);
            $ret = [
                'fileNameWithExt' => $fileName.'.pdf',
                'attach' => $pdf->output(),
            ];
        } elseif ($fileType == 'excel') {

            /*            $fileExcel=Excel::download(new ExportOrderInvoiceExcel($orderData), $fileNameWithExt);
                        $attach=$fileExcel->getFile();
            */
            /*
            $fileNameWithExt=$fileName.'.xlsx';
            $attach=Excel::raw(new ExportOrderInvoiceExcel($orderData), \Maatwebsite\Excel\Excel::XLSX);
            */
            $ret = [
                'fileNameWithExt' => $fileName.'.xlsx',
                'attach' => Excel::raw(new ExportOrderInvoiceExcel($orderData), \Maatwebsite\Excel\Excel::XLSX),
            ];
        }

        return $ret;
    }

    public function getEmailAttachment($orderData, $fileType): array
    {
        $ret = [];
        $ret[] = $this->makeEmailAttachment($orderData, $fileType);
        if ($orderData['orderType'] == 'weekly') {
            foreach (Order::find($orderData['id'])->children->toArray() as $dayOrder) {
                $dayOrderData = $this->getOrderData($dayOrder['id']);
                if (is_null($dayOrderData['sentTime'])) {
                    $dayOrderData['sentTime'] = Carbon::now()->toDateTimeString();
                }
                $ret[] = $this->makeEmailAttachment($dayOrderData, $fileType);
            }
        }

        return $ret;
    }

    private function updateSend(Request $request, int $orderId): JsonResponse
    {
        if (! $Order = Order::find($orderId)) {
            return \response()->json(['success' => false], 500);
        }
        $diffDay = Carbon::parse($Order->deliveryDate)->diffInDays(Carbon::now(), false);

        if ($diffDay > 0) {
            return \response()->json([
                'success' => false,
                'errors' => ['Nem megfelelő dátum ['.$Order->deliveryDate.']'],
            ], 500);
        }

        /*
                 sleep(3);
                return \response()->json([
                    'success' => true,
                    'retHTML'=>'$HTMLInvoice'
                ]);

                return \response()->json([
                    'success' => false,
                    'errors' => ['Nem megfelelő dátum [' . $Order->deliveryDate . ']']
                ], 500);
        */

        $Order = $this->createOrderIds($Order);
        $orderData = $this->getOrderData($Order->id);
        $Order->sumPrice = $orderData['sumPrice']; // nem a legszebb, de ott mar kiszamolasra kerult.

        /*
         * heti esetén legyártani a napikat!!!
         */
        if ($Order->orderType == 'weekly') {
            $this->createWeekDayOrders($Order);
        }

        /*
         * update order
         */
        $Order->orderStatus = OrderStatusEnum::send;
        $Order->save();
        $orderData['feedBackIdLinkParam'] = base64_encode($orderData['feedBackId']);
        $orderData['sentTime'] = Carbon::now()->toDateTimeString();
        $orderData['noPrintButton'] = true;
        $HTMLInvoice = view('modules.order.invoice')->with($orderData
        )->render();

        if ($Order->orderFlag == OrderFlag::modifier) {
            // parent_id ha van akkor heti napjanak modositasa
            // dd($orderData,formatterDate(Carbon::parse($orderData['deliveryDate'])->startOfWeek()),formatterDate(Carbon::parse($orderData['deliveryDate'])->endOfWeek()));
            // dd($orderData,$Order->toArray());
        }

        $attach = null;
        $fileNameWithExt = 'blank.txt';
        $fileType = 'pdf';
        $fileType = 'excel';
        $fileType = $orderData['supplier']['emailAttachmentType'];

        // return \response()->json(['success'=>true],201);

        if (true) {
            $attachments = $this->getEmailAttachment($orderData, $fileType);
            \Mail::send('email.order', [
                'orderHTMLInvoice' => $HTMLInvoice,
                'orderData' => $orderData,

            ], function ($m) use ($orderData, $fileType, $attachments) {

                $subject = 'Delirest - '.$orderData['profit_center']['name'].' - '.$orderData['humanId'];
                if ($orderData['orderFlag'] == OrderFlag::modifier) {
                    $subject .= ' MÓDOSÍTÁS';
                }
                $m->subject($subject);
                if ($orderData['customNotificationEmail'] && $orderData['customNotificationEmail'] != 'NULL') {
                    $m->to($orderData['customNotificationEmail']);
                }

                if (config('app.stage', 'DEV') == 'PROD') {
                    $m->to($orderData['supplier']['orderEmail']);
                    if ($orderData['supplier']['orderEmail2']) {
                        $m->to($orderData['supplier']['orderEmail2']);
                    }
                } else {
                    $m->to(config('mail.MailToOrderAddress'));
                }

                if (config('mail.MailToOrderAddress') != 'city99@e98.hu') {
                    $m->bcc('city@e98.hu');
                }
                // $m->attach($attach,['as'=>$fileNameWithExt]);
                if ($fileType !== 'none') {
                    if (is_array($attachments) && count($attachments) > 0) {
                        foreach ($attachments as $attachData) {
                            $m->attachData($attachData['attach'], $attachData['fileNameWithExt']);
                        }
                    }
                }
            });
        }
        $Order->sentTime = $orderData['sentTime'];
        $Order->orderStatus = OrderStatusEnum::sent;
        $Order->save();
        /*
         * @todo:eredei archivra modified flaget tenni, rel_id-t beallitani
         * @todo:uj archivra rel_id-t beallitani
         */
        if ($OrderArchived = $this->archiveOrder($Order)) {
            $Order->orderStatus = OrderStatusEnum::archived;
            $Order->save();
            $SupplierNotifier = new SupplierNotifier;
            $SupplierNotifier->makeNotificationsForOrderArchive($OrderArchived->id);
        }

        if ($Order->orderType == 'weekly') {
            foreach (Order::find($orderData['id'])->children as $dayOrder) {
                $dayOrder->orderStatus = OrderStatusEnum::sent;
                $dayOrder->sentTime = $orderData['sentTime'];
                $dayOrder->save();
                if ($this->archiveOrder($dayOrder, null, $OrderArchived->id)) {
                    $dayOrder->orderStatus = OrderStatusEnum::archived;
                    $dayOrder->save();
                } else {
                    // dd('Archive Error!!!!');
                }
            }
        }

        return \response()->json(['success' => true, 'retHTML' => $HTMLInvoice]);

        var_dump('updateSend End '.__LINE__);
        dd($orderData);

        return \response()->json(['success' => true], 201);

    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, int $orderId): JsonResponse
    {
        debug($request->get('updateType'));
        if (strlen($request->input('updateType')) < 1) {
            return \response()->json([], 400);
        }
        $functionName = 'update'.ucfirst($request->input('updateType'));
        if (method_exists($this, $functionName)) {
            return call_user_func_array([$this, $functionName], [$request, $orderId]);
        }

        return \response()->json([], 400);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $OrderId): Response|JsonResponse
    {
        if ($Order = Order::find($OrderId)) {
            if ($Order->delete()) {
                return \response()->json(['success' => true]);
            }
        }

        return \response()->json([
            'success' => false,
            'errors' => ['deleted error'],
        ], 500);
    }

    public function getDataTableContent(): JsonResponse
    {
        $groupId = null;
        $searchStr = null;
        $profitCenterId = auth()->user()->profitCenters()->first()->id;
        if (\request()->get('supplierId')) {
            $supplierId = \request()->get('supplierId');
        } else {
            return \response()->json(['data' => []]);
        }

        if (\request()->get('deliveryDate')) {
            $deliveryDate = \request()->get('deliveryDate');
        } else {
            $deliveryDate = Carbon::now()->format('Y-m-d');
        }

        $special = [];
        $special['withFavorites'] = true;
        if (\request()->get('searchStr')) {
            $searchStr = \request()->get('searchStr');
            if (substr($searchStr, 0, 2) == '**') {
                $special['type'] = str_replace('*', '', $searchStr);
                $special['profitCenterId'] = $profitCenterId;
                $searchStr = null;
            }
        } else {
            if (\request()->get('groupId')) {
                $groupId = \request()->get('groupId');
            }
        }

        if (\request()->get('krel')) {
            if (request()->get('krel') === 'true') {
                $special['krel'] = 1;
            }
        }

        debug(\request()->all());
        $productRepo = new ProductRepository;
        $productRepo->setRelation(
            'ProductGroup', 'Supplier', 'Producer', 'PriceList', 'LastPrice', 'picture', 'specification');
        // $products=$productRepo->getByGroupId($groupId,true);
        $products = $productRepo->getSupplierProductFromPriceList($supplierId, $profitCenterId, $deliveryDate, $groupId, $searchStr, $special);
        // debug($products[1]);
        $ret = ['data' => []];
        // dd($products);
        foreach ($products as $product) {
            // dd(count($product['price_list']));
            // if(count($product['price_list'])>0){
            if ($product['price_list_price']) {
                $data = [];
                $data['id'] = $product['id'];
                $data['name'] = $product['name'];
                $data['packing'] = $product['packing'];
                $data['unitValue'] = $product['unitValue'];
                $data['productUnit'] = $product['productUnit'];
                $data['sellerUnit'] = $product['sellerUnit'];
                $data['unitMultiplier'] = $product['unitMultiplier'];
                $data['amountUnit'] = $product['amountUnit'];

                $data['note'] = ($product['note'] ? $product['note'] : '');
                // $product['product_group']['name'];
                // $data['price']=$product['last_price'][0]['pivot']['price'];
                $data['price'] = $product['price_list_price']['price'];
                $data['hooreycaId'] = $product['hooreycaId'];
                $data['office'] = '';
                $data['extn'] = '';
                $data['favorites'] = $product['favorites'];
                if ($product['krel'] == 1) {
                    $product['krel'] = '*';
                } else {
                    $product['krel'] = '';
                }
                $data['krel'] = $product['krel'];

                $data['picture'] = false;
                if ($product['picture']) {
                    // $data['aa_picture']=$product['picture'];
                    $data['picture'] = $product['picture']['PublicUrl'].DIRECTORY_SEPARATOR.$product['picture']['filename'];
                }
                $data['specification'] = false;
                if ($product['specification']) {
                    // $data['aa_specification']=$product['specification'];
                    $data['specification'] = $product['specification']['PublicUrl'].DIRECTORY_SEPARATOR.$product['specification']['filename'];
                }
                $ret['data'][] = $data;
            } else {

            }
        }

        return \response()->json($ret);

        return \response()->file('exapmle2.json');

    }

    public function checkReadyToSend(Request $request, int $orderId): JsonResponse
    {
        $readyToSend = true;
        $orderData = $this->getParsedOrderDataFromSession();
        debug($orderData);
        $why = [];
        if (! isset($orderData['supplierId']) || $orderData['supplierId'] < 1) {
            $why[] = 'supplierId';
            $readyToSend = false;
        }
        if (! isset($orderData['items']) || ! is_array($orderData['items']) || count($orderData['items']) < 1) {
            $why[] = 'items';
            $readyToSend = false;
        }

        return \response()->json(['success' => true, 'readyToSend' => $readyToSend, 'orderData' => $orderData, 'why' => $why]);
    }
}
