<?php

namespace App\Console\Commands;

use App\Models\District;
use App\Models\HostelPostCrawl;
use App\Models\HostelPostCrawlMedia;
use App\Models\Province;
use App\Models\Ward;
use GuzzleHttp\Client;
use Illuminate\Console\Command;

class CrawlOhana extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'crawl:ohana';

    /**
     * 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()
    {
        for ($page = 0; $page <= 3; $page++) {
            $this->getData('HCM', $page);

        }
        for ($page = 0; $page <= 3; $page++) {
            $this->getData('HN', $page);
        }
    }

    public function getData($province, $page)
    {
        $client = new Client([
            'headers' => [
                'Content-Type' => 'application/json'
            ]
        ]);
        $roomsApi = 'https://www.ohanaliving.vn/api/web/rooms/view-all';
        $userApi = 'https://www.ohanaliving.vn/api/users/getById?userId=';
        $response = $client->post($roomsApi, [
            'body' => '{"matchData":{"disabled":{"$ne":true}},"room_location":"' . $province . '","page":' . $page . ',"page_number":10,"filters":{}}'
        ]);
        $roomJsons = $response->getBody()->getContents();
        $rooms = json_decode($roomJsons, true);
        $rooms = $rooms['data'];
        if (empty($rooms)) {
            return;
        }
        try {
            foreach ($rooms as $room) {
                $provinceId = null;
                $districtId = null;
                $wardId = null;
                $url = $userApi . $room['user_id'];
                $response = $client->get($url);
                $userJson = $response->getBody()->getContents();
                $userArr = json_decode($userJson, true);
                $userArr = $userArr['data'];
                $image = null;
                if (isset($userArr['provider'])) {
                    if ($userArr['provider'] == 'facebook') {
                        $image = 'https://graph.facebook.com/v7.0/' . $userArr['facebook_user_id'] . '/picture';
                    } else {
                        $image = $userArr['picture']['data']['url'];
                    }
                } else {
                    if (isset($userArr['picture'])) {
                        $image = $userArr['picture']['data']['url'];
                    }
                }

                if (!empty($room['full_address_object']['city']['text'])) {
                    $province = $room['full_address_object']['city']['text'];
                    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($room['full_address_object']['district']['text'])) {
                    $district = $room['full_address_object']['district']['text'];
                    $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($room['full_address_object']['ward']['text'])) {
                    $ward = $room['full_address_object']['ward']['text'];
                    $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' => $room['_id']
                ], [
                    'post_id' => $room['_id'],
                    'user_post' => isset($userArr['name']) ? $userArr['name'] : null,
                    'user_post_image' => $image,
                    'user_post_phone' => $room['phone_number'],
                    'content' => $room['notes'],
                    'province_id' => $provinceId,
                    'district_id' => $districtId,
                    'ward_id' => $wardId,
                    'address' => $room['exact_room_address'],
                    'from' => HostelPostCrawl::FROM_OHANA,
                    'title' => $room['room_name'],
                    'price' => $room['room_price'],
                    'lat' => $room['geocodingApi']['location']['lat'],
                    'lng' => $room['geocodingApi']['location']['lng'],
                    'price_min' => $room['room_price'],
                    'price_max' => $room['room_price']
                ]);

                $images = $room['upload_room_images'];
                HostelPostCrawlMedia::query()
                    ->where('hostel_post_crawl_id', $hostelPost->id)
                    ->delete();
                foreach ($images as $media) {
                    HostelPostCrawlMedia::create([
                        'hostel_post_crawl_id' => $hostelPost->id,
                        'media' => $media
                    ]);
                }

                $this->line('Done with ' . $room['room_name']);
            }
        } catch (\Exception $exception) {
            $this->line('Error ' . $room['_id']);
        }
    }
}
