<?php

namespace App\Http\Resources;

use App\Helpers\ImageSize;
use App\Http\Controllers\Traits\PriceFormatTrait;
use App\Http\Resources\ResidentialComplex\ResidentialComplexBanks;
use App\Http\Resources\ResidentialComplex\ResidentialComplexCharacteristics;
use App\Http\Resources\ResidentialComplex\ResidentialComplexCourseOfConstruction;
use App\Http\Resources\ResidentialComplex\ResidentialComplexDocument;
use App\Http\Resources\ResidentialComplex\ResidentialComplexFlatPrice;
use App\Http\Resources\ResidentialComplex\ResidentialComplexGeneralRating;
use App\Http\Resources\ResidentialComplex\ResidentialComplexLocation;
use App\Http\Resources\ResidentialComplex\ResidentialComplexMarkers;
use App\Http\Resources\ResidentialComplex\ResidentialComplexSecretBuyerRating;
use App\Http\Resources\ResidentialComplex\ResidentialComplexSection;
use App\Repository\DeveloperRepository;
use App\Repository\PlanningPriceRepository;
use App\Repository\PriceRepository;
use App\Repository\PromotionRepository;
use App\Repository\ResidentialComplexRepository;
use App\Services\ResidentialComplexRatingService;
use Illuminate\Http\Resources\Json\JsonResource;

class ResidentialComplex extends JsonResource
{
    use PriceFormatTrait;

    /** @var array */
    private $parameters;

    /** @var ResidentialComplexRatingService */
    private $residentialComplexRatingService;

    /**
     * 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 into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        /** @var \App\ResidentialComplex $residentialComplex */
        $residentialComplex = $this->resource;

        $this->residentialComplexRatingService = (new ResidentialComplexRatingService($residentialComplex));

        $result_short = [
            "id" => $residentialComplex->id ? $residentialComplex->id : null,
            "name" => $residentialComplex->name ? $residentialComplex->name : "",
            "slug" => $residentialComplex->code ? $residentialComplex->code : "",
        ];

