<?php

namespace TomatoPHP\FilamentBookmarksMenu\Filament\Tables;

use Filament\Forms\Components\Select;
use Filament\Notifications\Notification;
use Filament\Tables\Actions\BulkAction;
use TomatoPHP\FilamentBookmarksMenu\Models\Bookmark;
use TomatoPHP\FilamentBookmarksMenu\Models\BookmarkLink;
use TomatoPHP\FilamentBookmarksMenu\Traits\HasPage;
use TomatoPHP\FilamentBookmarksMenu\Traits\HasTypes;

class BookmarkBulkAction extends BulkAction
{
    use HasPage;
    use HasTypes;

    protected function setUp(): void
    {
        parent::setUp(); // TODO: Change the autogenerated stub

        $this->name('bulk_bookmark');
        $this->requiresConfirmation();
        $this->label(trans('filament-bookmarks-menu::messages.actions.bulk.add'));
        $this->modalHeading(trans('filament-bookmarks-menu::messages.actions.bulk.modal.add'));
        $this->form(fn() => $this->types());
        $this->color('success');
        $this->deselectRecordsAfterCompletion();
        $this->icon('heroicon-s-bookmark');
        $this->action(function (array $data, $records) {
            $records->each(function ($record) use ($data){
                $resource = app($this->getLivewire()::getResource());

                $checkExists = BookmarkLink::query()->where('url', $resource::getUrl($this->getPage(),['record' => $record]))->first();
                if(!$checkExists){
                    $bookmarkLink = BookmarkLink::create([
                        'name' => $record ? ($record->{$resource->getRecordTitleAttribute()} ?: ($record->name?: ($record->title ?: $this->getLivewire()->getTitle()))) : $this->getLivewire()->getTitle(),
                        'url' => $resource::getUrl($this->getPage(),['record' => $record]),
                        'icon' => $resource::getNavigationIcon() ?: 'heroicon-s-bookmark',
                        'color' => 'primary',
                    ]);

                    $bookmarkLink->bookmarks()->attach($data['bookmark_id']);
                }
            });

            Notification::make()
                ->title(trans('filament-bookmarks-menu::messages.actions.page.notification.add.title'))
                ->body(trans('filament-bookmarks-menu::messages.actions.page.notification.add.body'))
                ->success()
                ->send();

            return redirect()->back();
        });
    }
}
