<?php

namespace App\Filament\Resources\RfqTransporterBidResource\Pages;

use App\Filament\Resources\RfqTransporterBidResource;
use App\Models\RequestQuotation;
use App\Models\RfqTransporterBid;
use App\Models\SpotRateTransportMaster;
use App\Models\User;
use App\Notifications\PushAlertNotification;
use Filament\Actions;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Facades\Log;

class EditRfqTransporterBid extends EditRecord
{
    protected static string $resource = RfqTransporterBidResource::class;

    protected function afterSave(): void
    {
        if (! $this->record->wasChanged('total_freight_charge')) {
            return;
        }

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

        $requestQuotation = RequestQuotation::findOrFail(
            $this->record->request_quotation_id
        );

        $spotRateId = $requestQuotation->spot_rate_transport_master_id;

        $spotRate = SpotRateTransportMaster::findOrFail($spotRateId);

        $userNames = $spotRate->user_name;

        Log::info('User names from spot rate', [
            'user_name_raw' => $spotRate->user_name,
        ]);

        if (!is_array($userNames)) {
            Log::warning('user_name is not array, resetting', [
                'user_name' => $userNames,
            ]);
            $userNames = [];
        }


        $users = User::whereIn('name', $userNames)->get();

        Log::info('Matched users', [
            'count' => $users->count(),
            'user_ids' => $users->pluck('id'),
        ]);

        // $recipients = User::role(['Super Admin', 'Rfq Supervisor', 'TransporterBid Employee'])->get();

        // $recipients1 = User::role(['Super Admin', 'Rfq Supervisor', 'TransporterBid Employee'])->whereHas('pushSubscriptions')->get();

        $currentUser = Filament::auth()->user();

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

        // 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} current rank is #{$rank}")
        //     ->success()
        //     ->sendToDatabase($recipients);

        //     \Log::info('Notification sent', [
        //     'rank' => $rank,
        //     'recipients' => $recipients->pluck('id'),
        // ]);

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

        // foreach ($recipients1 as $user) {
        //     $user->notify(
        //         new PushAlertNotification(
        //             'Rank Updated',
        //             $body
        //         )
        //     );
        // }

        // foreach ($users as $user) {

        // Log::info('Checking push subscription for user', [
        //     'user_id' => $user->id,
        //     'name' => $user->name,
        //     'subscription_count' => $user->pushSubscriptions()->count(),
        // ]);
        //     if ($user->pushSubscriptions()->exists()) {

        //         Log::info('Sending push notification', [
        //             'user_id' => $user->id,
        //         ]);
        //         $user->notify(
        //             new PushAlertNotification(
        //                 'Rank Updated',
        //                 $body
        //             )
        //         );
        //     }
        //     else {
        //         Log::warning('User has NO push subscription', [
        //             'user_id' => $user->id,
        //         ]);
        //     }
        // }


            foreach ($users as $user) {

                $count = $user->pushSubscriptions()->count();

                Log::info('Checking push subscription for user', [
                    'user_id' => $user->id,
                    'name' => $user->name,
                    'subscription_count' => $count,
                ]);

                if ($count == 0) {
                    Log::warning('User has NO push subscription', [
                        'user_id' => $user->id,
                    ]);
                    continue;
                }

                Log::info('Sending push notification', [
                    'user_id' => $user->id,
                ]);

                // ✅ THIS IS ALL YOU NEED
                $user->notify(new PushAlertNotification(
                    'Rank Updated',
                    $body
                ));
            }



    }

    protected function getHeaderActions(): array
    {
        return [
            Actions\ViewAction::make(),
            Actions\DeleteAction::make(),
            Actions\ForceDeleteAction::make(),
            Actions\RestoreAction::make(),
        ];
    }
}
