<?php

namespace App\Console\Commands;

use App\Components\Functions;
use App\Jobs\CreateDelayNotification;
use App\Jobs\SendMailUser;
use App\Models\CollectSpend;
use App\Models\Config;
use App\Models\Contract;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Package;
use App\Models\Renter;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\RoomNeedMore;
use App\Models\RoomReservation;
use App\Models\RoomType;
use App\Models\SocialPost;
use App\Models\UserPackage;
use App\Notifications\SendEmailActive;
use App\User;
use Carbon\Carbon;
use Google\Cloud\Storage\StorageClient;
use Goutte\Client;
use Illuminate\Console\Command;
use Excel;
use Minishlink\WebPush\Subscription;
use Minishlink\WebPush\WebPush;
use Sendpulse\RestApi\ApiClient;
use Sendpulse\RestApi\Storage\FileStorage;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

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

    /**
     * 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()
    {
	            $role  = Role::query()->where('name', 'owner')->first();

        $permissions = Permission::all()->pluck('name')->toArray();

        $role->syncPermissions($permissions);

	    dd();
        $items = Renter::all();

        foreach ($items as $item)
        {
            if (empty($item->email)) {
                if (!empty($item->user_id)) {
                    $user = User::find($item->user_id);
                    if ($user) {
                        $item->email = $user->email;
                        $item->save();
                    }
                }
            }

        }
        dd();
       // dd(mb_strtoupper('Dãy A'));
      //  dd(Functions::calculateAmountForOrder(1411));

//        $role  = Role::create([
//            'name' => 'owner'
//        ]);
//
//        $permissions = Permission::all()->pluck('name')->toArray();
//
//        $role->syncPermissions($permissions);
//
//        $users = User::where('type', User::OWNER)->get();
//
//        foreach ($users as $user)
//        {
//            $user->assignRole('owner');
//        }


       // 669

//        $items = User::where('type', User::OWNER)->get();
//        $contract = Config::find(1);
//       // Config::where('id', '<>', 1)->delete();
//        foreach ($items as $item)
//        {
//        	if($item->id != 669) {
//		        Config::updateOrCreate( [
//			        'owner_id' => $item->id,
//		        ], [
//			        'owner_id'        => $item->id,
//			        'voucher_collect' => $contract->voucher_collect,
//			        'voucher_spend'   => $contract->voucher_spend,
//			        'contract'        => $contract->contract
//		        ] );
//	        }
//        }

//        $contract = Config::find(1);
//        \DB::table('samples')->insert([
//            'voucher_collect' => $contract->voucher_collect,
//			        'voucher_spend'   => $contract->voucher_spend,
//			        'contract'        => $contract->contract
//        ]);
//        dd();
        $items = User::where('type', User::OWNER)->get();


        foreach ($items as $user)
        {
            $package = UserPackage::where('user_id', $user->id)->first();

            if($package)
            {
                $user->package_id = $package->package_id;
                $user->save();
            }
        }

        dd();
//        foreach ($items as $item)
//        {
//            $pay = Functions::calculateAmountForOrder($item->id)['pay'];
//            $item->pay = $pay;
//            $item->remain = $item->amount - $pay;
//            $item->save();
//        }
//        $items = ElectricWater::all();
//
//        foreach ($items as $item)
//        {
//            $hostelName = null;
//            $hostel = Hostel::find($item->hostel_id);
//            if($hostel)
//            {
//                $hostelName = $hostel->name;
//            }
//
//            $roomName = null;
//            $room = Room::find($item->room_id);
//            if($room)
//            {
//                $roomName = $room->name;
//            }
//
//            $item->hostel_name = $hostelName;
//            $item->room_name = $roomName;
//            $item->save();
//        }
//
        dd();
        $items = RenterRoom::all();

        foreach ($items as $item)
        {
            $room = Room::find($item->room_id);
            if(!$room)
            {
                $item->delete();
            }
        }

        dd();
        $items = MoneyInfo::all();

        foreach ($items as $item)
        {
            $detailFirst = MoneyDetail::where('money_info_id', $item->id)->first();
            $detailLast = MoneyDetail::where('money_info_id', $item->id)->orderBy('id', 'desc')->first();

            $startDate = null;
            $endDate = null;

            if($detailFirst)
            {
                $startDate = $detailFirst->start_date;
                if(!empty($startDate)) {
                    $startDate = Carbon::createFromFormat('Y-m-d', $startDate)->format('d/m/Y');
                }
            }

            if($detailLast)
            {
                $endDate = $detailLast->end_date;
                if(!empty($endDate)) {
                    $endDate = Carbon::createFromFormat('Y-m-d', $endDate)->format('d/m/Y');
                }
            }

            if(!empty($startDate) && !empty($endDate))
            {
                $name = 'Thu tiền phòng từ '.$startDate. ' đến '.$endDate;
                $item->money_info_name = $name;
                $item->save();
            } else {
                $item->money_info_name = 'Thu tiền dịch vụ';
                $item->save();
            }
        }

        dd();
        try {

            \DB::table('renters')->truncate();
            $items = RenterRoom::all();
            foreach ($items as $item) {
                if ($item->room) {
                    $roomName = $item->room->name;
                } else {
                    $roomName = null;
                }

                if ($item->hostel) {
                    $hostelName = $item->hostel->name;
                } else {
                    $hostelName = null;
                }

                $accountName = null;
                $accountAddress = null;
                $accountPhone = null;

                if ($item->account) {
                    $accountName = $item->account->name;
                    $accountAddress = $item->account->address;
                    $accountPhone = $item->account->phone;
                }

                $image = null;
                $contract = Contract::where('phone', $accountPhone)->first();
                if ($contract) {
                    $image = $contract->customer_image;
                }
               // dump($image);
                Renter::create([
                    'image' => $image,
                    'user_id' => $item->user_id,
                    'hostel_id' => $item->hostel_id,
                    'hostel_name' => $hostelName,
                    'room_id' => $item->room_id,
                    'room_name' => $roomName,
                    'name' => $accountName,
                    'phone' => $accountPhone,
                    'address' => $accountAddress,
                    'status' => Renter::LIVING,
                    'date_joined' => $item->date_joined,
                    'date_end_residence' => $item->date_end_residence,
                    'residence_status' => $item->residence_status,
                ]);
            }
        } catch (\Exception $exception)
        {
            dd($exception->getMessage());
        }

        dd();
        $start = Carbon::createFromFormat('d/m/Y', '10/01/2018');
        $start2 = clone $start;
        $end = Carbon::createFromFormat('d/m/Y', '28/01/2018');

        $endStart = $start2->endOfMonth();

        $periods1 = ($endStart->diffInDays($start) + 1) / $start->daysInMonth;

        $periods2 = $start2->addDay(1)->diffInMonths($end) + 1;

        //    dump($periods2);


        dd($periods1 + $periods2);


        $days = ($end->diffInDays($start2->startOfMonth()) + 1) / ($end->diffInMonths($start2->startOfMonth()) + 1);
        dump($end->diffInMonths($start2->startOfMonth()) + 1);
        $diff = $end->diffInDays($start);
//        dump($diff);
//        dump($days);

        //    dump($diff / $days);

        //  dump(round($diff / $days, 2));
        dd();

//        $items = Hostel::all();
//
//        foreach ($items as $item)
//        {
//          $nums = Functions::getNumberRoomsHostel($item);
//          $item->number_empty_rooms = $nums['number_empty_rooms'];
//          $item->save();
//        }


//        $moneyInfos = MoneyInfo::all();
//
//        foreach ($moneyInfos as $moneyInfo)
//        {
//            $type = $moneyInfo->type;
//
//            MoneyDetail::where('money_info_id', $moneyInfo->id)->update([
//                'type' => $type
//            ]);
//        }
        dd();

        $to = Carbon::createFromFormat('d/m/Y', '01/01/2018');
        $from = Carbon::createFromFormat('m/Y', '5/2018');

        $months = $from->diffInMonths($to);

        dd($months);
        $rooms = Room::all();

        foreach ($rooms as $room) {
            Functions::updateIsEmptyRoom($room);
        }

        dd();
        $type = HostelFee::ELECTRIC;
        $room = Room::find(153);
        $amount = 100;
        dd(Functions::calculateElectricAmount($amount, $room, $type));

        $to = Carbon::createFromFormat('d/m/Y', '31/05/2018');
        dd($to->addMonth(1)->toDateString());
        $from = Carbon::createFromFormat('d/m/Y', '31/11/2018');
        $months = $from->diffInMonths($to);

        dd($months);

        $rooms = RoomNeedMore::all();

        foreach ($rooms as $room) {

            $data = $room->toArray();


            if ($data['gender'] != 'Khác') {

                $data['name'] = 'Tìm ' . $data['number_peoples'] . ' ' . strtolower($data['gender']);
            } else {
                $data['name'] = 'Tìm ' . $data['number_peoples'] . ' ';
            }


            if (isset($data['district'])) {
                $districtdt = Functions::getDistrictName($data['district']);
                if ($districtdt) {
                    $data['name'] .= ' ở ghép tại ' . $districtdt->name;
                }
            }

            $room->name = $data['name'];
            $room->save();

        }
        dd();


        $user = User::find(102);
        dump($user->email);
        \Notification::send($user, new SendEmailActive($user->token_active));

//        $users = User::where('type', User::OWNER)->get();
//
//        foreach ($users as $user)
//        {
//            $numberHostels = Hostel::where('owner_id', $user->id)->count();
//            $hostelsArr = Hostel::where('owner_id', $user->id)->pluck('id')->toArray();
//            $numberRooms = Room::whereIn('hostel_id', $hostelsArr)->count();
//
//            $user->number_hostels = $numberHostels;
//            $user->number_rooms = $numberRooms;
//            $user->save();
//        }

        dd();
//
//        try {
//            $notifications = [
//                [
//                    'subscription' => Subscription::create([
//                        'endpoint' => 'https://fcm.googleapis.com/fcm/send/cEkvy9ZDVm0:APA91bEYPrWN2GEYeeTN38xLeSCd-CtQKCxcXaGTlh7O9YlOPFcd-aHzn5BVQJ3bj9lT56PNr_m-gY_oWmWbX4ZI7KdsGIYxN1p22io4oJ8iH6kw58BnoqakCqWuyX4J2IZ6nN9lGh4_',
//                        'publicKey' => 'BI5MPCrUydsHWpmjDXKsRVfHoQOsaD/8n3dDnaWa9Lr37tuy2fbLnIGj+Bw5fOglCMTbOSRP7xJ8OWbFtMF8FvQ=', // base 64 encoded, should be 88 chars
//                        'authToken' => '1YO+YnCxfvtt8p9hzG7U4g==', // base 64 encoded, should be 24 chars
//                        'contentEncoding' => 'aesgcm'
//                    ]),
//                    'payload' => json_encode(['title'=>'Thông báo từ itro.vn','body' => 'Xin chào các bạn', 'icon' => 'https://itro.vn/frontend3/assets/img/logo.png']),
//                ]
//            ];
//
//            $auth = array(
//                'VAPID' => array(
//                    'subject' => 'https://itro.vn',
//                    'publicKey' => 'BD0Unf2tKZn2vQuf0OFBgB4rcOcCkIA2xxS0UNSsSYs5V0-6zHwd6BHe-94ya5XAHUh3ut_Q1TONbYaaHQ5XyhQ',
//                    'privateKey' => 'bUq5v6EdmbXZU4lRKDWFNQZpdOcV1NpDKiZTRUBd6dw', // in the real world, this would be in a secret file
//                ),
//            );
//
//            $webPush = new WebPush($auth);
//
//            foreach ($notifications as $notification) {
//                $webPush->sendNotification(
//                    $notification['subscription'],
//                    $notification['payload'], // optional (defaults null)
//                    true
//                );
//            }
//        } catch (\Exception $ex)
//        {
//            dd($ex->getTraceAsString());
//        }
//
//        dd();
//    	$sp = new ApiClient('26f0aa18ea26fc02f5c2a22890737969', 'a628237421758808306f60dedc8636bf', new FileStorage());
//
//	    $task = array(
//		    'title' => 'Hello!',
//		    'body' => 'This is my first push message',
//		    'website_id' => 53927,
//		    'ttl' => 20,
//		    'stretch_time' => 0,
//	    );
//
//// This is optional
//	    var_dump($sp->pushListWebsiteVariables(53927));
//
//
//    	dd();
        dd(Carbon::now()->toDateTimeString());


        dd();

        $projectId = 'itro-2017';
        $storage = new StorageClient([
            'projectId' => $projectId,
            'keyFilePath' => public_path('account.json')
        ]);

        $bucket = $storage->bucket('itro-2017.appspot.com');
//        foreach ($bucket as $bucket) {
//                 echo $bucket->name() . PHP_EOL;
//             }
//             die();
        $name = $bucket->upload(fopen(public_path('frontend3/assets/img/gia_re.png'), 'r'));
        $return = 'https://firebasestorage.googleapis.com/v0/b/itro-2017.appspot.com/o/' . $name->name() . '?alt=media';

        dd($return);
//        $phone = preg_replace('/[^0-9]/', '', $matches);
//
//        dd($phone);

        //  preg_replace($pattern, 'xxxx', 'ass 0123456');

        \DB::table('district')->truncate();
        \DB::table('ward')->truncate();

        Excel::load(public_path('district.xls'), function ($reader) {
            $results = $reader->all();
            foreach ($results as $result) {
                if (!empty($result->ma)) {
                    $name = str_replace("Huyện ", "", $result->ten);
                    $name = str_replace("Quận ", "", $name);
                    \DB::table('district')->insert([
                        'districtid' => $result->ma,
                        'name' => $name,
                        'type' => $result->cap,
                        'provinceid' => $result->ma_tp
                    ]);
                }
            }
        });

        Excel::load(public_path('ward.xls'), function ($reader) {
            $results = $reader->all();

            foreach ($results as $result) {
                if (!empty($result->ma)) {
                    $name = str_replace("Phường ", "", $result->ten);
                    $name = str_replace("Xã ", "", $name);
                    $name = str_replace("Thị trấn ", "", $name);
                    \DB::table('ward')->insert([
                        'wardid' => $result->ma,
                        'name' => $name,
                        'type' => $result->cap,
                        'districtid' => $result->ma_qh
                    ]);
                }
            }
        });

        dd();

        $user = User::find(4);
        dispatch(new SendMailUser($user));
        dd();
//    	$hostel = Hostel::find(111);
//	    $total = Functions::getTotalRoomHostel($hostel, '01/2018', '04/2018');
//        dd($total);
//        $hostel = Hostel::find(111);
//
//        $owe = Functions::calculateOweHostel($hostel,'01/2018', '04/2018');
//        dd($owe);


//    	$posts = SocialPost::all();
//
//    	foreach ($posts as $post)
//	    {
//	    	$userId = $post->user_id;
//	    	$user = User::find($userId);
//		    $hostelId = null;
//	    	if($user)
//		    {
//		    	if($user->type == User::OWNER)
//			    {
//			    	$hostel = Hostel::where('owner_id', $user->id)->first();
//			    	if($hostel)
//				    {
//				    	$hostelId = $hostel->id;
//				    }
//			    } else if ($user->type == User::RENTER)
//			    {
//			    	$hostelId = Functions::getHostelByUser($user);
//			    }
//
//			    if(!empty($hostelId))
//			    {
//				    \DB::table('hostel_posts')->updateOrInsert(['social_post_id' => $post->id, 'hostel_id' => $hostelId], [
//					    'social_post_id' => $post->id, 'hostel_id' => $hostelId,
//					    'created_at' => Carbon::now()->toDateTimeString(),
//					    'updated_at' => Carbon::now()->toDateTimeString()
//				    ]);
//			    }
//		    }
//
//	    }
//
//
//	    dd();
        //
//	    dd(json_encode([1, 2, 3]));
        $renterRooms = RenterRoom::all();

        foreach ($renterRooms as $renterRoom) {
            if (empty($renterRoom->hostel_id)) {
                $room = Room::find($renterRoom->room_id);
                if ($room) {
                    $hostel = $room->hostel;
                    if ($hostel) {
                        $renterRoom->hostel_id = $hostel->id;
                        $renterRoom->save();
                    }
                }

                $this->line('Done with ' . $renterRoom->id);
            }
        }
    }
}
