<?php

namespace App\Http\Controllers;

use App\Enums\DbStatusFieldEnum;
use App\Enums\OrderFlag;
use App\Enums\OrderStatusEnum;
use App\Enums\OrderType;
use App\Models\Order;
use App\Models\OrderArchive;
use App\Models\ProfitCenter;
use App\Models\Supplier;
use App\Services\OrderService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class OrderArchiveController extends Controller
{
    protected OrderService $service;

    protected bool $testMode = false;

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

    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        // test mode
        if (\request()->input('t') == 1) {
            dd(auth()->user()->roles->toArray(), auth()->user()->allPermissions(), auth()->user()->whereDoesntHaveRole()->get()
            );
            dd(auth()->user()->roles->toArray());
            dd(auth()->user()->allPermissions());
            dd(auth()->user()->whereDoesntHaveRole()->get());
        }

        $dataView = ['testMode' => $this->testMode];
        if (auth()->user()->hasRole(['root', 'admin', 'developer'])) {
            $dataView['profitCenters'] = ProfitCenter::whereIn('status', [DbStatusFieldEnum::active, DbStatusFieldEnum::archive])->select('name', 'id')->orderBy('name')->get()->toArray();
            $dataView['suppliers'] = Supplier::whereIn('status', [DbStatusFieldEnum::active, DbStatusFieldEnum::archive])->select('name', 'id')->orderBy('name')->get()->toArray();
        }

        return view('modules.orderArchive.index')->with($dataView);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(Request $request): Response|JsonResponse
    {
        return \response()->json([], 400);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): Response|JsonResponse
    {
        return \response()->json([], 400);
    }

    /**
     * Display the specified resource.
     */
    public function show(int $id): View|Response|JsonResponse
    {
        $showData = [];
        $showData = OrderArchive::with('items', 'supplier', 'profitCenter')->find($id)->toArray();

        debug($showData);

        return view('modules.orderArchive.show')->with($showData);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(int $OrderId): Response|JsonResponse|RedirectResponse
    {

        // letre kell hozni egy újat ordert
        $OrderArchive = OrderArchive::find($OrderId);

        $Order = new Order;
        $Order->orderStatus = OrderStatusEnum::productSelect;

        $copyFieldPointer = [
            'profit_center_id',
            'supplier_id',
            'contactName',
            'note',
            'orderType',
            'parent_id',
            'deliveryDate',
            'deliveryAddressId',
            'deliveryAddressName',
            'deliveryAddress',
            'customNotificationEmail',
            'productSelected',
            'productComment',
            'sumPrice',
        ];
        foreach ($copyFieldPointer as $pointer) {
            $Order->$pointer = $OrderArchive->$pointer;
        }
        $Order->orderFlag = OrderFlag::modifier;
        $Order->rel_id = $OrderArchive->id;
        $OrderOriginal = Order::where('humanId', $OrderArchive->humanId)->first();
        if ($OrderOriginal) {
            $Order->parent_id = $OrderOriginal->parent_id;
            $Order->note = $OrderOriginal->note.' '.$OrderOriginal->humanId.' számú megrendelés módosítása.';
        }
        $Order->save();

        return \response()->redirectTo(route('order.edit', $Order->id));

        dd($Order->toArray(), $OrderArchive->toArray(), $OrderOriginal->toArray());
    }

    public function update(Request $request, int $orderId): JsonResponse
    {
        return \response()->json([], 400);
    }

    public function destroy(int $OrderId): Response|JsonResponse
    {
        return response()->noContent();
    }

    private function orderCanEditable($orderData)
    {
        if (! auth()->user()->hasRole('profit-center')) {
            return false;
        }
        $profitCenterId = auth()->user()->profitCenters->first()->id;
        if ($orderData['profit_center_id'] !== $profitCenterId) {
            return false;
        }
        if ($orderData['orderType'] !== OrderType::daily) {
            return false;
        }
        //        print"<pre>";
        // var_dump($orderData);
        if (in_array($orderData['orderFlag'], [OrderFlag::storno, OrderFlag::modified])) {
            return false;
        }

        if ($orderData['deliveryDate'] <= Carbon::tomorrow()->format('Y-m-d')) {
            return false;
        }

        return true;
    }

    public function getDataTableContent(): JsonResponse
    {
        $groupId = null;
        $searchStr = null;
        $OrderArchive = OrderArchive::with('attachment')->select('id', 'profit_center_id', 'supplier_name', 'deliveryAddressName', 'deliveryAddress', 'deliveryDate', 'humanId', 'confirmed', 'contactName', 'sentTime', 'orderType', 'parent_id', 'orderFlag', 'rel_id');
        if (auth()->user()->hasRole('profit-center')) {
            $profitCenterId = auth()->user()->profitCenters->first()->id;
            $OrderArchive = $OrderArchive->where('profit_center_id', $profitCenterId);
        } elseif (auth()->user()->hasRole(['root', 'admin', 'developer'])) {
            debug('high permission');
            $OrderArchive->with('profitCenter');
            if (\request()->get('advanceSearchParameter')) {
                $advanceSearchParameter = \request()->get('advanceSearchParameter');
                if (isset($advanceSearchParameter['profitCenterId']) && is_int($advanceSearchParameter['profitCenterId'] * 1)) {
                    $OrderArchive->where('profit_center_id', $advanceSearchParameter['profitCenterId']);
                }
                if (isset($advanceSearchParameter['supplierId']) && is_int($advanceSearchParameter['supplierId'] * 1)) {
                    $OrderArchive->where('supplier_id', $advanceSearchParameter['supplierId']);
                }
            }
        } else {
            return \response()->json(['data' => []]);
        }

        if (\request()->get('advanceSearchParameter')) {
            debug(\request()->get('advanceSearchParameter'));
            $advanceSearchParameter = \request()->get('advanceSearchParameter');
            if (isset($advanceSearchParameter['deliveryDateFrom']) && strlen($advanceSearchParameter['deliveryDateFrom']) == 10) {
                $OrderArchive->where('deliveryDate', '>=', $advanceSearchParameter['deliveryDateFrom']);
            }
            if (isset($advanceSearchParameter['deliveryDateTo']) && strlen($advanceSearchParameter['deliveryDateTo']) == 10) {
                $OrderArchive->where('deliveryDate', '<=', $advanceSearchParameter['deliveryDateTo']);
            }
        }
        $OrderArchive->orderBy('sentTime', 'desc');
        $OrderArchive->limit(3000);
        //        $OrderArchive->limit(100);
        $OrderArchive->where('orderType', '!=', 'weekly');

        $retData = $OrderArchive->get()->toArray();
        // $retData=$OrderArchive->limit(10)->get()->toArray();
        $retData = array_map(function ($item) {
            $item['fileUrl'] = false;
            $item['fileName'] = false;
            if ($item['attachment']) {
                $item['fileUrl'] = $item['attachment']['PublicUrl'].$item['attachment']['filename'];
                $item['fileName'] = $item['attachment']['original_filename'];
            }
            if (! $item['deliveryAddressName'] || strlen($item['deliveryAddressName']) < 2) {
                $item['deliveryAddressName'] = $item['deliveryAddress'];
            }
            $item['canEditable'] = $this->orderCanEditable($item);

            //            dd($item);
            return $item;
        }, $retData);

        debug(count($retData));
        debug($retData);

        return \response()->json(['data' => $retData]);
        /**clean up code*/
    }
}
