<?php

namespace App\Classes\Modules\Segments\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Segments\Services\FetchesConstant;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Http\Resources\ConstantResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Carbon\CarbonPeriod;

class FetchBasePriceLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Retrieved Base Price',
            'message' => 'You have successfully retrieved the Base Price'
        ];
    }


    /** @var FetchesConstant */
    private $fetchesConstant;

    /**
     * FetchConstantLogic constructor.
     * @param FetchesConstant $fetchesConstant
     */
    public function __construct(FetchesConstant $fetchesConstant)
    {
        $this->fetchesConstant = $fetchesConstant;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function logic(Request $request) : JsonResponse
    {

        $constant = $this->fetchesConstant->execute(['segment_id' => $request->route('id'), 'reference' => SegmentConstants::BASE_PRICE]);

        $constantObject = (array) $constant->value;

        if ($request->input('dateFrom') !== null && $request->input('dateTo') !== null) {

            $period = CarbonPeriod::create($request->input('dateFrom'), $request->input('dateTo'));

            $returnObject = [];

            foreach ($period as $date) {
                array_key_exists($date->format('Y-m-d'), $constantObject) === true ? $returnObject[$date->format('Y-m-d')] = $constantObject[$date->format('Y-m-d')] : '';
            }

            $constant->value = json_encode($returnObject);

        }

        return $this->resourceResponse(new ConstantResource($constant));
    }

}