<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\UpiTransaction;
use App\Services\UPIVerificationService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;

class UpiController extends Controller
{
    public function index(): View
    {
        $transactions = UpiTransaction::query()
            ->where('user_id', auth()->id())
            ->latest('id')
            ->paginate(15);

        return view('user.upi', compact('transactions'));
    }

    public function store(Request $request, UPIVerificationService $upiService): RedirectResponse
    {
        $user = auth()->user();
        if ($user && $user->upi_locked_at) {
            return back()->withErrors(['utr' => 'UPI submissions are locked. Please contact support.']);
        }

        $validated = $request->validate([
            'utr' => ['required', 'string', 'min:12', 'max:30'],
            'amount' => ['required', 'numeric', 'min:1'],
            'bank_name' => ['nullable', 'string', 'max:191'],
            'remark' => ['nullable', 'string', 'max:191'],
            'screenshot' => ['required', 'image', 'max:4096'],
        ]);

        $path = $request->file('screenshot')->store('upi/screenshots', 'public');
        $fullPath = storage_path('app/public/'.$path);

        $manager = new ImageManager(new Driver());
        $image = $manager->read($fullPath);
        $watermark = sprintf(
            '%s | %s | USER:%d',
            (string) setting('company_name', 'AKRSera MLM'),
            now()->format('Y-m-d H:i'),
            auth()->id()
        );
        $image->text($watermark, 20, 30);
        $image->save($fullPath);

        $upiService->submitUTR(auth()->id(), [
            'utr' => $validated['utr'],
            'amount' => $validated['amount'],
            'bank_name' => $validated['bank_name'] ?? null,
            'remark' => $validated['remark'] ?? null,
            'screenshot_path' => $path,
            'device_info' => $request->userAgent(),
        ]);

        return back()->with('status', 'UPI submission recorded for verification.');
    }
}
