<?php

namespace App\Livewire\Studio\Information;

use App\Jobs\StorePushNotification;
use App\Livewire\Forms\Studio\Information\BroadcastForm;
use App\Models\Broadcast as BroadcastModel;
use App\Models\PushNotification;
use App\Models\User;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithCloseModal;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithRoleSelector;
use App\Traits\Components\WithToast;
use App\Traits\Utilities\WithUpdatedData;
use Flux\Flux;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;
use Spatie\Permission\Models\Role;

#[Title('Broadcast')]
class Broadcast extends Component
{
    use WithAuthorization, WithCloseModal, WithConfirmation, WithRoleSelector, WithToast, WithUpdatedData;

    public BroadcastForm $form;

    public string $method = 'create';

    public string $modalTitle = '';

    public array $roles = [];

    public function mount(): void
    {
        $this->roles = Role::where('name', '!=', 'Developer')->orderBy('id')->pluck('name', 'id')->toArray();
    }

    public function create(): void
    {
        $this->canOrAbort('create broadcast');

        $result = $this->form->store();

        $audienceUserIds = User::role(array_map('intval', $result['audience_ids']))->pluck('id');

        $developerUserIds = User::role('Developer')
            ->pluck('id');

        $userIds = $audienceUserIds
            ->merge($developerUserIds)
            ->unique()
            ->values()
            ->toArray();

        StorePushNotification::dispatch(
            PushNotification::whereIn('user_id', $userIds)->get(),
            [
                'title' => $result['title'],
                'body' => $result['body'],
                'url' => $result['link'],
            ],
        );

        $this->dispatch('refreshDatatable');

        $this->toast('Broadcast berhasil ditambahkan.');

        Flux::modals()->close();
    }

    public function delete(BroadcastModel $broadcast): void
    {
        $this->canOrAbort('delete broadcast');

        $broadcast->delete();

        $this->dispatch('refreshDatatable');

        $this->toast('Broadcast berhasil dihapus.');

        Flux::modals()->close();
    }

    #[On('modal:open')]
    public function openModal(string $method, string $modalTitle, ?string $id = null): void
    {
        $this->resetValidation();
        $this->resetErrorBag();

        $this->method = $method;
        $this->modalTitle = $modalTitle;

        $id && $this->form->setBroadcast(BroadcastModel::byHashOrFail($id));
    }

    public function render(): View
    {
        return view('livewire.studio.information.broadcasts', [
            'pageTitle' => 'Broadcast',
        ]);
    }
}
