<?php

namespace App\Http\Resources\ResidentialComplex;

use App\CourseOfConstruction;
use App\ResidentialComplex;
use Illuminate\Http\Resources\Json\JsonResource;

class ResidentialComplexCourseOfConstruction extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $result = [];
        /** @var ResidentialComplex $residentialComplex */
        $residentialComplex = $this;

        $courseOfConstructions = $residentialComplex->courseOfConstruction()->orderBy('report_date')->get();

        /** @var CourseOfConstruction $construction */
        foreach ($courseOfConstructions as $construction) {
            $year = $construction->getReportYearAttribute($construction->report_date, ['year' => true]);
            $month = $construction
                ->getReportYearAttribute($construction->report_date, ['month' => true]);

            $result[$year]['year'] = $year;
            if (isset($result[$year]['month'])) {
                if (!in_array($month, $result[$year]['month'])) {
                    $result[$year]['month'][] = $month;
                }
            } else {
                $result[$year]['month'][] = $month;
            }
        }

        return $result;
    }
}
