<?php

namespace App\Http\Controllers\Admin;

use App\Enums\DbStatusFieldEnum;
use App\Http\Controllers\Controller;
use App\Models\ProfitCenter;
use App\Models\Service;
use App\Models\Supplier;
use App\Services\SupplierService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class SupplierController extends Controller
{
    protected SupplierService $service;

    private bool $testMode = false;

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

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

        // test
        if (\request()->input('t') == 1) {

            return response()->json(['debug' => 'test']);
        }

        $retData = [];
        $retData['testMode'] = ($this->testMode) ? 'true' : 'false';
        $retData['init'] = (bool) \request()->get('init', true);

        return view('admin.supplier.index')->with($retData);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        $ProductGroup = new \App\Models\ProductGroup;
        $productGroupArray = $ProductGroup->allWithParents(2);
        $retData = [];
        $retData['testMode'] = ($this->testMode) ? 'true' : 'false';
        $retData['productGroup'] = $ProductGroup->allWithParents(2);
        $retData['profitCenter'] = ProfitCenter::orderBy('name', 'asc')->get()->toArray();
        $retData['service'] = Service::select('name')->orderBy('name')->get()->toArray();

        return view('admin.supplier.create')->with($retData);

        return view('admin.supplier.create')->with([
            'productGroup' => $productGroupArray,
            'testMode' => ($this->testMode) ? 'true' : 'false',

        ]);

    }

    private function getSupplierDataFromRequest(Request $request)
    {

        // dd($request->route('supplier'));
        /** @var array $data */
        $data = [];
        $acceptedData = [
            1 => 'name',
            2 => 'hooreycaId',
            3 => 'nameId',
            4 => 'orderEmail',
            5 => 'orderEmail2',
            6 => 'address',
            7 => 'mailingAddress',
            8 => 'phone',
            9 => 'fax',
            10 => 'customerServicePhone',
            11 => 'note',
            12 => 'emailAttachmentType',
            13 => 'canSee',
            14 => 'canSeeInOrder',
            //            15 => 'hooreycaDataActive',
            15 => 'openHours',
            16 => 'ordersDeadline',
            17 => 'minOrderValue',
        ];

        foreach ($acceptedData as $num => $key) {
            $data[$key] = $request->get($key);
        }
        $data['status'] = DbStatusFieldEnum::active;
        if ($contactId = $request->get('contactId')) {
            $data['contactId'] = $contactId;
        } else {
            $data['contactId'] = [];
        }

        $data['productGroupId'] = [];
        if ($productGroupNames = $request->get('productGroup')) {
            // @todo: atszervezni a servicebe, vagy a repositoryba
            // dd($productGroupNames);
            $data['productGroupId'] = \App\Models\ProductGroup::whereIn('name', (array) $productGroupNames)->get()->pluck('id')->toArray();
        }

        $data['serviceId'] = [];
        if ($ServiceNames = $request->get('supplierService')) {
            // @todo: atszervezni a servicebe, vagy a repositoryba
            $Services = \App\Models\Service::select(['name', 'id'])->whereIn('name', (array) $ServiceNames)->get()->keyBy('name')->toArray();
            foreach ($ServiceNames as $serviceName) {
                if (! isset($Services[$serviceName])) {
                    $newService = \App\Models\Service::create(['name' => $serviceName]);
                    $data['serviceId'][] = $newService->id;

                } else {
                    $data['serviceId'][] = $Services[$serviceName]['id'];
                }
            }
        }

        $data['profitCenterId'] = [];
        if ($profitCenterNames = $request->get('profitCenter')) {
            $data['profitCenterId'] = \App\Models\ProfitCenter::whereIn('name', (array) $profitCenterNames)->get()->pluck('id')->toArray();
        }

        if ($request->file('logoFile')) {
            $disk = 'image';
            $diskPath = \Storage::disk($disk)->getAdapter()->getPathPrefix();
            $pathPrefix = str_replace(public_path(), '', $diskPath);
            $pathPrefix = ltrim($pathPrefix, DIRECTORY_SEPARATOR);
            $pathPrefix = str_replace('\\', '/', $pathPrefix);
            // ha van mar akkor torolni kell!!!
            if ($request->route('supplier')) {
                $supplier = Supplier::with('attachment')->find($request->route('supplier'));
                if ($supplier->logoFile) {
                    $file = 'images/supplierLogo/B9f65IlF62fEoNfLPmSFen8D8A2E0HUCHJcqHYDw.jpg';
                    // var_dump(str_replace($pathPrefix,'',$file));
                    \Storage::disk($disk)->delete(str_replace($pathPrefix, '', $supplier->logoFile));
                }
            }
            $path = $request->file('logoFile')->store('/supplierLogo', $disk);
            $data['logoFile'] = $pathPrefix.$path;
        }

        return $data;
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): Response|JsonResponse
    {
        $data = $this->getSupplierDataFromRequest($request);
        // $data['canSeeInOrder']=1;
        $id = $this->service->add($data);
        $ret = [];
        $ret['success'] = true;
        $ret['id'] = $id;
        $ret['data'] = $data;
        if ($this->service->hasError()) {
            $ret['success'] = false;
            $ret['error'] = $this->service->getError();
        }

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

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

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(int $SupplierId): View|JsonResponse|bool
    {

        if (! $supplierData = $this->service->getWithAllRelations($SupplierId)) {
            return false;
        }
        $retData = [];
        $retData['supplierData'] = $supplierData;
        $retData['testMode'] = ($this->testMode) ? 'true' : 'false';
        $retData['init'] = false;
        $ProductGroup = new \App\Models\ProductGroup;
        $productGroupArray = $ProductGroup->allWithParents(2);
        $retData['productGroup'] = $productGroupArray;
        $retData['service'] = Service::select('name')->orderBy('name')->get()->toArray();
        $retData['profitCenter'] = ProfitCenter::orderBy('name', 'asc')->get()->toArray();
        if (\request()->input('t') == 1) {
            echo '<pre>';
            var_dump($supplierData);
            var_dump($retData);

            return response()->json($supplierData);
        }

        return view('admin.supplier.create')->with($retData);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $SupplierId
     */
    public function update(Request $request, int $supplierId): JsonResponse
    {
        /*
                $ret['success']=false;
                return \response()->json($ret);
        */

        //        $this->fileManagement($request,$SupplierId);
        //        debug($request->get('profitCenter'));
        $data = $this->getSupplierDataFromRequest($request);
        $this->service->update($supplierId, $data);
        $ret['success'] = true;
        $ret['data'] = $data;
        $ret['id'] = $supplierId;
        if ($this->service->hasError()) {
            $ret['success'] = false;
            $ret['error'] = $this->service->getError();
        }

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $SupplierId): Response|JsonResponse
    {
        if ($this->service->delete($SupplierId)) {
            $ret = ['success' => true];
        } else {
            $ret = ['success' => false];
        }

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

    }

    public function getDataTableContent(): JsonResponse
    {

        $repository = new \App\Repositories\SupplierRepository;
        $ret = ['data' => []];
        $items = $repository->getQueryWithRelations()->orderBy('name')->get()->toArray();
        foreach ($items as $item) {
            $data['id'] = $item['id'];
            $data['name'] = $item['name'];
            $data['hooreycaId'] = $item['hooreycaId'];
            $data['nameId'] = $item['nameId'];
            $data['created_at'] = formatterDateTime($item['created_at']);
            $ret['data'][] = $data;
        }

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

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

    }

    private function fileManagement($request, $supplierId)
    {
        if ($file = $request->file('logoFile')) {
            // ha van mar akkor torolni kell!!!
            $supplier = Supplier::with('attachment')->find($supplierId);
            if (count($supplier->attachment) > 0) {
                foreach ($supplier->attachment as $attached) {
                    \App\Models\Attachment::find($attached->id)->delete();
                }
            }
            $attachment = new \App\Models\Attachment;
            $attachment->addFile($file);
            $attachment->attachable()->associate($supplier);
            $attachment->save();
        }
    }

    private function getResponseStatusFromData($retData)
    {
        $status = 500;
        if (isset($retData['success']) && $retData['success'] === true) {
            $status = 200;
        }
        if (isset($retData['statusCode']) && is_numeric($retData['statusCode'])) {
            $status = $retData['statusCode'];
        }

        return $status;
    }

    public function attachFile(int $supplierId): JsonResponse
    {
        $file = \request()->file('attacheFile');
        $ret = ['data' => [], 'success' => false];
        if ($file) {
            $ret['data']['file'] = var_export(\request()->file('attacheFile'), true);
            if ($supplier = Supplier::find($supplierId)) {
                $attachment = new \App\Models\Attachment;
                $attachment->addFile($file);
                $attachment->attachable()->associate($supplier);
                $attachment->save();
                $ret['data']['attachment'] = $attachment->toArray();
                $ret['success'] = true;
            }
        }
        if ($ret['success'] === true) {
            $supplierData = $this->service->getWithAllRelations($supplierId);
            $emailData = [
                'supplierName' => $supplierData['name'],
                'documentName' => $file->getClientOriginalName(),
            ];
            if (is_array($supplierData['profit_center'])) {
                $toEmailAddress = [];
                foreach ($supplierData['profit_center'] as $profitCenter) {
                    if ($profitCenter['email'] && $profitCenter['email'] != 'NULL') {
                        $toEmailAddress[] = $profitCenter['email'];
                    }
                }
            }
            Log::info('supplierNewFile prepared'.var_export($toEmailAddress,true));
            Log::info('supplierNewFile prepared'.var_export($emailData,true));
            \Mail::send('email.supplierNewFile', [
                'emailData' => $emailData,
            ], function ($m) use ($toEmailAddress) {

                $subject = 'Értesítés dokumentum változásról';
                $m->subject($subject);

                if (config('app.stage', 'DEV') == 'PROD') {
                    $m->to($toEmailAddress);
                } else {
                    $m->to($toEmailAddress);
                    $m->to(config('mail.MailToOrderAddress'));
                }
                if (config('mail.MailToOrderAddress') != 'city99@e98.hu') {
                    $m->bcc('city99@e98.hu');
                }
            });
        }

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

    public function detachFile(int $supplierId): JsonResponse
    {
        $ret = ['data' => [], 'success' => false];
        if ($supplier = Supplier::with('attachment')->find($supplierId)) {
            if ($attachment = $supplier->attachment->where('id', \request()->get('attachemntId'))->first()) {
                if ($attachment->delete()) {
                    $ret['data']['attachment'] = $attachment->toArray();
                    $ret['success'] = true;
                }
            }
        }

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