<?php

namespace App\Classes\Modules\PackingLists\ControllersLogic\Containers;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\Containers\FetchesContainer;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Http\Resources\ContainerResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AssignPackingListContainerLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Assign Packing List Container',
            'message' => 'You have successfully assign Packing List to Container'
        ];
    }

    /** @var FetchesContainer */
        private $fetchesContainer;

    /** @var FetchesPackingList */
        private $fetchesPackingList;

    /**
     * DeleteContainerControllersLogic constructor.
     * @param FetchesContainer $fetchesContainer
     * @param FetchesPackingList $fetchesPackingList
     */
    public function __construct(FetchesContainer $fetchesContainer, FetchesPackingList $fetchesPackingList)
    {
        $this->fetchesContainer = $fetchesContainer;
        $this->fetchesPackingList = $fetchesPackingList;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        try {
            $container = $this->fetchesContainer->execute(['id' => $request->route('id')]);
            $packing_list = $request->input('packing_list_id');

            foreach ($packing_list as $key => $row) {
                $packing_list_item = $this->fetchesPackingList->execute(['id' => $row]);
                $container->packingLists()->attach($packing_list_item);
            }

            return $this->resourceResponse(new ContainerResource($container));

        } catch (\Exception $exception){
            throw new ErrorException($exception->getMessage(), $exception->getCode());
        }

    }

}
