<?php

namespace App\Services\Parser;

use GuzzleHttp;
use Symfony\Component\DomCrawler\Crawler;

class PlanningService
{
//    const URL = 'https://novostroyki.lun.ua';
    const URL = 'https://lun.ua';
    const MANY_LEVEL_TITLE = "Багаторівнева";
    const STUDIO_TITLE = "Студія";
    private $planning = [];

    /**
     * @param $url
     * @param $content
     */
    public function getPlanning($url, $html = null)
    {
        $data = [];
        $rcOption = $this->getRCOption($html);
        if (isset($rcOption['building_id'])) {
            $buildingId = $rcOption['building_id'];
            $planningOptions = $this->guzzleRequest('/api/flats-filters-config', $rcOption);
        }
        $buildingHouseParameters = [];
        $buildingHouseIds = isset($planningOptions['house_id']) && isset($planningOptions['house_id']['options']) ? $planningOptions['house_id']['options'] : [];
        if (count($buildingHouseIds) == 0) {
            $roomPlanning = isset($planningOptions['rooms_count']) && isset($planningOptions['rooms_count']['options']) ? $planningOptions['rooms_count']['options'] : [];
            if (count($roomPlanning) > 0) {
                $parameters = [
                    'building_id' => (int)$buildingId
                ];
                $data['building'] = ["title" => "Будинок 1"];
                $data['flor'] = isset($planningOptions['abs_max_floor']) ? $planningOptions['abs_max_floor'] : null;
                $data['rooms'] = $this->getPlanningByHouseRoom($planningOptions, $parameters);
                $data['feature'] = $this->featuredOption($planningOptions, $parameters);
            }
        }

        foreach ($buildingHouseIds as $key => $building) {
            if (
                $building['disabled'] == false
//                &&
//            $key == 5
            ) {
                $parameters = [
                    'building_id' => (int)$buildingId,
                    'house_id' => $building['value']
                ];
                $buildingHouseParameter = $this->guzzleRequest('/api/flats-filters-config', $parameters);
//                $buildingHouseParameters[] = $buildingHouseParameter;
                $data[$key]['building'] = $building;
                $data[$key]['flor'] = isset($buildingHouseParameter['abs_max_floor']) ? $buildingHouseParameter['abs_max_floor'] : null;
                $data[$key]['rooms'] = $this->getPlanningByHouseRoom($buildingHouseParameter, $parameters);
                $data[$key]['feature'] = $this->featuredOption($buildingHouseParameter, $parameters);
            }
        }

        return $data;
    }

    public function getPlanningByHouseRoom($buildingHouseParameter, $parameters)
    {
        $planningLayout = $this->guzzleRequest('/api/filter/layout', $parameters);
        if (isset($planningLayout['html'])) {
            return $this->parseAllPlanningByHouseId($planningLayout["html"], $buildingHouseParameter);
        }
    }

    public function parseAllPlanningByHouseId($html, $buildingHouseParameter)
    {
        $crawler = new Crawler();
        $crawler->addHtmlContent($html, 'UTF-8');
        $divHeaderElements = $crawler->filter('div.Plans-header');
        $divHeaderElementsCount = $divHeaderElements->count();
        $divPlanElements = $crawler->filter('div.Plans-grid');
        $roomArray = isset($buildingHouseParameter['rooms_count']) && isset($buildingHouseParameter['rooms_count']['options']) ? $buildingHouseParameter['rooms_count']['options'] : [];
        $roomArrayCount = count($roomArray);
        $roomArray[] = [
            'value' => count($roomArray) > 0 ? $roomArray[$roomArrayCount - 1]['value'] + 1 : null,
            'title' => count($roomArray) > 0 ? $roomArray[$roomArrayCount - 1]['value'] + 1 : null,
            'analytics' => count($roomArray) > 0 ? 'rooms_count_5' : null,
            'active' => true,
            'disabled' => false
        ];
        $enabledRoomCounter = 0;
        $planningData = [];
        foreach ($roomArray as $key => $room) {
            if ($room['disabled'] == false) {
                $planningSectionsByRoomCount = $divPlanElements->slice($enabledRoomCounter, 1)->count();
                $planningSectionsByRoomHeaderCount = $divHeaderElements->slice($enabledRoomCounter, 1)->count();

                if ($room['title'] == '4+' || $room['value'] == 5) {
//                    $roomArray[4]['disabled'] = false;
                    $headerCount = $divHeaderElements->filter('h2')->count();
                    $planningSectionsHeaderBlock = $divHeaderElements->slice($enabledRoomCounter, 1);
                    $headerCount = $planningSectionsHeaderBlock->count();
                    if ($headerCount > 0) {
                        $header = $planningSectionsHeaderBlock->filter('h2')->text();
                        $explodeHeaderByBlock = explode('-', trim($header));
                        $blockWithNumber = count($explodeHeaderByBlock) > 0 ? $explodeHeaderByBlock[0] : "";
                        if (!empty($blockWithNumber)) {
                            $roomNumberExplode = explode(' ', trim($blockWithNumber));
                            $roomNumber = count($roomNumberExplode) > 1 ? $roomNumberExplode[1] : 0;
                            if ($roomNumber > 0) {
                                $room['value'] = (int)$roomNumber;
                                $room['title'] = (int)$roomNumber;
                            }
                        }
                    }
                }

                if ($planningSectionsByRoomCount > 0) {
                    $planningSectionsByRoomChildren = $divPlanElements->slice($enabledRoomCounter, 1)->children();
                    $enabledRoomCounter += 1;
                    $planningData[] = [
                        'room_count' => $room,
                        'planning' => $this->parsePlanningByRoom($planningSectionsByRoomChildren)
                    ];
                }
            }
        }

        return $planningData;
    }

