<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PaymentTransaction;
use App\Models\UpiTransaction;
use App\Services\AdminActivityLogger;
use App\Services\PaymentVerificationService;
use App\Services\UPIVerificationService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class UpiController extends Controller
{
    public function index(Request $request): View
    {
        $status = $request->query('status', 'pending');
        $query = UpiTransaction::query()->with('user')->latest();

        if ($status) {
            $query->where('verification_status', $status);
        }

        return view('admin.upi', [
            'records' => $query->paginate(20),
            'status' => $status,
        ]);
    }

    public function approve(
        UpiTransaction $upi,
        PaymentVerificationService $paymentVerificationService,
        AdminActivityLogger $logger
    ): RedirectResponse {
        if ($upi->verification_status === 'verified') {
            return back()->with('status', 'UPI already verified.');
        }

        $tolerance = (float) setting('upi_amount_tolerance', 2);
        $minAmount = max(0, (float) $upi->amount - $tolerance);
        $maxAmount = (float) $upi->amount + $tolerance;

        $payment = PaymentTransaction::query()
            ->where('status', 'pending')
            ->whereBetween('amount', [$minAmount, $maxAmount])
            ->where(function ($query) use ($upi) {
                $query
                    ->where('merchant_order_ref', 'like', '%'.$upi->utr.'%')
                    ->orWhere('gateway_transaction_id', $upi->utr);
            })
            ->latest('id')
            ->first();

        if ($payment) {
            $upi->payment_transaction_id = $payment->id;
        }

        $upi->verification_status = 'verified';
        $upi->verified_by = auth()->id();
        $upi->verified_at = now();
        $upi->save();

        if ($payment) {
            $paymentVerificationService->markPaymentSuccess($payment, ['source' => 'manual_upi']);
        }

        $logger->log('upi.approve', UpiTransaction::class, $upi->id);

        return back()->with('status', 'UPI marked as verified.');
    }

    public function reject(
        Request $request,
        UpiTransaction $upi,
        AdminActivityLogger $logger,
        UPIVerificationService $upiService
    ): RedirectResponse
    {
        if ($upi->verification_status === 'verified') {
            return back()->with('status', 'UPI already verified.');
        }

        $upi->attempts = min(255, $upi->attempts + 1);
        $upi->fraud_attempt_count = min(65535, (int) $upi->fraud_attempt_count + 1);
        $upi->verification_status = $upi->attempts >= 5 ? 'locked' : 'rejected';
        $upi->verified_by = auth()->id();
        $upi->verified_at = now();
        $upi->save();

        $upiService->lockUserIfThreshold($upi->user_id);

        $logger->log('upi.reject', UpiTransaction::class, $upi->id);

        return back()->with('status', 'UPI marked as rejected.');
    }
}
