<?php

namespace App\Filament\Resources\TransactionResource\Pages;

use App\Filament\Resources\TransactionResource;
use App\Models\Sales\Transaction;
use App\Services\CurrentContext;
use App\Services\PaymentService;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Validation\ValidationException;
use RuntimeException;

/**
 * Ported from TransactionController::store(): a standalone payment recorded
 * against a customer, optionally allocated across their unpaid invoices, with
 * the branch defaulting to the current branch context. Delegates to
 * PaymentService::createAllocatedTransaction() which owns numbering, status,
 * credit-note-on-overpayment, and invoice recomputation.
 */
class CreateTransaction extends CreateRecord
{
    protected static string $resource = TransactionResource::class;

    protected function handleRecordCreation(array $data): Transaction
    {
        $context = app(CurrentContext::class);

        if (! empty($data['branch_id'])) {
            abort_unless(
                $context->canAccessBranch((int) $data['branch_id']),
                403,
                'You do not have access to this branch.',
            );
        }

        $branchId = $data['branch_id']
            ?? $context->branchId()
            ?? $context->branches()->first()?->id;

        $allocations = collect($data['invoice_allocations'] ?? [])
            ->map(fn (array $a) => [
                'invoice_id' => (int) $a['invoice_id'],
                'amount' => round((float) $a['amount'], 2),
            ])
            ->filter(fn (array $a) => $a['amount'] > 0)
            ->values()
            ->all();

        try {
            return app(PaymentService::class)->createAllocatedTransaction(
                data: [
                    'customer_id' => (int) $data['customer_id'],
                    'branch_id' => $branchId ? (int) $branchId : null,
                    'payment_method_id' => (int) $data['payment_method_id'],
                    'amount' => (float) $data['amount'],
                    'reference' => $data['reference'] ?? null,
                    'note' => $data['note'] ?? null,
                    'taken_on' => $data['taken_on'] ?? null,
                    'cheque_number' => $data['cheque_number'] ?? null,
                    'cheque_bank' => $data['cheque_bank'] ?? null,
                    'cheque_date' => $data['cheque_date'] ?? null,
                ],
                allocations: $allocations,
            );
        } catch (RuntimeException $e) {
            throw ValidationException::withMessages(['data.amount' => $e->getMessage()]);
        }
    }

    protected function getRedirectUrl(): string
    {
        return TransactionResource::getUrl('view', ['record' => $this->record]);
    }
}
