<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Wallet;
use App\Models\Transaction;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use DB;

class WalletController extends Controller
{
    /**
     * Get current user's wallet balance.
     */
    public function getBalance(Request $request)
    {
        $user = $request->user();
        $wallet = $user->wallet ?: Wallet::create(['user_id' => $user->id, 'balance' => 0.00]);

        return response()->json([
            'success' => true,
            'balance' => (float)$wallet->balance,
            'currency' => $wallet->currency
        ]);
    }

    /**
     * Initialize wallet funding (Paystack integration mock).
     */
    public function initializeFund(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:100', // min 100 in units
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        $user = $request->user();
        // Generate a unique reference for Paystack
        $reference = 'MD-' . Str::random(10);

        // Note: In real production, you'd call Paystack API here to get an auth_url
        // For development, we return a mock URL and the reference.
        
        return response()->json([
            'success' => true,
            'message' => 'Transaction initialized.',
            'reference' => $reference,
            'authorization_url' => 'https://checkout.paystack.com/mock-checkout-' . $reference,
            'amount' => $request->amount,
            'email' => $user->email ?? $user->phone . '@metrodrop.com'
        ]);
    }

    /**
     * Verify wallet funding.
     */
    public function verifyFund(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'reference' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        // Mock verification logic - in reality, you'd call Paystack's verification API.
        $user = $request->user();
        $reference = $request->reference;
        
        // Assume verified for now - we take amount from the 'initialized' request or real API response.
        // For this mock, we'll allow amount to be passed or use a default.
        $amount = $request->amount ?? 1000; // default for mock if not provided

        return \Illuminate\Support\Facades\DB::transaction(function () use ($user, $amount, $reference) {
            $wallet = $user->wallet ?: Wallet::create(['user_id' => $user->id, 'balance' => 0.00]);
            
            // Prevent duplicate transaction entry if reference exists
            $exists = Transaction::where('reference', $reference)->exists();
            if ($exists) {
                return response()->json(['success' => false, 'message' => 'Transaction already processed.'], 400);
            }

            // Update balance
            $wallet->increment('balance', $amount);

            // Record transaction
            Transaction::create([
                'user_id' => $user->id,
                'type' => 'credit',
                'amount' => $amount,
                'status' => 'completed',
                'description' => 'Wallet Funding via Paystack',
                'reference' => $reference
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Wallet funded successfully.',
                'balance' => (float)$wallet->balance
            ]);
        });
    }

    /**
     * Get transaction history.
     */
    public function getTransactions(Request $request)
    {
        $transactions = Transaction::where('user_id', $request->user()->id)
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return response()->json([
            'success' => true,
            'transactions' => $transactions
        ]);
    }
}
