<?php

namespace App\Http\Resources\ResidentialComplex;

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

class ResidentialComplexSectionStatistic 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;
        if ($residentialComplex->building_count == 1) {
            $result = [
              'building_count' => 1,
              'building_stage_of_construction' => $residentialComplex->stageOfConstruction()
                  ? $residentialComplex->stageOfConstruction()->first()->name : ""
            ];
        } else {
            $sections = $residentialComplex->sections()->get();
            $RCSectionStatuses = [];
            /** @var Section $section */
            foreach ($sections as $section) {
                $stageOfConstruction = $section->stage_of_construction ?
                    $section->stage_of_construction->first() : null;
                if (!empty($stageOfConstruction)) {
                    if (!isset($RCSectionStatuses[$stageOfConstruction->id])) {
                        $RCSectionStatuses[$stageOfConstruction->id]['count'] = 1;
                        $RCSectionStatuses[$stageOfConstruction->id]['name'] = $stageOfConstruction->name;
                    } else {
                        $RCSectionStatuses[$stageOfConstruction->id]['count'] += 1;
                    }
                }
            }

            $result = [
                'building_count' => $residentialComplex->building_count,
                'sections' => $RCSectionStatuses
            ];
        }

        return $result;
    }
}
