<?php

/**
 * ============================================================
 *
 * @project   biiproject
 *
 * @author    Andika Debi Putra
 *
 * @email     andikadebiputra@gmail.com
 *
 * @website   https://biiproject.com
 *
 * @copyright Copyright (c) 2026 Andika Debi Putra
 * @license   Proprietary - All Rights Reserved
 *
 * @version   1.0.0
 *
 * @created   2026-05-01
 * ============================================================
 */

namespace App\Events;

use App\Services\System\ActivityFormatter;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Spatie\Activitylog\Models\Activity;

class ActivityLogCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $log;

    /**
     * Create a new event instance.
     */
    public function __construct(Activity $activity)
    {
        // Format the activity for the dashboard table
        $this->log = [
            'time' => $activity->created_at->diffForHumans(),
            'datetime' => $activity->created_at->format('Y-m-d H:i:s'),
            'level' => $this->getLevel($activity->description),
            'manifest' => ActivityFormatter::getFriendlyModelName($activity->subject_type),
            'description' => ucfirst($activity->description),
            'causer' => $activity->causer ? $activity->causer->name : 'System',
        ];
    }

    private function getLevel(string $description): string
    {
        if (str_contains($description, 'deleted') || str_contains($description, 'failed')) {
            return '<span class="badge text-bg-danger rounded-pill">CRIT</span>';
        }
        if (str_contains($description, 'updated')) {
            return '<span class="badge text-bg-warning rounded-pill">MODI</span>';
        }

        return '<span class="badge text-bg-success rounded-pill">INFO</span>';
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new PrivateChannel('admin.monitoring'),
        ];
    }

    /**
     * The event's broadcast name.
     */
    public function broadcastAs(): string
    {
        return 'activity.created';
    }
}
