<?php

namespace App\Http\Resources\Planning;

use App\RoomCount;
use App\RoomType;
use App\Section;
use Illuminate\Http\Resources\Json\ResourceCollection;

class PlanningFilterParameters extends ResourceCollection
{
    /**
     * @var array
     */
    private $parameters;

    /**
     * Create a new resource instance.
     *
     * @param  mixed $resource
     * @param array $parameters
     */
    public function __construct($resource, $parameters = null)
    {
        parent::__construct($resource);
        $this->resource = $resource;
        $this->parameters = is_array($parameters) ? $parameters : [];
    }

    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $result = [];
        /** @var Section $section */
        foreach ($this->collection as $key => $section) {
            $result['sections'][] = [
                'id' => $section->id,
                'section_number' => $section->number ? $section->number : "",
                'building_name' => $section->name ? $section->name : "",
                'date' => $section->date_finish_buildiing ? $section->date_finish_buildiing : "",
                'quarterly' => $section->quarterly_finish ? $section->quarterly_finish->code : "",
                'stage_of_construction' => $section->stage_of_construction->code ?? '',
                'floors' => $section->count_of_floor ? $section->count_of_floor : false
            ];
        }
        if (isset($this->parameters['filter']) && count($this->parameters) > 0) {
            $planning = $this->parameters['filter']->first();
            foreach (RoomCount::all() as $room) {
                $result['room'][] = [
                    'key' => (int) $room->code,
                    'value' => $room->count,
                    'available' => $planning->{$room->code . "_room"} > 0 ? true : false
                ];
            }
            foreach (RoomType::all() as $roomType) {
                $result['room_types'][] = [
                    'key' => $roomType->code,
                    'value' => $roomType->name,
                    'room' => $planning->{"room_" . $roomType->code} > 0 ? true : false
                ];
            }
            $result['space'] = [
                'min' => $planning->min_space,
                'max' => $planning->max_space
            ];
        }

        return $result;
    }
}
