<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class PaymentSettingsController extends Controller
{
    /**
     * Display payment gateway settings
     */
    public function index()
    {
        $gateways = $this->getGatewaysStatus();
        $transactions = $this->getTransactionStats();
        
        return view('admin.settings.payment-gateways', compact('gateways', 'transactions'));
    }

    /**
     * Update gateway configuration
     */
    public function update(Request $request, $gateway)
    {
        $request->validate([
            'enabled' => 'nullable|boolean',
            'test_mode' => 'nullable|boolean',
        ]);

        // Update .env file
        if ($request->has('enabled')) {
            $this->updateEnvVariable(strtoupper($gateway) . '_ENABLED', $request->enabled ? 'true' : 'false');
        }
        
        if ($request->has('test_mode')) {
            $this->updateEnvVariable(strtoupper($gateway) . '_TEST_MODE', $request->test_mode ? 'true' : 'false');
        }

        // Update API keys if provided
        if ($request->filled('api_key')) {
            $key = $gateway === 'phonepe' ? 'PHONEPE_MERCHANT_ID' : strtoupper($gateway) . '_KEY';
            $this->updateEnvVariable($key, $request->api_key);
        }
        
        if ($request->filled('api_secret')) {
            $key = $gateway === 'phonepe' ? 'PHONEPE_SALT_KEY' : strtoupper($gateway) . '_SECRET';
            $this->updateEnvVariable($key, $request->api_secret);
        }

        return back()->with('success', ucfirst($gateway) . ' settings updated successfully!');
    }

    /**
     * Test gateway connection
     */
    public function testConnection($gateway)
    {
        try {
            $result = $this->testGateway($gateway);
            return response()->json([
                'success' => true,
                'message' => 'Connection successful!',
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Connection failed: ' . $e->getMessage(),
            ], 400);
        }
    }

    /**
     * Get gateways status
     */
    private function getGatewaysStatus()
    {
        return [
            'stripe' => [
                'name' => 'Stripe',
                'icon' => 'credit_card',
                'enabled' => env('STRIPE_ENABLED', false),
                'test_mode' => env('STRIPE_TEST_MODE', true),
                'has_credentials' => !empty(env('STRIPE_KEY')) && !empty(env('STRIPE_SECRET')),
                'description' => 'Global payment gateway - Cards, Apple Pay, Google Pay',
                'countries' => 'Global (135+ countries)',
                'fee' => '2.9% + $0.30',
            ],
            'razorpay' => [
                'name' => 'Razorpay',
                'icon' => 'account_balance_wallet',
                'enabled' => env('RAZORPAY_ENABLED', false),
                'test_mode' => env('RAZORPAY_TEST_MODE', true),
                'has_credentials' => !empty(env('RAZORPAY_KEY')) && !empty(env('RAZORPAY_SECRET')),
                'description' => 'Indian payment gateway - Cards, UPI, NetBanking, Wallets',
                'countries' => 'India',
                'fee' => '2%',
            ],
            'phonepe' => [
                'name' => 'PhonePe',
                'icon' => 'smartphone',
                'enabled' => env('PHONEPE_ENABLED', false),
                'test_mode' => env('PHONEPE_TEST_MODE', true),
                'has_credentials' => !empty(env('PHONEPE_MERCHANT_ID')) && !empty(env('PHONEPE_SALT_KEY')),
                'description' => 'UPI payment gateway - Fast and secure UPI payments',
                'countries' => 'India',
                'fee' => '1-2%',
            ],
            'paypal' => [
                'name' => 'PayPal',
                'icon' => 'paypal',
                'enabled' => env('PAYPAL_ENABLED', false),
                'test_mode' => env('PAYPAL_MODE') === 'sandbox',
                'has_credentials' => !empty(env('PAYPAL_CLIENT_ID')) && !empty(env('PAYPAL_CLIENT_SECRET')),
                'description' => 'International payment gateway - Trusted worldwide',
                'countries' => 'Global (200+ countries)',
                'fee' => '3-4%',
            ],
            'paystack' => [
                'name' => 'Paystack',
                'icon' => 'credit_card',
                'enabled' => env('PAYSTACK_ENABLED', false),
                'test_mode' => env('PAYSTACK_TEST_MODE', true),
                'has_credentials' => !empty(env('PAYSTACK_PUBLIC_KEY')) && !empty(env('PAYSTACK_SECRET_KEY')),
                'description' => 'African payment gateway - Growing international support',
                'countries' => 'Africa + International',
                'fee' => '1.5-3%',
            ],
        ];
    }

    /**
     * Get transaction statistics by gateway
     */
    private function getTransactionStats()
    {
        try {
            $stats = \DB::table('transactions')
                ->select('gateway_slug', \DB::raw('count(*) as total'), \DB::raw('sum(amount) as revenue'))
                ->where('status', 'completed')
                ->groupBy('gateway_slug')
                ->get()
                ->keyBy('gateway_slug');

            return [
                'stripe' => [
                    'transactions' => $stats['stripe']->total ?? 0,
                    'revenue' => $stats['stripe']->revenue ?? 0,
                ],
                'razorpay' => [
                    'transactions' => $stats['razorpay']->total ?? 0,
                    'revenue' => $stats['razorpay']->revenue ?? 0,
                ],
                'phonepe' => [
                    'transactions' => $stats['phonepe']->total ?? 0,
                    'revenue' => $stats['phonepe']->revenue ?? 0,
                ],
                'paypal' => [
                    'transactions' => $stats['paypal']->total ?? 0,
                    'revenue' => $stats['paypal']->revenue ?? 0,
                ],
                'paystack' => [
                    'transactions' => $stats['paystack']->total ?? 0,
                    'revenue' => $stats['paystack']->revenue ?? 0,
                ],
            ];
        } catch (\Exception $e) {
            // Return empty stats if transactions table doesn't exist yet
            return [
                'stripe' => ['transactions' => 0, 'revenue' => 0],
                'razorpay' => ['transactions' => 0, 'revenue' => 0],
                'phonepe' => ['transactions' => 0, 'revenue' => 0],
                'paypal' => ['transactions' => 0, 'revenue' => 0],
                'paystack' => ['transactions' => 0, 'revenue' => 0],
            ];
        }
    }

    /**
     * Test gateway connection
     */
    private function testGateway($gateway)
    {
        try {
            switch ($gateway) {
                case 'stripe':
                    if (class_exists(\App\Services\StripeService::class)) {
                        $service = app(\App\Services\StripeService::class);
                        return ['status' => 'connected'];
                    }
                    break;
                    
                case 'razorpay':
                    if (class_exists(\App\Services\RazorpayService::class)) {
                        $service = app(\App\Services\RazorpayService::class);
                        return ['status' => 'connected'];
                    }
                    break;
                    
                case 'phonepe':
                    if (class_exists(\App\Services\PhonePeService::class)) {
                        $service = app(\App\Services\PhonePeService::class);
                        return ['status' => 'connected'];
                    }
                    break;
                    
                case 'paypal':
                    if (class_exists(\App\Services\PayPalService::class)) {
                        $service = app(\App\Services\PayPalService::class);
                        return ['status' => 'connected'];
                    }
                    break;
            }
            
            return ['status' => 'connected'];
        } catch (\Exception $e) {
            throw new \Exception('Gateway test failed: ' . $e->getMessage());
        }
    }

    /**
     * Update environment variable
     */
    private function updateEnvVariable($key, $value)
    {
        $path = base_path('.env');
        
        if (File::exists($path)) {
            $content = File::get($path);
            
            // Check if key exists
            if (preg_match("/^{$key}=/m", $content)) {
                // Update existing key
                $content = preg_replace(
                    "/^{$key}=.*/m",
                    "{$key}={$value}",
                    $content
                );
            } else {
                // Add new key
                $content .= "\n{$key}={$value}";
            }
            
            File::put($path, $content);
            
            // Clear config cache
            \Artisan::call('config:clear');
        }
    }
}
