<?php

namespace App\Services;

use App\Models\Resource;
use Illuminate\Support\Carbon;
use App\Builders\ChartDrillBuilder;

class ChartDetailsService
{
    public function prepareDetails(Resource $chart)
    {
        $dateRange     = $chart->getResourceConfiguration('date_range');
        $timeScale     = $chart->getResourceConfiguration('date_time_scale');
        $xAxis         = $chart->data["x_axis"];
        $drillBuilder  = new ChartDrillBuilder($chart);
        $preparedXAxis = [];

        if (empty($dateRange) || empty($timeScale)) {
            return;
        }

        if (strtolower($timeScale) == "quarters") {

            foreach ($xAxis as $value) {
                $dateValue       = Carbon::parse($value)->addMonths(2)->lastOfMonth()->toDateString();
                $preparedXAxis[] = "{$value} to {$dateValue}";
            }

            $chart->data = ["x_axis" => $preparedXAxis, "y_axis" => $chart->data["y_axis"]];
            // dd($chart->data);

        }

        if (strtolower($timeScale) == "weeks") {

            foreach ($xAxis as $value) {
                $value = Carbon::parse($value);

                $dateValue = $drillBuilder->populateOptions()->handleWeeks($value);

                $preparedXAxis[] = "{$dateValue[0]} to {$dateValue[1]}";
            }

            $chart->data = ["x_axis" => $preparedXAxis, "y_axis" => $chart->data["y_axis"]];

        }

    }

}
