<?php

namespace Daylight\Core\Livewire\Tables\Concerns;

use Livewire\Attributes\Computed;

trait WithBulkActions
{
    public bool $bulkActions = true;

    public ?string $bulkAction = null;

    public ?string $confirmingBulkAction = null;

    public function updatedBulkAction(): void
    {
        if (is_null($this->bulkAction)) {
            return;
        }

        if (! in_array($this->bulkAction, array_keys($this->availableBulkActions()))) {
            $this->reset('bulkAction');

            return;
        }

        $action = $this->availableBulkActions()[$this->bulkAction];

        if (! empty($action['confirm'])) {
            $this->confirmingBulkAction = $this->bulkAction;

            return;
        }

        $this->{$action['action']}();
        $this->reset('bulkAction');
    }

    public function confirmBulkAction(): void
    {
        if (is_null($this->confirmingBulkAction)) {
            return;
        }

        $action = $this->availableBulkActions()[$this->confirmingBulkAction];
        $this->{$action['action']}();
        $this->confirmingBulkAction = null;
        $this->reset('bulkAction');
    }

    public function cancelBulkAction(): void
    {
        $this->confirmingBulkAction = null;
        $this->reset('bulkAction');
    }

    public function bulkDelete(): void
    {
        $this->getBaseQuery()
            ->getModel()::whereIn('id', $this->selectedIds)
            ->get()
            ->each
            ->delete();

        $this->selectedIds = [];

        session()->flash('success', __('daylight::general.bulk_deleted'));
    }

    public function bulkStatusChange(int $status): void
    {
        $this->getBaseQuery()
            ->getModel()::whereIn('id', $this->selectedIds)
            ->update(['status' => $status]);

        $this->selectedIds = [];

        session()->flash('success', __('daylight::general.status_updated'));
    }

    #[Computed]
    abstract protected function availableBulkActions(): array;
}
