<?php

namespace App\Http\Controllers;

use App\Models\ManualFunding;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class WalletController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user()->load('wallet');

        return response()->json([
            'balance' => $user->wallet->balance,
        ]);
    }

    public function initiatePaystack(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:100',
        ]);

        $user      = $request->user();
        $reference = 'FT-' . strtoupper(Str::random(12));
        $amount    = (int) $request->amount;

        // Create pending transaction so the webhook can find & credit it
        Transaction::create([
            'user_id'   => $user->id,
            'type'      => 'wallet_fund',
            'amount'    => $amount,
            'reference' => $reference,
            'status'    => 'pending',
            'details'   => ['method' => 'paystack'],
        ]);

        return response()->json([
            'reference'  => $reference,
            'amount'     => $amount * 100, // Paystack uses kobo
            'email'      => $user->email,
            'public_key' => config('services.paystack.public_key'),
        ]);
    }

    // Called by frontend after Paystack popup succeeds — verifies with Paystack directly
    public function verifyPaystack(Request $request)
    {
        $request->validate(['reference' => 'required|string']);

        $reference = $request->reference;
        $secretKey = config('services.paystack.secret_key');

        // Ask Paystack if this payment really succeeded
        $response = \Illuminate\Support\Facades\Http::withToken($secretKey)
            ->get("https://api.paystack.co/transaction/verify/{$reference}");

        $result = $response->json();

        if (!($result['status'] ?? false) || ($result['data']['status'] ?? '') !== 'success') {
            return response()->json(['message' => 'Payment not confirmed'], 400);
        }

        $transaction = Transaction::where('reference', $reference)
            ->where('status', 'pending')
            ->first();

        if (!$transaction) {
            // Already processed (likely by webhook) or not found
            return response()->json(['message' => 'Already processed or not found']);
        }

        $amount = $result['data']['amount'] / 100; // kobo to naira
        $user   = $transaction->user;
        $user->wallet->increment('balance', $amount);

        $transaction->update([
            'status'       => 'success',
            'api_response' => $result['data'],
        ]);

        \App\Models\Notification::create([
            'user_id' => $user->id,
            'title'   => 'Wallet Funded',
            'message' => "₦" . number_format($amount, 2) . " has been added to your wallet.",
        ]);

        return response()->json([
            'message'     => 'Wallet funded successfully',
            'new_balance' => $user->wallet->fresh()->balance,
        ]);
    }

    public function manualFunding(Request $request)
    {
        $request->validate([
            'amount'      => 'required|numeric|min:100',
            'proof_image' => 'required|image|max:2048',
        ]);

        $path = $request->file('proof_image')->store('proofs', 'public');

        ManualFunding::create([
            'user_id'     => $request->user()->id,
            'amount'      => $request->amount,
            'proof_image' => $path,
            'status'      => 'pending',
        ]);

        return response()->json([
            'message' => 'Payment proof submitted. Your wallet will be credited after review.',
        ]);
    }
}