<?php

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

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

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

        $this->label('Lanjutkan ke Pembayaran')
            ->icon(Heroicon::Banknotes)
            ->color('success')
            ->requiresConfirmation()
            ->modalHeading('Lanjutkan ke Pembayaran?')
            ->modalDescription('Apakah Anda yakin ingin melanjutkan kerja sama ini ke tahap pembayaran? Pastikan semua laporan telah diverifikasi.')
            ->action(function (Cooperation $record): void {
                $record->update([
                    'status' => CooperationStatus::PAYMENT,
                    'payment_date' => now()->toDateString(),
                ]);

                CheerfulNotification::success(
                    'Tahap Pembayaran Dimulai! 💸✨',
                    'Kerja sama telah dipindahkan ke tahap pembayaran. Silakan proses pembayarannya ya! 😊'
                )->send();
            })
            ->visible(function (Cooperation $record): bool {
                $user = auth()->user();

                if (! $user || $user->hasRole(RoleEnum::PERUSAHAAN->value) || $record->status !== CooperationStatus::VERIFICATION) {
                    return false;
                }

                // Check if all reports are verified (either Accepted or Rejected, not Pending)
                $reports = $record->reports;

                if ($reports->isEmpty()) {
                    return true;
                }

                return $reports->every(fn ($report) => $report->status !== ApprovalStatus::PENDING);
            });
    }
}
