<?php

namespace App\Http\Controllers\api\v1;

use App\Http\Controllers\Controller;
use App\Models\OrderArchive;
use Carbon\Carbon;
use Flugg\Responder\Http\MakesResponses;
use Flugg\Responder\Responder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class OrderController extends Controller
{
    use MakesResponses;

    public function convertItemCollectionToHooreycaAPIItems($ItemCollection)
    {
        unset($ItemCollection->order_archive_id);
        $ItemCollection->HooreycaVolumen = null;
        $ItemCollection->HooreycaUnitPrice = null;

        if ($ItemCollection->HooreycaMultiplier !== null) {
            $ItemCollection->HooreycaVolumen = $ItemCollection->quantity * $ItemCollection->HooreycaMultiplier;
            $ItemCollection->HooreycaUnitPrice = ($ItemCollection->quantity * $ItemCollection->price) / $ItemCollection->HooreycaVolumen;
        }

        /*        if(!in_array($ItemCollection->id,[91045,91046,91047,91042,91043,91044])){
                    var_dump($ItemCollection->id);
                    var_dump(($ItemCollection->quantity*$ItemCollection->price)/($ItemCollection->quantity*$ItemCollection->HooreycaMultiplier));
                    die('hello');
                }*/
        // $ItemCollection->HooreycaSumPrice=($ItemCollection->quantity*$ItemCollection->HooreycaMultiplier);
        // 'HooreycaSumPrice'=>

        return $ItemCollection;

        /*
            Rendelő felületről adatok biztosítása
            -	Cikk kódja
            -	Mennyiségi egység (árlista L oszlop)
            -	Mértékegység (árlista H oszlop)
            -	Kiszerelés (árlista F oszlop)
            -	Súly/Űrtartalom (árlista G oszlop)
            -	Egységszorzó (árlista K oszlop)
            -	Rendelt mennyiség
            -	Megrendelt cikk nettó értéke
         */
        return $ItemCollection->map(function ($item) {
            return [
                'id' => $item->id,
                'hooreycaId' => $item->hooreycaId, // -	Cikk kódja
                'HooreycaUnit' => $item->HooreycaUnit,
                'HooreycaMultiplier' => $item->HooreycaMultiplier,
                'productName' => $item->name.'aaaaaaaaaaaa',
                'hooreycaId' => $item->hooreycaId,
                'productUnit' => $item->productUnit,
                'sellerUnit' => $item->sellerUnit,
                'unitMultiplier' => $item->unitMultiplier, // -	Egységszorzó (árlista K oszlop)
                'amountUnit' => $item->amountUnit,
                'quantity' => $item->quantity, // -	Rendelt mennyiség
                'price' => $item->price, // -	Megrendelt cikk nettó értéke
                'HooreycaVolumen' => $item->quantity * $item->HooreycaMultiplier,
                'HooreycaSumPrice' => ($item->quantity * $item->price) / ($item->quantity * $item->HooreycaMultiplier),

            ];
        });
    }

    public function convertOrderToHooreycaAPI($order, $key)
    {
        /*
            Rendelő felületről adatok biztosítása
            -	szállító kódja supplier.hooreycaId
            -	Szállítási dátum deliveryDate
            -	Üzlet kódja profit_center.hooreycaId
         */
        $order->APICallBackId = (string) \Str::orderedUuid();
        $order->save();
        $order->supplierHooreycaId = $order->supplier->hooreycaId;
        $order->supplierName = $order->supplier->name;
        $order->profitCenterHooreycaId = $order->profitCenter->hooreycaId;
        $order->profitCenterName = $order->profitCenter->name;
        $order->items = $order->itemsAPISpecial->transform([$this, 'convertItemCollectionToHooreycaAPIItems']);
        unset($order->supplier,$order->profitCenter,$order->itemsAPISpecial);

        return $order;
    }

    /**
     Display a listing of the unprocessed orders.

        @group Order management
        @authenticated
        @urlParam page int required The page number. Example: 4
        @responseField status integer request HTTP status
        @responseField status integer request HTTP status
        @responseField success boolean process successes
        @responseField apiVersion integer current API version
        @responseField processedTime DateTime process Timestamp
        @responseField data object collection of Orders.
        @responseField data.APICallBackId string Neet to set order update status in setProcessed interface.
        @responseFile  200 scenario="Has unprocessed orders" example/APIUnProcessingResponse.json
        @responseFile  401 scenario="Request unauthenticated" example/APIUnauthenticated.json
     */
    public function unProcessed(Request $request, Responder $responder)
    {
        Log::channel('api')->info('API request', ['requestData' => var_export($request->server(), true)]);
        $updateDate = Carbon::now();
        $OrderCollection = OrderArchive::with(['supplier' => function ($query) {
            $query->select('id', 'name', 'hooreycaId');
        }, 'profitCenter' => function ($query) {
            $query->select('id', 'name', 'hooreycaId');
        }, 'itemsAPISpecial' => function ($query) {
            // $query->select('id','order_archive_id');
            $query->select(
                'order_archive_id',
                'id',
                'hooreycaId', // -	Cikk kódja
                'name',
                'hooreycaId',
                'HooreycaUnit',
                'HooreycaMultiplier',
                'productUnit',
                'sellerUnit',
                'unitMultiplier', // -	Egységszorzó (árlista K oszlop)
                'amountUnit',
                'quantity', // -	Rendelt mennyiség
                'price'
            );
        },

        ])->select(
            'id',
            'supplier_id',
            'profit_center_id',
            'humanId',
            'deliveryDate',
            'confirmed', )
        // ->whereNulll('APIConfirmed')
            ->whereNotNull('confirmed')
            ->whereNull('APIConfirmed')
            ->orderBy('id', 'desc')->paginate(3);

        $ret[] = get_debug_type($OrderCollection);

        $OrderCollection->transform([$this, 'convertOrderToHooreycaAPI']);

        $updateId = $OrderCollection->pluck('id');
        $header = parseAPIVersionFromNamespace(__NAMESPACE__);
        $header['processedTime'] = $updateDate->format('Y.m.d. H:i:s.u');
        $response = responder()->success($OrderCollection)->respond(null, $header);

        $ret = [];
        $ret[] = $OrderCollection->pluck('id');
        $ret[] = OrderArchive::whereIn('id', $OrderCollection->pluck('id'));

        OrderArchive::whereIn('id', $updateId)->update(['APILastGetting' => $updateDate]);
        $ret[] = OrderArchive::whereIn('id', $updateId)->update(['APILastGetting' => $updateDate]);

        Log::channel('api')->info('Update APILastGetting ', ['Id' => $updateId->toArray(), 'Date' => $updateDate]);

        $ret[] = $response->getContent();
        $ret[] = var_export($request->server(), true);
        Log::channel('api')->info('API response', ['responseBody' => json_decode($response->getContent(), JSON_PRETTY_PRINT)]);

        return $response;
        /*erorr teszthez DB error
         * return responder()->success(OrderArchive::with('items')->orderBy('kod','desc')->paginate(2))->respond();
         */
    }

    /*
     *  @bodyParam [] Example:["987f3001-6364-4d7c-8b0c-daf29dbd38ec","987ee197-5293-48de-a488-3c9a05229bb6"]
    localhost key  2|hqN0ifD9OP0vIAQZRPubcZ7x5W8qw49XKeFk9WJs
    d2d key "1|tCtfKT9hAjGt213iuluWiHEvlyAK2KqtZmblQx8Y"
    {"APICallBackId":["987f3001-6364-4d7c-8b0c-daf29dbd38ec","987f3001-6364-4d7c-8b0c-daf29dbd38eX"]}
     */
    /**
    Set processed orders.

    @group Order management
    @authenticated

    @bodyParam APICallBackId string[] required List of APICallBackId need to set. Example: 987f3001-6364-4d7c-8b0c-daf29dbd38ec


    @responseField status integer request HTTP status
    @responseField status integer request HTTP status
    @responseField success boolean process successes
    @responseField apiVersion integer current API version
    @responseField processedTime DateTime process Timestamp
    @responseField data object collection of updated Order status.
    @responseField data.APICallBackId string Order update status ("updated" is ok).
    @responseFile  200 scenario="Has unprocessed orders" example/APISetProcessingResponse.json
    @responseFile  500 scenario="Request invalid Request Body data" example/APISetProcessingResponseErrorInvalidData.json
    @responseFile  401 scenario="Request unauthenticated" example/APIUnauthenticated.json
     */
    public function setProcessed(Request $request)
    {
        $updateDate = Carbon::now();
        $successData = [];
        $header = parseAPIVersionFromNamespace(__NAMESPACE__);
        $header['processedTime'] = $updateDate->format('Y.m.d. H:i:s.u');

        Log::channel('api')->info('API request', ['requestData' => var_export($request->server(), true)]);
        Log::channel('api')->info('API request', ['requestData' => var_export($request->getContent(), true)]);
        $orderUUIds = json_decode($request->getContent());
        // var_export($orderUUIds);
        // if(!property_exists($orderUUIds,'APICallBackId') || !is_array($orderUUIds->APICallBackId)){
        if (! property_exists($orderUUIds, 'APICallBackId')) {
            return responder()->error('invalid data', $request->getContent())->respond(null, $header);
        }
        // var_export(property_exists($orderUUIds,'APICallBackId'));
        // die();
        // return responder()->error('invalid data',gettype($orderUUIds));
        // $orderUUIds=json_decode($request->getContent());
        Log::channel('api')->info(var_export($orderUUIds, true));
        foreach ($orderUUIds->APICallBackId as $APICallBackId) {
            if (is_array($APICallBackId)) {
                return responder()->error('invalid data'.__LINE__, $request->getContent())->respond(null, $header);
            }
            if ($Order = OrderArchive::where('APICallBackId', $APICallBackId)->whereNull('APIConfirmed')->first()) {
                $Order->APIConfirmed = $updateDate;
                $Order->save();
                $successData[$APICallBackId] = 'updated';
            } else {
                $successData[$APICallBackId] = 'invalid Id';
            }
        }
        $response = responder()->success($successData)->respond(null, $header);
        Log::channel('api')->info('API response', ['responseBody' => json_decode($response->getContent(), JSON_PRETTY_PRINT)]);

        return $response;
    }

    /**
    Display a server Status.

    @group General Interfaces
    @unauthenticated
    @responseField status integer request HTTP status
    @responseField success boolean process successes
    @responseField apiVersion integer current API version
    @responseField processedTime DateTime process Timestamp
     *
    @responseField data.APIStatus string API status state (up and down).
    @responseFile  200 scenario="Server status" example/APIServerStatusResponse.json
     */
    public function status()
    {
        $header = parseAPIVersionFromNamespace(__NAMESPACE__);
        $header['processedTime'] = Carbon::now()->format('Y.m.d. H:i:s.u');

        return responder()->success(['APIStatus' => 'up'])->respond(null, $header);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return 'hello';
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function show(int $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, int $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(int $id)
    {
        //
    }
}
