<?php

namespace App\Filament\Resources\RfqTransporterBidResource\Pages;

use App\Filament\Resources\RfqTransporterBidResource;
use App\Models\RfqTransporterBid;
use App\Models\User;
use App\Notifications\PushAlertNotification;
use Filament\Actions;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;

class CreateRfqTransporterBid extends CreateRecord
{
    protected static string $resource = RfqTransporterBidResource::class;


    protected function afterCreate(): void
    {
        $record = $this->record;

        // Calculate rank based on total_freight_charge
        $rank = RfqTransporterBid::where('request_quotation_id', $this->record->request_quotation_id)
            ->orderBy('total_freight_charge')
            ->pluck('id')
            ->search($this->record->id) + 1;

        $recipients = User::role(['Super Admin', 'Rfq Supervisor'])->get();
        $currentUser = Filament::auth()->user();


        if ($currentUser && ! $recipients->contains('id', $currentUser->id)) {
            $recipients->push($currentUser);
        }

        // $user1 = Filament::auth()->user();

        $rfqNumber = $this->record->requestQuotation->rfq_number;
        $body = "{$currentUser->name} has updated the bid for RFQ No '{$rfqNumber}'. The current rank is #{$rank}.";

        Notification::make()
            ->title('Rank Updated')
            ->body("{$currentUser->name} has updated the bid for RFQ No '{$rfqNumber}'. The current rank is #{$rank}.")
            ->success()
            ->sendToDatabase($recipients);

        // Push notification
        foreach ($recipients as $user) {
            $user->notify(
                new PushAlertNotification(
                    'New Bid Added',
                    $body
                )
            );
        }

        \Log::info('Create bid notification sent', [
            'bid_id' => $record->id,
            'rank' => $rank,
            'recipients' => $recipients->pluck('id'),
        ]);
    }
}