    /**
     * @param $planningSections
     */
    public function parsePlanningByRoom($planningSections)
    {
        $data = [];
        if ($planningSections != null) {
            $countOfPlanningCarts = $planningSections->count();
            for ($count = 0; $count < $countOfPlanningCarts; $count++) {
                /** @var Crawler $planningCart */
                $planningCart = $planningSections->eq($count);
                $image = $planningCart->filter('img')->attr('data-srcset');
                $alt = $planningCart->filter('img')->attr('alt');
                $parseSpace = $planningCart->filter('p')->text();
                $trimSpace = trim($parseSpace);
                $explodeSpace = explode(" ", $trimSpace);
                $space = count($explodeSpace) > 0 ? $explodeSpace[0] : "";
                $isSold = $planningCart->filter('div.PlansCard-label')->count();
                if (
                    preg_match('/схожих планувань/', $parseSpace)
                    || preg_match('/схожих планування/', $parseSpace)
                    || preg_match('/схоже планування/', $parseSpace)

                ) {
                    if (preg_match('/схоже планування/', $parseSpace)) {
                        $a = $parseSpace;
                    }
                    $link = $planningCart->filter('a')->attr('href');
                    $a = $link;
                    $similarPlanningData = $this->parseSinglePlanning($link, $isSold, $alt);
                    if (count($similarPlanningData) > 0) {
                        foreach ($similarPlanningData as $similarPlanning) {
                            $data[] = $similarPlanning;
                        }
                    } else {
                        if (preg_match('/-/', $space)) {
                            $spaceExpl = explode('-', $space);
                            $space = count($spaceExpl) > 0 ? $spaceExpl[0] : "";
                        }
                        $data[] = [
                            'is_sold' => $isSold > 0 ? true : false,
                            'image' => $image,
                            'space' => $space,
                            'alt' => $alt
                        ];
                    }
                } else {
                    if (preg_match('/-/', $space)) {
                        $spaceExpl = explode('-', $space);
                        $space = count($spaceExpl) > 0 ? $spaceExpl[0] : "";
                    }
                    $data[] = [
                        'is_sold' => $isSold > 0 ? true : false,
                        'image' => $image,
                        'space' => $space,
                        'alt' => $alt
                    ];
                }
            }
        }

        return $data;
    }

    public function parseSinglePlanning($link, $isSold, $alt)
    {
        $link = self::URL . $link;
        $html = file_get_contents($link);
        $crawler = new Crawler();
        $crawler->addHtmlContent($html, 'UTF-8');
        $planningSections = $crawler->filter('div.PlanView-layout-sidebar > section');
        $planningSectionsCount = $planningSections->count();
        if ($planningSectionsCount >= 2) {
            $planningGrid = $planningSections->eq(1);
            $planningHeader = $planningGrid->filter('div.h2')->text();
            $data = [];
            if (preg_match('/Схожі планування/', $planningHeader)) {
                $planningGridBlocks = $planningGrid->filter('div.PlanGrid')->children();
                foreach ($planningGridBlocks as $planningGridBlock) {
                    $planningGridBlockCrawler = new Crawler($planningGridBlock);
                    $fullSpace = $planningGridBlockCrawler->filter('p')->text();
                    $explodeSpace = explode(' ', $fullSpace);
                    $space = count($explodeSpace) > 0 ? $explodeSpace[0] : '';
                    $image = $planningGridBlockCrawler->filter('img')->attr('src');
                    $explodePath = explode('/', $image);
                    $imagePathCount = count($explodePath);
                    $imageId = $explodePath[$imagePathCount - 1];
                    $image = '//img.lun.ua/layout-640x640/' . $imageId;
                    $data[] = [
                        'is_sold' => $isSold > 0 ? true : false,
                        'image' => $image,
                        'space' => $space,
                        'alt' => $alt
                    ];
                }
            } else {
                $fullSpace = $crawler->filter('section.PlanInfo h2 b')->text();
                $explodeSpace = explode(' ', $fullSpace);
                $space = count($explodeSpace) > 0 ? $explodeSpace[0] : '';
                $imageAlt = $crawler->filter('section.PlanInfo div.PlanInfo-image img')->attr('alt');
                $image = $crawler->filter('section.PlanInfo div.PlanInfo-image img')->attr('src');
                $explodePath = explode('/', $image);
                $imagePathCount = count($explodePath);
                $imageId = $explodePath[$imagePathCount - 1];
                $image = '//img.lun.ua/layout-640x640/' . $imageId;
                $data[] = [
                    'is_sold' => $isSold > 0 ? true : false,
                    'image' => $image,
                    'space' => $space,
                    'alt' => $imageAlt
                ];
            }

            return $data;
        } else {
            $fullSpace = $crawler->filter('section.PlanInfo h2 b')->text();
            $explodeSpace = explode(' ', $fullSpace);
            $space = count($explodeSpace) > 0 ? $explodeSpace[0] : '';
            $imageAlt = $crawler->filter('section.PlanInfo div.PlanInfo-image img')->attr('alt');
            $image = $crawler->filter('section.PlanInfo div.PlanInfo-image img')->attr('src');
            $explodePath = explode('/', $image);
            $imagePathCount = count($explodePath);
            $imageId = $explodePath[$imagePathCount - 1];
            $image = '//img.lun.ua/layout-640x640/' . $imageId;
            $data[] = [
                'is_sold' => $isSold > 0 ? true : false,
                'image' => $image,
                'space' => $space,
                'alt' => $imageAlt
            ];

            return $data;
        }

        return [];
    }

