<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attachment;
use App\Models\PriceList;
use App\Models\Supplier;
use App\Services\PriceListService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Rap2hpoutre\FastExcel\FastExcel;

class PriceListController extends Controller
{
    protected PriceListService $service;
    /*

        protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSortKRELHooreyca.xlsx';
        protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceList.xlsx';
        protected $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListOriginal.xlsx';
        protected $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListFieldTypeError.xlsx';
        protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSort.xlsx';
        protected string $testFile='V:\!EurestNew\Katitol\Jáner 2021.12.13-tólv2.xlsx';
        protected string $testFile='V:\!EurestNew\Katitol\Egertej egységes árlista - 2021.12.01-től.xlsx';
        protected string $testFile='V:\!EurestNew\Katitol\Rozmár Egységes árlista 2021.11.15v2.xlsx';
        protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSort.xlsx';
        protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSortKREL.xlsx';
        protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSortKRELHooreyca.xlsx';
     */

    protected string $testFile = 'V:\!EurestNew\doc\forrasAnyagok\examplePriceListSortKREL.xlsx';

    protected bool $testFileMod = false;

    protected int $dataStartLine = 3;

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

    /**
     * Display a listing of the resource.
     */
    public function index(): View|Response|JsonResponse
    {
        // test
        if (\request()->input('t') == 1) {

            $priceListId = 222;
            $repository = new \App\Repositories\PriceListRepository;
            $ret = ['data' => []];
            $repository->setRelation('attachment');
            $priceList = $repository->getQueryWithRelations()->find($priceListId);
            /*
             * árlistábol kell a suppplier ID
             * supplierbol kellenek a csatolt egységek
             * $S->pluck????
             */
            $supplier = Supplier::with('profitCenter')->find($priceList->supplier_id);
            // print "<pre>";
            // profit_center
            // Supplier::with('profitCenter')->pluck('profitCenter.id')->toArray()
            $destEmail = $supplier->profitCenter->pluck('email', 'name')->filter(function ($value) {
                return ! is_null($value);
            });

            if ($destEmail->isEmpty()) {
                return response()->noContent();
            }

            // ->filter(function ($value){return !is_null($value);})

            $emailData['priceList']['note'] = $priceList->note;
            $emailData['priceList']['filename'] = $priceList->attachment->filename;
            $emailData['priceList']['fileName'] = $priceList->attachment->original_filename;
            $emailData['priceList']['url'] = $priceList->attachment->PublicUrl;

            $MailData['HTML'] = view('email.priceListChangeNotify')->with($emailData)->render();

            echo '<pre>';
            $destEmail->each(function ($emailAddress) use ($emailData) {
                var_export($emailAddress);

                \Mail::send('email.priceListChangeNotify', $emailData, function ($m) use ($emailAddress) {
                    $m->subject('Árlista változás ');
                    $m->to($emailAddress);
                    /*
                    if(env('APP_STAGE')=='PROD'){
                        $m->to($emailAddress);
                    }else{
                        if(env('APP_STAGE')=='TEST'){
                            $m->to('beszerzes@delirest.hu');
                        }
                        if(env('APP_STAGE')=='DEV'){
                            $m->to('city@e98.hu');
                        }

                    }
                    */

                    if (env('MAIL_TO_ORDER_ADDRESS') != 'city@e98.hu') {
                        $m->bcc('city@e98.hu');
                    }
                    // $m->attach($attach,['as'=>$fileNameWithExt]);
                    // $m->attachData($attach,$fileNameWithExt);
                });

            });

            /*
            print "<pre>";
            var_export($destEmail);
            var_export($item->toArray());
            var_export($emailData);
            return view('email.priceListChangeNotify')->with($emailData);

*/
            dd('end');

            dd([$destEmail->filter(function ($value) {
                return ! is_null($value);
            }), $priceListId, $item, $S]);

            $importStartLine = $this->dataStartLine;
            $importLength = 9999;
            // $importStartLine = rand(100,400);
            $importLength = 10;
            $collection = $this->getRowCollection();

            /*$startDate = $collection[0][1];
            $supplierName = $collection[1][1];
            */
            $supplierId = 9;
            $availableDate = '2022-01-26';
            $res = $this->service->importPriceList($supplierId, $availableDate, $collection->slice($importStartLine, $importLength)->toArray());
            // $res = $this->service->importPriceListCheck($supplierId, $collection->slice($importStartLine,$importLength)->toArray());
            echo '<pre>';
            dd($res);
            // @todo: file attachment storage

            dd($res, $res['rows'][1]['originalData'], $this->service->getError());
            $success = false;
            if ($res) {
                if ($res['importSuccess'] == true) {
                    $success = true;
                }
            }

            return \response()->json([
                'success' => $success,
                'error' => $this->service->getError(),
            ]);

            $collection = $this->getRowCollection();

            // $startDate=$collection[0][1];
            // $supplierName=$collection[1][1];
            $supplierId = 7;
            $availableDate = '2022-01-01';
            if (! $return = $this->service->importPriceListCheck($supplierId, $collection->slice($this->dataStartLine)->toArray())) {
                // if(!$return=$this->service->importPriceListCheck(99999,[])){
                $return = $this->service->getError();

                return \response()->json([
                    'success' => false,
                    // 'file'=>$file->getLinkTarget(),
                    // 'item'=>$collection[0],
                    'error' => $return,
                ], 500);
            }
            dd($return);

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

        }

        $suppliers = Supplier::orderBy('name')->get(['id', 'name'])->toArray();
        // var_dump($this->testFileMod);

        return view('admin.priceList.index')->with(
            ['suppliers' => $suppliers,
                'testFileMod' => ($this->testFileMod) ? 'true' : 'false',
            ]

        );
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        $suppliers = Supplier::orderBy('name')->get(['id', 'name'])->toArray();

        return view('admin.priceList.create')->with(
            ['suppliers' => $suppliers,
                'testFileMod' => $this->testFileMod,
            ]

        );

    }