        $result_full = [];
        if (isset($this->parameters['show_residential_complex'])) {
            $developer = $residentialComplex->developer;

            $developerData =  $this->otherOption($developer, $residentialComplex);
            if (count($developerData) > 0) {
                list($residentialComplexDeveloper, $developerResidentialComplexes, $developerPromotion) =
                    $this->otherOption($developer, $residentialComplex);
            }

            list($sectionsCount, $sectionsFloorsUnique) = $this->getSectionFloorUnique($residentialComplex);
            $pricing = (new PriceRepository())->fullPrice($residentialComplex->id);
            $planningPricing = (new PlanningPriceRepository())->fullPrice($residentialComplex->id);
            $termsOfPayments = $residentialComplex->term_of_paymentes;

            $this->getExchangeRate();

            $result_full = [
                'site_link' => $residentialComplex->site_link ?? "",
                'site_utm' => $residentialComplex->site_utm ?? "",
//                'phone' => $residentialComplex->developer ? $residentialComplex->developer->phone : "",
                'phone' => !empty($residentialComplex->phone) ? $residentialComplex->phone :
                    ($residentialComplex->developer && !empty($residentialComplex->developer->phone) ?
                        $residentialComplex->developer->phone : ""),
                'seo_text' => $residentialComplex->residential_complex_seos()->first() ?
                    $residentialComplex->residential_complex_seos()->first()->seo_text : "",
                'buildingo_count' => $residentialComplex->building_count,
                'building_floors' => $sectionsFloorsUnique,
                'sections_count' => $sectionsCount,
                'lowest_price' => !empty($residentialComplex->min_price) ? $this
                    ->formatPrice((float) $residentialComplex->min_price)  : 0,
//                'flat_count' => $residentialComplex->room_count,
                'images' => new ResidentialComplexImagesCollection($residentialComplex->getMedia('landscape_photo')),
                'show_planning' => $residentialComplex->is_show_planning > 0 ? true : false,
                'show_price' => $residentialComplex->is_show_price > 0 ? true : false,
                'show_terms_of_payment' => $residentialComplex->is_show_terms_of_payments > 0 ? true : false,
                'info' => [
                    'price' => $residentialComplex->price_info,
                    'building' => $residentialComplex->building_status_info,
                    'planning' => $residentialComplex->planning_info,
                    'documment' => $residentialComplex->document_info
                ],
                'contact' => [
                    'presentation' => [
                        'show' => $residentialComplex->is_show_presentation > 0 ? true : false,
                        'content' => $residentialComplex->presentation ?
                            asset(env('UPLOAD_PATH').'/'. ImageSize::PRESENTATION .'/'.  $residentialComplex->presentation) : ""
                    ],
                    'consultation' => [
                        'show' => $residentialComplex->is_show_consultation > 0 ? true : false,
                        'content' => null
                    ],
                    'telegram' => [
                        'show' => $residentialComplex->is_show_telegram > 0 ? true : false,
                        'content' => $residentialComplex->telegram
                    ],
                    'viber' => [
                        'show' => $residentialComplex->is_show_viber > 0 ? true : false,
                        'content' => $residentialComplex->viber
                    ],
                    'skype' => [
                        'show' => $residentialComplex->is_show_skype > 0 ? true : false,
                        'content' => $residentialComplex->skype
                    ],
                    'whatsapp' => [
                        'show' => $residentialComplex->is_show_whatsapp > 0 ? true : false,
                        'content' => $residentialComplex->whatsapp
                    ],
                ],
                'consultation_description' => $residentialComplex->consultation_description,
                'consultation_button' => [
                    'text' => $residentialComplex->consultation_button_text ?
                        $residentialComplex->consultation_button_text : "",
                    'color' => $residentialComplex->consultation_button_color ?
                        $residentialComplex->consultation_button_color : "",
                ],
                'preview' => [
                    'text' => $residentialComplex->preview ?
                        $residentialComplex->preview : "",
                    'color' => $residentialComplex->preview_color_picker ?
                        $residentialComplex->preview_color_picker : "",
                ],
                'promotion' => [
                    'plajka' => $residentialComplex->plajka ? $residentialComplex->plajka : "",
                    'color_picker' => $residentialComplex->color_picker ? $residentialComplex->color_picker : "",
                ],
                'commissioning' => [
                    'building_put_into_operation' => $residentialComplex->building_put_into_operation,
                    'year' => $residentialComplex->date_putting_into_operation,
                    'quarterly' => $residentialComplex->quarterly_putting_into_operation()->first() ?
                        $residentialComplex->quarterly_putting_into_operation()->first()->code : ""
                ],

//                'room' => [
//                    'room_count' => $residentialComplex->room_count,
//                    'date' => $residentialComplex->room_count_date
//                ],
                'stage_of_construction' => $residentialComplex->stageOfConstruction()->first() ?
                    $residentialComplex->stageOfConstruction()->first()->name : "",
                'stage_of_construction_statistic' => new ResidentialComplexSection($residentialComplex),
                'developer' => isset($residentialComplexDeveloper) && $residentialComplexDeveloper->first() ?
                    new Developer($residentialComplexDeveloper->first(), [
                        'developer_id' => $developer ? $developer->id : null,
                        'statistic' => true,
                        'developer_residential_complex' => true]) : false,
                'characteristics' => new ResidentialComplexCharacteristics($residentialComplex),
//                'flats_statistic' => new ResidentialComplexFlatPrice($residentialComplex),

                'pricing' => count($pricing) > 0 ? new SectionPriceCollection($pricing) : false,
                'planning_pricing' => count($planningPricing) > 0 ? new SectionPriceCollection($planningPricing) : false,
                'terms_of_payments' => count($termsOfPayments) > 0 ? new TermOfPaymentCollection($termsOfPayments) : false,

                'customer_rating' => new CustomerRatingAVG($residentialComplex, [
                    'rating' => $this->residentialComplexRatingService->customerRatingGeneralAVG()
                ]),
                'secret_buyer_ratings' =>
                    new ResidentialComplexSecretBuyerRating($residentialComplex, $this->residentialComplexRatingService->secretBuyerRating),
                'banks' => $residentialComplex->show_bank > 0 ?
                    new ResidentialComplexBanks($residentialComplex) : false,
                'show_bank' => $residentialComplex->show_bank > 0 ? true : false,
                'documents' => $residentialComplex->document->count() > 0 ?
                    new ResidentialComplexDocument($residentialComplex) : false,
                'course_of_constructions' => new ResidentialComplexCourseOfConstruction($residentialComplex),
                'other_residential_complexes' => isset($developerResidentialComplexes) ?
                    new ResidentialComplexCollection($developerResidentialComplexes, ['show_first_image' => true]) : [],
                'developer_promotion' => isset($developerPromotion) && count($developerPromotion) > 0 ?
                    new PromotionCollection($developerPromotion) : [],
                'markers' => new ResidentialComplexMarkers($residentialComplex),
                'location' => new ResidentialComplexLocation($residentialComplex),
                'general_rating' => new ResidentialComplexGeneralRating($residentialComplex, [
                    'rating_service' => $this->residentialComplexRatingService,
                ])
            ];
        }

        $result = array_merge($result_short, $result_full);

        return $result;
    }

    public function getSectionFloorUnique($residentialComplex)
    {
        $sections = $residentialComplex->sections()->get();
        $sectionsCount = $sections->count();

        $sectionCollection = collect($sections);
        $sectionsFloors = $sectionCollection->map(function ($item, $key) {
            if ($item->count_of_floor > 0) {
                return $item->count_of_floor;
            }
        });

        $sectionsFloorsUnique = array_unique($sectionsFloors->toArray());

        return [$sectionsCount, $sectionsFloorsUnique];
    }

    public function otherOption($developer, $residentialComplex)
    {
        $parameters = [
        'developer_id' => $developer ? $developer->id : null,
        'hide_residential_complex_id' => $residentialComplex ? $residentialComplex->id : null,
        'statistic' => true,
        'developer_residential_complex' => true
    ];

        if ($developer) {
            $residentialComplexDeveloper = (new DeveloperRepository())->find($parameters);

            /** @var \App\ResidentialComplex $residentialComplex */
            $developerResidentialComplexes =
                (new ResidentialComplexRepository())->listResidentialComplex($parameters);
            if (count($developerResidentialComplexes) == 0) {
                $developerResidentialComplexes = $residentialComplex->
                recomended_residental_complex_id()
                    ->where('enabled', true)
                    ->take(3)
                    ->get();
            }

            $developerPromotion = (new PromotionRepository())->listOfPromotion(3, $parameters);
            return [$residentialComplexDeveloper, $developerResidentialComplexes, $developerPromotion];
        }

        return [];
    }
}
