<?php

namespace App\Filament\Resources\Manage\Cooperations\Actions\Cooperation;

use App\Enums\ApprovalStatus;
use App\Enums\RoleEnum;
use App\Filament\Support\CheerfulNotification;
use App\Models\Cooperation;
use App\Models\User;
use App\Notifications\BroadcastNotification;
use Filament\Actions\Action;
use Filament\Support\Icons\Heroicon;

class RejectAction extends Action
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Tolak')
            ->icon(Heroicon::XMark)
            ->color('danger')
            ->action(function (Cooperation $record): void {
                $cooperationMedia = $record->cooperationMedia()
                    ->whereHas('partnerMedia', function ($query) {
                        $query->whereHas('company', function ($subQuery) {
                            $subQuery->where('user_id', auth()->id());
                        });
                    })
                    ->first();

                if ($cooperationMedia) {
                    $cooperationMedia->update(['status' => ApprovalStatus::REJECTED]);

                    CheerfulNotification::info(
                        'Berhasil Ditolak 🙏',
                        'Terima kasih atas konfirmasinya. Pesan penolakan telah diteruskan ke Admin. 😊'
                    )->send();

                    // Notify Admins
                    User::superAdmin()
                        ->get()
                        ->each(function ($admin) use ($record, $cooperationMedia): void {
                            $admin->notify(new BroadcastNotification([
                                'title' => 'Yah, Tawaran Ditolak 😔🤝',
                                'body' => "Media {$cooperationMedia->partnerMedia->name} baru saja menolak penawaran kerja sama \"{$record->title}\". Mungkin di lain waktu ya! 🙏",
                            ]));
                        });
                }
            })
            ->visible(function (Cooperation $record): bool {
                $user = auth()->user();

                if (! $user || ! $user->hasRole(RoleEnum::PERUSAHAAN->value)) {
                    return false;
                }

                $cooperationMedia = $record->cooperationMedia()
                    ->whereHas('partnerMedia', function ($query) {
                        $query->whereHas('company', function ($subQuery) {
                            $subQuery->where('user_id', auth()->id());
                        });
                    })
                    ->first();

                return $cooperationMedia && $cooperationMedia->status === ApprovalStatus::PENDING;
            });
    }
}