    public function guzzleRequest($url, $options)
    {
        $data = [
            "building_id" => $options['building_id'],
            "lang" => "uk",
            "house_id" => isset($options['house_id']) ? [$options['house_id']] : [],
            "ready_state" => [],
            "rooms_count" => [],
//            "rooms_count" => [$options['room_id']],
            "features" => isset($options['features']) ? [$options['features']] : [],
            "max_area" => [],
            "max_floor" => null,
            "min_area" => null,
            "min_floor" => null,
            "show_sold" => true
        ];
        $client = new GuzzleHttp\Client();
        $request = $client->post(self::URL . $url, [
//            'headers' => ['Content-Type' => 'application/json'],
            'json' => $data
        ]);
        $response = $request->getBody()->getContents();

        return json_decode($response, true);
    }

    private function getRCOption(string $content): array
    {
        $match = [];
        preg_match_all('/\[(.*)\]/', $content, $match);
        if (!isset($match[0])) {
            return [];
        }
        $data = json_decode($match[0][5], true);
        if (isset($data[0]) && !empty($data[0])) {
            return $data[0];
        }

        return [];
    }

    public function planningFeatureParameters($options)
    {
        $parameters = [];
        if (isset($options['features']) && isset($options['features']['options'])) {
            foreach ($options['features']['options'] as $feature) {
                if (($feature['title'] == self::MANY_LEVEL_TITLE || $feature['title'] == self::STUDIO_TITLE) && $feature['disabled'] == false) {
                    $parameters[] = $feature;
                }
            }
        }

        return $parameters;
    }

    public function featuredOption($buildingHouseParameter, $parameters)
    {
        $data = [];
        $featuredOption = isset($buildingHouseParameter) ? $this->planningFeatureParameters($buildingHouseParameter) : [];
        if (count($featuredOption) > 0) {
            foreach ($featuredOption as $feature) {
                $parameters['features'] = $feature['value'];
            }
            $buildingHouseParameter = $this->guzzleRequest('/api/flats-filters-config', $parameters);
            $data = $this->getPlanningByHouseRoom($buildingHouseParameter, $parameters);
        }

        return $data;
    }
}


//$divHeaderElements->each(function (Crawler $node, $i) {
//                    $headerElement = $node;
////            $headerElement->
//
//                });
//                $headerElementBlock = $divHeaderElements->first()->filter('h2')->text();
//                $headerElementBlock = $divHeaderElements->getNode(0)->childNodes->item(1)->textContent;
//                $headerElementBlock = $divHeaderElements->getNode($enabledRoomCounter)->firstChild->textContent;
//                $text = $headerElementBlock-;
//                $planningCartBlock = $divPlanElements->getNode($enabledRoomCounter)->childNodes;
//                $planningCartElements = $planningCartBlock->childNodes;
//                $plan = $divPlanElements->each(function (Crawler $node, $i) use ($enabledRoomCounter, &$planningSections) {
//                    if ($enabledRoomCounter == $i) {
//                        return $planningSection = $node->children();
//                    }
//                });
//        $buildingRoomCount = isset($buildingHouseParameter['rooms_count']) && isset($buildingHouseParameter['rooms_count']['options']) ?
//                    $buildingHouseParameter['rooms_count']['options'] : [];
//        foreach ($buildingRoomCount as $room) {
//            if ($room['disabled'] == false) {
//                $parameters['room_id'] = $room['value'];
//            }
//
//            $planningLayout = $this->guzzleRequest('/api/filter/layout', $parameters);
//            if (isset($planningLayout['html'])) {
//                $this->parsePlanningByHouseIdAndRoom($planningLayout["html"]);
//            }
//        }

