<?php

namespace App\Filament\Resources\Payments\Pages;

use App\Filament\Resources\Payments\PaymentResource;
use App\Models\Invoice;
use App\Models\Payment;
use App\Services\InvoiceService;
use Filament\Resources\Pages\CreateRecord;

class CreatePayment extends CreateRecord
{
    protected static string $resource = PaymentResource::class;

    // ── Pre-fill form when arriving from "Record Payment" on an invoice row ──

    public function mount(): void
    {
        parent::mount();

        $consignmentId = (int) request()->query('consignment_id');
        if (! $consignmentId) return;

        $invoice = Invoice::where('consignment_id', $consignmentId)
            ->select([
                'id', 'invoice_number', 'amount_kes', 'amount_usd',
                'amount_paid_kes', 'outstanding_kes', 'payment_status',
            ])
            ->first();

        if (! $invoice || $invoice->payment_status === 'paid') return;

        $this->form->fill([
            'consignment_id' => $consignmentId,
            'invoice_id'     => $invoice->id,
            '_inv_no'        => $invoice->invoice_number,
            '_total'         => 'KES ' . number_format($invoice->amount_kes, 2),
            '_usd'           => $invoice->amount_usd > 0
                                    ? '$ ' . number_format($invoice->amount_usd, 2)
                                    : '—',
            '_paid'          => 'KES ' . number_format($invoice->amount_paid_kes, 2),
            '_outstanding'   => 'KES ' . number_format($invoice->outstanding_kes, 2),
            '_status'        => ucfirst($invoice->payment_status),
            'amount_kes'     => $invoice->outstanding_kes,
        ]);
    }

    // ── Inject system fields before DB insert ─────────────────────────────

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $data['receipt_number'] = $this->nextReceiptNumber();
        $data['cashier_id']     = auth()->id();

        // Strip the placeholder display-only fields so they don't hit the DB
        unset($data['_inv_no'], $data['_total'], $data['_usd'],
              $data['_paid'], $data['_outstanding'], $data['_status']);

        return $data;
    }

    // ── Update invoice balance + redirect to receipt print ────────────────

    protected function afterCreate(): void
    {
        $invoice = Invoice::find($this->record->invoice_id);
        if ($invoice) {
            app(InvoiceService::class)->recalculateInvoiceBalance($invoice);
        }
    }

    protected function getRedirectUrl(): string
    {
        return route('documents.print', ['receipt', $this->record->id]);
    }

    // ── Sequential receipt number generator ───────────────────────────────

    private function nextReceiptNumber(): string
    {
        $last = Payment::orderByDesc('id')->value('receipt_number');
        $next = $last
            ? (int) substr($last, strrpos($last, '-') + 1) + 1
            : 1;

        return 'RCP-' . date('Y') . '-' . str_pad($next, 5, '0', STR_PAD_LEFT);
    }
}
