<?php

namespace App\Http\Controllers\Admin;

use App\Enums\DbStatusFieldEnum;
use App\Http\Controllers\Controller;
use App\Models\Supplier;
use App\Repositories\ProfitCenterRepository;
use App\Services\ProfitCenterService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class ProfitCenterController extends Controller
{
    protected ProfitCenterService $service;

    private bool $testMode = false;

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

    /**
     * Display a listing of the resource.
     */
    public function index(): View|JsonResponse
    {
        if (\request()->input('t') == 1) {
            $options = [
                'validate_all' => true,
                'return_type' => 'both',
            ];
            [$validate, $allValidations] = auth()->user()->ability(
                ['root', 'owner'],
                ['create-post', 'edit-user'],
                $options
            );
            dd($allValidations);
            dd(auth()->user()->hasRole('admin'));

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

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

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

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        $retData = [];
        $retData['testMode'] = ($this->testMode) ? 'true' : 'false';
        $retData['supplier'] = Supplier::orderBy('name', 'asc')->get()->toArray();

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

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

        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): Response|JsonResponse
    {
        $data = $this->getSupplierDataFromRequest($request);
        $id = $this->service->add($data);

        $ret['success'] = true;
        $ret['data'] = $data;
        $ret['id'] = $id;
        if ($this->service->hasError()) {
            $ret['success'] = false;
            $ret['error'] = $this->service->getError();
        }

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

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

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(int $ProfitCenterId): View|JsonResponse|bool
    {
        $this->service->setRelation('address', 'contact', 'users', 'supplier');
        // if(!$itemData=$this->service->getWithRelations($ProfitCenterId)){
        if (! $itemData = $this->service->getWithAllRelations($ProfitCenterId)) {
            return false;
        }

        $retData = [];
        $retData['itemData'] = $itemData;
        if (isset($retData['itemData']['users'][0])) {
            $profitCenterUserData = $retData['itemData']['users'][0];
            $retData['itemData']['userId'] = $profitCenterUserData['id'];
            $retData['itemData']['userName'] = $profitCenterUserData['name'];
        } else {
            $profitCenterUserData = ['id' => '', 'name' => ''];
        }
        unset($retData['itemData']['users']);

        $retData['testMode'] = ($this->testMode) ? 'true' : 'false';
        $retData['init'] = false;
        $retData['supplier'] = Supplier::orderBy('name', 'asc')->get()->toArray();
        debug($retData);
        if (\request()->input('t') == 1) {
            echo '<pre>';
            var_dump($itemData);

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

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, int $ProfitCenterId): Response|JsonResponse
    {
        $data = $this->getSupplierDataFromRequest($request);

        debug($data);
        $this->service->update($ProfitCenterId, $data);

        $ret['success'] = true;
        $ret['data'] = $data;
        $ret['id'] = $ProfitCenterId;
        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 $id): Response|JsonResponse
    {
        $repository = new ProfitCenterService(new ProfitCenterRepository);
        if ($repository->delete($id)) {
            $ret = ['success' => true];
        } else {
            $ret = ['success' => false];
        }

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

    public function getDataTableContent(): JsonResponse
    {

        $repository = new ProfitCenterRepository;
        $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);
    }

    private function getSupplierDataFromRequest(Request $request)
    {

        // dd($request->route('supplier'));
        /** @var array $data */
        $data = [];
        $acceptedData = [
            'name',
            'hooreycaId',
            'nameId',
            'email',
            'postCode',
            'city',
            'street',
            'phone',
            'mobil',
            'userName',
            'userPassword',
            'userRePassword',
            'note',
            'canSee',
            'addressEqual',
            'multiAddress',
            'user',
        ];

        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'] = [];
        }

        if ($addressId = $request->get('addressId')) {
            $data['addressId'] = $addressId;
        } else {
            $data['addressId'] = [];
        }

        $hasDefaultValueNotNull = [
            'addressEqual',
            'multiAddress',
            'canSee',
        ];
        foreach ($hasDefaultValueNotNull as $key) {
            if (array_key_exists($key, $data) && is_null($data[$key])) {
                unset($data[$key]);
            }
        }
        $data['supplierId'] = [];
        if ($supplierNames = $request->get('supplier')) {
            $data['supplierId'] = \App\Models\Supplier::whereIn('name', (array) $supplierNames)->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('profitCenter')) {
                $profitCenter = \App\Models\ProfitCenter::with('attachment')->find($request->route('profitcenter'));
                if ($profitCenter->logoFile) {
                    $file = 'images/supplierLogo/B9f65IlF62fEoNfLPmSFen8D8A2E0HUCHJcqHYDw.jpg';
                    // var_dump(str_replace($pathPrefix,'',$file));
                    \Storage::disk($disk)->delete(str_replace($pathPrefix, '', $profitCenter->logoFile));
                }
            }
            $path = $request->file('logoFile')->store('/profitCenter', $disk);
            $data['logoFile'] = $pathPrefix.$path;
        }

        return $data;
    }
}
