<?php

namespace App\Console\Commands;

use App\Models\CollectSpend;
use App\Models\Contract;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\MoneyInfo;
use App\Models\Room;
use App\User;
use Illuminate\Console\Command;

class DeleteDataOwner extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'delete:owner {--phone=}';

    /**
     * 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()
    {
        //
        $phone = $this->option('phone');

        if(empty($phone))
        {
            {
                $this->error('Dữ liệu không hợp lệ');
                return;
            }
        }
        $owner = User::where('phone', $phone)->where('type', User::OWNER)->first();

        if(!$owner)
        {
            $this->error('Dữ liệu không hợp lệ');
            return;
        }

        $hostels = Hostel::where('owner_id', $owner->id)->get();

        $bar = $this->output->createProgressBar(count($hostels));

        $bar->start();

        foreach ($hostels as $hostel)
        {

            Room::where('hostel_id', $hostel->id)->delete();
            MoneyInfo::where('hostel_id', $hostel->id)->delete();
            CollectSpend::where('hostel_id', $hostel->id)->delete();
            Contract::where('hostel_id', $hostel->id)->delete();
            ElectricWater::where('hostel_id', $hostel->id)->delete();


            $bar->advance();
        }

        Hostel::where('owner_id', $owner->id)->delete();
        User::where('staff_owner_id', $owner->id)->delete();

        $bar->finish();

        $this->line('Delete all data owner: '.$phone);
    }
}
