<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use App\Models\Wallet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    public function index()
    {
        $user = auth()->user();

        // Ensure wallet exists for existing users
        if (!$user->wallet) {
            $user->wallet()->create([
                'balance' => 0,
                'pending_balance' => 0,
            ]);
            $user->load('wallet');
        }

        $transactions = $user->wallet->transactions()->latest()->paginate(10);
        return view('wallet.index', compact('transactions'));
    }

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

        $user = auth()->user();
        $amount = $request->amount * 100; // Paystack expects amount in kobo

        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . env('PAYSTACK_SECRET_KEY'),
                'Content-Type' => 'application/json',
            ])->post(env('PAYSTACK_PAYMENT_URL') . '/transaction/initialize', [
                        'email' => $user->email,
                        'amount' => $amount,
                        'callback_url' => route('payment.callback'),
                        'metadata' => [
                            'user_id' => $user->id,
                        ]
                    ]);

            if ($response->successful()) {
                $data = $response->json();
                return redirect($data['data']['authorization_url']);
            }

            return back()->with('error', 'Paystack initialization failed: ' . $response->json()['message']);
        } catch (\Exception $e) {
            Log::error('Paystack error: ' . $e->getMessage());
            return back()->with('error', 'Could not initiate payment. Please try again later.');
        }
    }

    public function handleCallback(Request $request)
    {
        $reference = $request->query('reference');

        if (!$reference) {
            return redirect()->route('wallet.index')->with('error', 'No payment reference supplied.');
        }

        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . env('PAYSTACK_SECRET_KEY'),
                'Content-Type' => 'application/json',
            ])->get(env('PAYSTACK_PAYMENT_URL') . "/transaction/verify/" . $reference);

            if ($response->successful()) {
                $data = $response->json();

                if ($data['status'] && $data['data']['status'] === 'success') {
                    $amount = $data['data']['amount'] / 100; // Convert kobo back to Naira
                    $userId = $data['data']['metadata']['user_id'];
                    $user = \App\Models\User::find($userId);

                    if ($user) {
                        \Illuminate\Support\Facades\DB::transaction(function () use ($user, $amount) {
                            $wallet = $user->wallet;
                            $wallet->increment('balance', $amount);

                            Transaction::create([
                                'wallet_id' => $wallet->id,
                                'amount' => $amount,
                                'type' => 'deposit',
                                'status' => 'completed',
                                'description' => 'Wallet funding via Paystack',
                            ]);
                        });

                        return redirect()->route('wallet.index')->with('success', 'Wallet funded successfully!');
                    }
                }
            }

            Log::warning('Paystack verification failed for ref: ' . $reference);
            return redirect()->route('wallet.index')->with('error', 'Payment verification failed. Please contact support.');
        } catch (\Exception $e) {
            Log::error('Paystack callback error: ' . $e->getMessage());
            return redirect()->route('wallet.index')->with('error', 'An error occurred during payment verification.');
        }
    }

    public function showWithdrawForm()
    {
        $user = auth()->user();
        if (!$user->isPromoter()) {
            abort(403);
        }

        $bankDetails = $user->bankDetails;
        $wallet = $user->wallet;

        return view('wallet.withdraw', compact('bankDetails', 'wallet'));
    }

    public function updateBankDetails(Request $request)
    {
        $request->validate([
            'bank_name' => 'required|string|max:255',
            'account_number' => 'required|string|max:20',
            'account_name' => 'required|string|max:255',
        ]);

        $user = auth()->user();
        $user->bankDetails()->updateOrCreate(
            ['user_id' => $user->id],
            $request->only(['bank_name', 'account_number', 'account_name'])
        );

        return back()->with('success', 'Bank details updated successfully.');
    }

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

        $user = auth()->user();
        $wallet = $user->wallet;

        if ($request->amount > $wallet->balance) {
            return back()->with('error', 'Insufficient balance for this withdrawal.');
        }

        if (!$user->bankDetails) {
            return back()->with('error', 'Please set up your bank details first.');
        }

        // Deduct balance and create pending transaction
        $wallet->decrement('balance', $request->amount);

        Transaction::create([
            'wallet_id' => $wallet->id,
            'amount' => $request->amount,
            'type' => 'withdrawal',
            'status' => 'pending',
            'description' => "Withdrawal request to {$user->bankDetails->bank_name} ({$user->bankDetails->account_number})",
        ]);

        return back()->with('success', 'Withdrawal request submitted successfully and is pending approval.');
    }
}
