<?php

namespace App\Http\Controllers\Api\V1\Showroom;

use App\Http\Controllers\Controller;
use App\Models\PaymentTransaction;
use App\Services\Payments\BanglaQrPaymentService;
use Illuminate\Http\Request;

class BanglaQrController extends Controller
{
    public function __construct(private readonly BanglaQrPaymentService $paymentService)
    {
    }

    public function initiate(Request $request)
    {
        $data = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'source_reference' => 'nullable|string|max:120',
        ]);
        $admin = $request->attributes->get('showroom_admin');

        $transaction = $this->paymentService->initiate([
            'source_type' => 'showroom_pos',
            'source_reference' => $data['source_reference'] ?? 'POS-PENDING-' . now()->format('YmdHis'),
            'amount' => $data['amount'],
            'created_by_admin_id' => $admin?->id,
        ]);

        return response()->json($transaction);
    }

    public function status(PaymentTransaction $paymentTransaction)
    {
        return response()->json($this->paymentService->status($paymentTransaction));
    }

    public function manualVerification(Request $request)
    {
        $data = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'submitted_transaction_id' => 'required|string|max:160',
            'source_reference' => 'nullable|string|max:120',
            'qr_reference' => 'nullable|string|max:160',
            'note' => 'nullable|string|max:500',
            'evidence_payload' => 'nullable|array',
        ]);
        $admin = $request->attributes->get('showroom_admin');

        $verification = $this->paymentService->submitManualVerification([
            'source_type' => 'showroom_pos_static_qr',
            'source_reference' => $data['source_reference'] ?? 'POS-STATIC-' . now()->format('YmdHis'),
            'amount' => $data['amount'],
            'submitted_transaction_id' => $data['submitted_transaction_id'],
            'qr_reference' => $data['qr_reference'] ?? null,
            'note' => $data['note'] ?? null,
            'evidence_payload' => $data['evidence_payload'] ?? [],
        ], $admin?->id);

        return response()->json([
            'message' => translate('Bangla QR manual verification request has been queued. Invoice can be completed after approval.'),
            'manual_verification' => $verification,
            'payment_transaction' => PaymentTransaction::find($verification->payment_transaction_id),
        ], 201);
    }
}
