<?php

namespace App\Services\Finance\Gateways;

use App\Contracts\Finance\PaymentGatewayDriver;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\PaymentAllocation;
use App\Models\User;
use App\Services\Accounting\AccountLookupService;
use App\Services\Finance\DocumentNumberService;
use Illuminate\Support\Facades\DB;

class ManualGateway implements PaymentGatewayDriver
{
    public function key(): string
    {
        return 'manual';
    }

    public function initiate(Invoice $invoice, User $payer, float $amount, array $context = []): array
    {
        $method = $context['payment_method'] ?? 'manual';

        $payment = DB::transaction(function () use ($invoice, $payer, $amount, $method, $context) {
            $payment = Payment::query()->create([
                'payment_number' => app(DocumentNumberService::class)->next('PAY', Payment::class, 'payment_number'),
                'payee_name' => $invoice->student?->full_name,
                'amount' => number_format($amount, 2, '.', ''),
                'payment_date' => now()->toDateString(),
                'payment_method' => $method,
                'account_id' => app(AccountLookupService::class)->configured('cash')->id,
                'status' => 'pending',
                'gateway' => 'manual',
                'gateway_status' => 'awaiting_confirmation',
                'reference' => $context['reference'] ?? null,
                'recorded_by' => $payer->id,
                'notes' => $context['notes'] ?? 'Payment request via parent portal',
            ]);

            PaymentAllocation::query()->create([
                'payment_id' => $payment->id,
                'invoice_id' => $invoice->id,
                'allocated_amount' => $payment->amount,
            ]);

            return $payment;
        });

        return [
            'payment' => $payment,
            'redirect_url' => null,
            'view' => null,
            'view_data' => [],
            'message' => 'Payment request submitted. Finance will review and confirm.',
        ];
    }

    public function verify(Payment $payment): bool
    {
        return false;
    }
}
