<?php

namespace App\Console\Commands;

use App\Models\Hostel;
use App\Models\Room;
use App\Models\RoomType;
use App\User;
use Illuminate\Console\Command;

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

    /**
     * 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()
    {
        //
        $limit = 1000;
        Hostel::where('source', Hostel::SOURCE_CRAWLER)->forceDelete();
        $crawlers = \App\Models\Crawler::take($limit)->get();

        foreach ($crawlers as $crawler) {
            try {
                \DB::beginTransaction();

                $owner = User::find(7711);
                $item = [
                    'name' => $crawler->name,
                    'lat' => $crawler->lat,
                    'lng' => $crawler->lng,
                    'address' => $crawler->address,
                    'phone' => $crawler->phone,
                    'desc' => $crawler->desc,
                    'owner_id' => $owner->id,
                    'source' => Hostel::SOURCE_CRAWLER
                ];


                $hostel = Hostel::create($item);

                $roomType = RoomType::create([
                    'name' => 'Phòng loại 1',
                    'price' => $crawler->price,
                    'size' => $crawler->size,
                    'max_peoples' => 4,
                    'owner_id' => $owner->id,
                    'hostel_id' => $hostel->id
                ]);
                Room::create([
                    'hostel_id' => $hostel->id,
                    'lat' => $crawler->lat,
                    'lng' => $crawler->lng,
                    'name' => 'P101',
                    'size' => $crawler->size,
                    'price' => $crawler->price,
                    'type' => $roomType->id
                ]);

                \DB::commit();
            } catch (\Exception $exception) {
                \DB::rollBack();
            }
            $this->line('Done with ' . $crawler->name);
        }
    }
}
