<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Auth;

class ProfileSwitchEvent implements ShouldBroadcastNow
{
    use Dispatchable;
    use InteractsWithSockets;
    use SerializesModels;

    public $activeProfile;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($activeProfile)
    {
        $this->activeProfile = $activeProfile;
        $this->checkVerification();
    }


    public function checkVerification()
    {
        // Use the query method which is clearly available
        $profile = getActiveProfile();

        if ($profile && method_exists($profile, 'hasVerifiedEmail') && ! $profile->hasVerifiedEmail()) {
            $profile->sendEmailVerificationNotification();
            session(['notification.alert' => 'Your profiles email address is unverified. We have just sent you a new verification email. The link in this email will expire within 60 minutes.']);
        }

        activity()
            ->useLog('Active profile')
            ->performedOn($profile)
            ->causedBy(Auth::guard('web')->user())
            ->withProperties([
                'attributes' => [
                    'last_login_at' => now()->toDateTimeString(),
                ],
                'old' => [
                    'last_login_at' => ($profile->last_login_at instanceof \Carbon\Carbon)
                        ? $profile->last_login_at->toDateTimeString()
                        : $profile->last_login_at,
                ],
            ])
            ->event('switched')
            ->log('Switched to ' . $profile->name);
    }


    public function broadcastQueue()
    {
        return 'broadcastable';
    }


    public function broadcastWith()
    {
        return [
            'userId' => $this->activeProfile['userId'],
            'type' => $this->activeProfile['type'],
            'id' => $this->activeProfile['id'],
            'name' => $this->activeProfile['name'],
            'photo' => $this->activeProfile['photo']
        ];
    }


    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('switch-profile.' . $this->activeProfile['userId']);
    }
}