    private function getSourceFileName()
    {
        if ($this->testFileMod) {
            /*
             * A teszt fajlal dolgozunk
             *
             */
            $fileName = basename($this->testFile);
        } else {
            /*
             * A feltott fajlal dolgozunk
            $file=$file->getLinkTarget(); //nem mukodik splfileinfo elszall file olvasasi hibaval
            $file = $request->file('priceListFile');
             */
            $fileName = $_FILES['priceListFile']['name'];
        }

        return $fileName;
    }

    private function getSourceFile()
    {
        if ($this->testFileMod) {
            /*
             * A teszt fajlal dolgozunk
             *
             */
            $file = $this->testFile;
        } else {
            /*
             * A feltott fajlal dolgozunk
            $file=$file->getLinkTarget(); //nem mukodik splfileinfo elszall file olvasasi hibaval
            $file = $request->file('priceListFile');
             */
            $file = $_FILES['priceListFile']['tmp_name'];
        }

        return $file;
    }

    private function getRowCollection(): Collection
    {
        return (new FastExcel)->sheet(1)->withoutHeaders()->import(
            $this->getSourceFile()
        );
    }

    private function importPriceListCheck(Request $request)
    {
        app('debugbar')->disable();
        $collection = $this->getRowCollection();

        // $startDate=$collection[0][1];
        // $supplierName=$collection[1][1];
        $supplierId = $request->input('supplier');
        $availableDate = $request->input('availableDate');
        if (! $return = $this->service->importPriceListCheck($supplierId, $collection->slice($this->dataStartLine)->toArray())) {
            // if(!$return=$this->service->importPriceListCheck(99999,[])){
            $return = $this->service->getError();

            return \response()->json([
                'success' => false,
                // 'file'=>$file->getLinkTarget(),
                // 'item'=>$collection[0],
                'error' => $return,
            ], 500);
        }

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

    private function notificationNewPriceList($priceListId)
    {
        // debugbar($priceListId);
        $repository = new \App\Repositories\PriceListRepository;
        $repository->setRelation('attachment');
        $priceList = $repository->getQueryWithRelations()->find($priceListId);
        /*
         * árlistábol kell a suppplier ID
         * supplierbol kellenek a csatolt egységek
         */
        $supplier = Supplier::with('profitCenter')->find($priceList->supplier_id);
        $destEmail = $supplier->profitCenter->pluck('email', 'name')->filter(function ($value) {
            return ! is_null($value);
        });
        if ($destEmail->isEmpty()) {
            return;
        }

        $emailData['priceList']['note'] = $priceList->note;
        $emailData['priceList']['filename'] = $priceList->attachment->filename;
        $emailData['priceList']['fileName'] = $priceList->attachment->original_filename;
        $emailData['priceList']['url'] = $priceList->attachment->PublicUrl;
        // $MailData['HTML']=view('email.priceListChangeNotify')->with($emailData)->render();
        $destEmail->each(function ($emailAddress) use ($emailData) {
            \Mail::send('email.priceListChangeNotify', $emailData, function ($m) use ($emailAddress) {
                $m->subject('Árlista változás ');
                if (env('APP_STAGE') == 'PROD') {
                    $m->to($emailAddress);
                } else {
                    if (env('APP_STAGE') == 'TEST') {
                        $m->to('beszerzes@delirest.hu');
                    }
                    if (env('APP_STAGE') == 'DEV') {
                        $m->to('city@e98.hu');
                    }
                }
                if (env('MAIL_TO_ORDER_ADDRESS') != 'city@e98.hu') {
                    $m->bcc('city@e98.hu');
                }

            });

        });

        return 'Notified Ok:'.$priceListId;
    }

    private function importPriceList(Request $request): JsonResponse
    {
        $importStartLine = $this->dataStartLine;
        $importLength = 9999;
        // $importStartLine = rand(100,400);
        // $importLength=20;
        $collection = $this->getRowCollection();

        /*$startDate = $collection[0][1];
        $supplierName = $collection[1][1];
        */
        $supplierId = $request->input('supplier');
        $availableDate = $request->input('availableDate');

        $otherField = [];
        $otherField['note'] = $request->input('note');
        $res = $this->service->importPriceList($supplierId, $availableDate, $collection->slice($importStartLine, $importLength)->toArray(), $otherField);
        $success = false;
        if ($res) {
            if ($res['importSuccess'] == true) {
                $success = true;
                $attachmentFile = new Attachment;
                $attachmentFile->addStreamedFile(file_get_contents($this->getSourceFile()), $this->getSourceFileName());
                // fajl csatolasa
                $attachmentFile->attachable()->associate(PriceList::find($res['id']));
                $attachmentFile->save();

                /*
                 * Álista értesítő profitcenter számára
                 * http://pm.e98.hu/agiles/117-9/current?issue=EV3-69
                 *
                 */
                $res['NotifyRes'] = $this->notificationNewPriceList($res['id']);
            }
        }

        return \response()->json([
            'success' => $success,
            'error' => $this->service->getError(),
            'res' => $res,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): Response|JsonResponse
    {
        if ($request->input('finalization') == '1') {
            return $this->importPriceList($request);
        } else {
            return $this->importPriceListCheck($request);
        }

    }

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

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(int $SupplierId): Response|JsonResponse
    {
        return response()->noContent();
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, int $SupplierId): Response|JsonResponse
    {
        return response()->noContent();
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $Id): Response|JsonResponse
    {

        $repository = new \App\Repositories\PriceListRepository;
        if ($repository->delete($Id)) {
            $ret = ['success' => true];
        } else {
            $ret = ['success' => false];
        }

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

    public function getDataTableContent(): JsonResponse
    {

        $repository = new \App\Repositories\PriceListRepository;
        $ret = ['data' => []];
        $items = $repository->getQueryWithRelations()->get()->toArray();
        foreach ($items as $item) {
            if (! isset($item['supplier']['name'])) {

            } else {
                $data['id'] = $item['id'];
                $data['supplierName'] = $item['supplier']['name'];
                $data['available'] = formatterDate($item['available']);
                $data['created_at'] = formatterDateTime($item['created_at']);
                $data['note'] = $item['note'];
                $ret['data'][] = $data;
            }
        }

        return \response()->json($ret);
        var_dump($ret);
        dd($ret);
        dd($repository->all()->toArray());

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

    }
}
