<?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\WithAuthorization;
use App\Traits\WithCloseModal;
use App\Traits\WithConfirmation;
use App\Traits\WithRoleSelector;
use App\Traits\WithToast;
use App\Traits\WithUpdatedData;
use Flux\Flux;
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()
    {
        $this->roles = Role::where('name', '!=', 'Developer')->orderBy('id')->pluck('name', 'id')->toArray();
    }

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

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

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

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

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

        $userIds = User::role(array_map('intval', $result['data']['audience_ids']))->pluck('id')->toArray();
        StorePushNotification::dispatch(
            PushNotification::whereIn('user_id', $userIds)->get(),
            [
                'title' => $result['data']['title'],
                'body' => $result['data']['body'],
            ],
        );

        $this->dispatch('refreshDatatable');

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

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

    public function update()
    {
        $this->canOrAbort('update broadcast');

        $this->form->update();

        $this->dispatch('refreshDatatable');

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

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

    public function delete(BroadcastModel $broadcast)
    {
        $broadcast->delete();

        $this->dispatch('refreshDatatable');

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

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

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