<?php

namespace App\Http\Controllers;

use App\Models\Wallet;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Driver;
use App\Services\PaystackService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    protected $paystack;

    public function __construct(PaystackService $paystack)
    {
        $this->paystack = $paystack;
    }

    /**
     * Get user's wallet and Paystack Virtual Account details.
     */
    public function getWallet(Request $request)
    {
        $user = $request->user();
        $wallet = Wallet::firstOrCreate(
            ['user_id' => $user->id],
            ['currency' => 'NGN', 'balance' => 0.00]
        );

        // If DVA doesn't exist, try to create it
        if (!$wallet->paystack_account_number) {
            $this->setupVirtualAccount($user, $wallet);
        }

        return response()->json([
            'success' => true,
            'balance' => $wallet->balance,
            'currency' => $wallet->currency,
            'bank_transfer_details' => [
                'bank_name' => $wallet->paystack_bank_name,
                'account_number' => $wallet->paystack_account_number,
                'account_name' => $user->name,
            ]
        ]);
    }

    /**
     * Handle Paystack Webhook for incoming transfers.
     */
    public function handleWebhook(Request $request)
    {
        // Paystack sends x-paystack-signature header
        // For production, you should verify this signature
        
        $payload = $request->all();
        $event = $payload['event'] ?? '';

        if ($event === 'charge.success') {
            $data = $payload['data'];
            $customerCode = $data['customer']['customer_code'];
            $amountKobo = $data['amount'];
            $amountNaira = $amountKobo / 100;
            $reference = $data['reference'];

            $wallet = Wallet::where('paystack_customer_code', $customerCode)->first();
            
            if ($wallet) {
                // Check if transaction was already processed
                if (Transaction::where('reference', $reference)->exists()) {
                    return response('Already processed', 200);
                }

                DB::transaction(function () use ($wallet, $amountNaira, $reference) {
                    $wallet->balance += $amountNaira;
                    $wallet->save();

                    Transaction::create([
                        'user_id' => $wallet->user_id,
                        'type' => 'credit',
                        'amount' => $amountNaira,
                        'status' => 'completed',
                        'description' => 'Deposit via Bank Transfer (Paystack DVA)',
                        'reference' => $reference,
                    ]);
                });

                return response('Webhook processed', 200);
            }
        }

        return response('Event ignored', 200);
    }

    /**
     * Update driver's bank details for offline bank transfers.
     */
    public function updateDriverBankDetails(Request $request)
    {
        $user = $request->user();
        $driver = Driver::where('user_id', $user->id)->first();

        if (!$driver) {
            return response()->json(['success' => false, 'message' => 'Driver not found'], 404);
        }

        $request->validate([
            'bank_name' => 'required|string',
            'account_number' => 'required|string',
            'account_name' => 'required|string',
        ]);

        $driver->update([
            'bank_name' => $request->bank_name,
            'account_number' => $request->account_number,
            'account_name' => $request->account_name,
        ]);

        return response()->json(['success' => true, 'message' => 'Bank details updated.']);
    }

    /**
     * Internal helper to setup Paystack Virtual Account.
     */
    private function setupVirtualAccount($user, $wallet)
    {
        try {
            $customerCode = $wallet->paystack_customer_code;
            if (!$customerCode) {
                $customerCode = $this->paystack->createCustomer($user);
                if ($customerCode) {
                    $wallet->paystack_customer_code = $customerCode;
                    $wallet->save();
                }
            }

            if ($customerCode) {
                $dva = $this->paystack->createVirtualAccount($customerCode);
                if ($dva) {
                    $wallet->update([
                        'paystack_account_number' => $dva['account_number'],
                        'paystack_bank_name' => $dva['bank']['name'],
                    ]);
                }
            }
        } catch (\Exception $e) {
            Log::error('DVA Setup error: ' . $e->getMessage());
        }
    }
}
