<?php

namespace App\Console\Commands;

use App\Components\Functions;
use App\Models\District;
use App\Models\HostelPostCrawl;
use App\Models\HostelPostCrawlMedia;
use App\Models\Province;
use App\Models\Ward;
use Goutte\Client;
use Illuminate\Console\Command;

class CrawlerSite extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'crawl:site {--location=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $location = $this->option('location');
        if (empty($location)) {
            $location = 'ho-chi-minh';
        }
        $client = new Client();

        for ($i = 1; $i <= 3; $i++) {
            try {
                $crawler = $client->request('GET', 'https://phongtro123.com/tinh-thanh/' . $location . '?page=' . $i);
                $crawler->filter('div.post-info.clearfix > div.title > a')->each(function ($node) use ($client) {
                    $link = $node->link();
                    $post = $client->click($link);
                    $name = trim($post->filter('h1')->text());
                    $address = trim($post->filter('div.block-content-1 > div > div.table_overview > table > tr:nth-child(1) > td:nth-child(2)')->text());
                    $phone = trim($post->filter('div.block-content-1 > div > div.table_overview > table >  tr:nth-child(5) > td:nth-child(4) > a > span')->text());
                    $price = trim($post->filter('div.block-content-1 > div > div.table_overview > table >  tr:nth-child(7) > td:nth-child(4) > span')->text());
                    $id = trim($post->filter('div.block-content-1 > div > div.table_overview > table >  tr:nth-child(4) > td:nth-child(2)')->text());

                    $userPost = trim($post->filter('div.block-content-1 > div > div.table_overview > table >  tr:nth-child(4) > td:nth-child(4)')->text());
                    $price = str_replace('triệu/tháng', '', $price);
                    $price = str_replace('Triệu/tháng', '', $price);
                    $price = intval(trim($price));
                    $price *= 1000000;
                    $desc = $post->filter('#motachitiet')->html();
                    $desc = str_replace('Thông tin mô tả', '', $desc);
                    $lat = trim($post->filter('#__maps_content')->attr('data-lat'));
                    $lng = trim($post->filter('#__maps_content')->attr('data-long'));

                    $source = HostelPostCrawl::FROM_PHONGTRO_123;

                    $addressArr = explode(',', $address);
                    $provinceId = null;
                    $districtId = null;
                    $wardId = null;

                    if (is_array($addressArr)) {
                        $province = null;
                        $district = null;
                        $ward = null;

                        $addressArr = array_reverse($addressArr);
                        if (isset($addressArr[0])) {
                            $province = trim($addressArr[0]);
                        }
                        if (isset($addressArr[1])) {
                            $district = trim($addressArr[1]);
                        }

                        if (isset($addressArr[2])) {
                            $ward = trim($addressArr[2]);
                        }
                        if (!empty($province)) {
                            if ($province == 'Hồ Chí Minh') {
                                $province = 'TP. Hồ Chí Minh';
                            }
                            $province = trim($province);
                            $provinceItem = Province::query()->where('name', $province)->first();
                            $provinceId = optional($provinceItem)->provinceid;
                        }

                        if (!empty($district)) {
                            $district = str_replace('Quận', '', $district);
                            $district = str_replace('Huyện', '', $district);
                            $district = trim($district);
                            $districtItem = District::query()->where('name', $district)->first();
                            $districtId = optional($districtItem)->districtid;
                        }

                        if (!empty($ward)) {
                            $ward = str_replace('Phường', '', $ward);
                            $ward = str_replace('Xã', '', $ward);
                            $ward = str_replace('Thị trấn', '', $ward);
                            $ward = trim($ward);
                            $wardItem = Ward::query()->where('name', $ward)->first();
                            $wardId = optional($wardItem)->wardid;
                        }

                    }

                    $hostelPost = HostelPostCrawl::query()->updateOrCreate([
                        'post_id' => $id
                    ], [
                        'post_id' => $id,
                        'user_post' => $userPost,
                        'user_post_image' => null,
                        'user_post_phone' => $phone,
                        'content' => $desc,
                        'province_id' => $provinceId,
                        'district_id' => $districtId,
                        'ward_id' => $wardId,
                        'address' => $address,
                        'from' => $source,
                        'title' => $name,
                        'price' => $price,
                        'lat' => $lat,
                        'lng' => $lng,
                        'price_min' => $price,
                        'price_max' => $price
                    ]);

                    $imagesArr = [];
                    $slides = $post->filter('#hinhanh img')->each(function ($node2) use (&$imagesArr) {
                        $image = $node2->attr('src');
                        $image = str_replace('900x600', '450x300', $image);
                        $imagesArr[] = $image;
                    });
                    HostelPostCrawlMedia::query()
                        ->where('hostel_post_crawl_id', $hostelPost->id)
                        ->delete();
                    foreach ($imagesArr as $media) {
                        HostelPostCrawlMedia::create([
                            'hostel_post_crawl_id' => $hostelPost->id,
                            'media' => $media
                        ]);
                    }
                    $this->line('Done with ' . $name);
                    //  dd($name);
                    //  dd($post->html());
                });
            } catch (\Exception $exception) {
                dump($exception->getMessage() . '||' . $exception->getLine());
                dd($exception->getTraceAsString());
            }
        }
    }
}
