<?php

namespace App\Filament\Admin\Resources\OrderProducts\Pages;

use App\Filament\Admin\Resources\OrderProducts\OrderProductResource;
use Filament\Resources\Pages\CreateRecord;
   use Filament\Support\Exceptions\Halt;
use Filament\Notifications\Notification;
class CreateOrderProduct extends CreateRecord
{
    protected static string $resource = OrderProductResource::class;


protected function mutateFormDataBeforeCreate(array $data): array
{
    if ($data['pm_type'] === 'wallet') {

        $user = \App\Models\User::find($data['user_id']);

        if (! $user?->wallet) {
            Notification::make()
                ->title('User does not have a wallet.')
                ->danger()
                ->send();

            throw new Halt();
        }

        $walletBalance = $user->wallet->balance;
        $orderPrice = $data['total_price'];

        if ($walletBalance < $orderPrice) {
            Notification::make()
                ->title('Insufficient wallet balance')
                ->body('Available balance: ' . $walletBalance)
                ->danger()
                ->send();

            throw new Halt();
        }
    }

    return $data;
}

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

    if ($record->pm_type === 'wallet') {
        $wallet = $record->user->wallet;

        $wallet->decrement('balance', $record->total_price);
    }
}

}
