<?php declare(strict_types=1);

namespace App\Events;

use App\Helpers\Helpers;
use App\Models\CaptchaLog;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

final class CreatedCaptchaLog implements ShouldBroadcast
{
    use SerializesModels, Dispatchable;

    public array $chartCaptchaActivity = [];
    public array $captchaLog = [];

    public function __construct(CaptchaLog $captchaLog) {
        $this->chartCaptchaActivity = [
            'date' => $captchaLog->created_at->format('Y-m-d'),
            'meta' => $captchaLog->type->getTitle(),
            'type' => $captchaLog->type->value,
        ];
        $link = '';
        $title = '';
        if ($captchaLog->captcha && $captchaLog->captcha->captchaToken) {
            $link = route('captcha-tokens.edit', ['captcha_token' => $captchaLog->captcha->captcha_token_id], false);
            $title = $captchaLog->captcha->captchaToken->title;
        }

        $ip = $captchaLog->ip;
        $userAgent = $captchaLog->user_agent;
        if (Helpers::isDemoMode()) {
            $ip = __('Demo Mode');
            $userAgent = __('Demo Mode');
        }

        $this->captchaLog = [
            'created_at' => $captchaLog->created_at->format("d.m.Y H:i:s"),
            'link'       => $link,
            'title'      => $title,
            'type'       => $captchaLog->type->getTitle(),
            'ip'         => $ip,
            'user_agent' => $userAgent,
            'referer'    => $captchaLog->referer,
        ];
    }

    public function broadcastOn(): Channel
    {
        return new PrivateChannel('chart-captcha-activity');
    }
}
