<?php

namespace App\Http\Controllers;

use App\Models\PaymentMethod;
use Illuminate\Http\Request;

class PaymentMethodController extends Controller
{
    /**
     * Display a listing of payment methods.
     */
    public function index()
    {
        $paymentMethods = PaymentMethod::paginate(15);

        return view('admin.payment-methods.index', compact('paymentMethods'));
    }

    /**
     * Show the form for creating a new payment method.
     */
    public function create()
    {
        $providers = ['stripe', 'paypal', 'wise'];

        return view('admin.payment-methods.create', compact('providers'));
    }

    /**
     * Store a newly created payment method in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'provider' => 'required|in:stripe,paypal,wise',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'credentials' => 'required|array',
            'credentials.*.key' => 'required|string',
            'credentials.*.value' => 'required|string',
        ]);

        // Convert credentials array to associative array
        $credentialsArray = [];
        foreach ($request->input('credentials', []) as $credential) {
            $credentialsArray[$credential['key']] = $credential['value'];
        }

        $paymentMethod = new PaymentMethod($validated);
        $paymentMethod->setCredentials($credentialsArray);
        $paymentMethod->is_active = $request->boolean('is_active', true);
        $paymentMethod->save();

        return redirect()->route('admin.payment-methods.index')
            ->with('success', 'Payment method added successfully');
    }

    /**
     * Display the specified payment method.
     */
    public function show(PaymentMethod $paymentMethod)
    {
        return view('admin.payment-methods.show', compact('paymentMethod'));
    }

    /**
     * Show the form for editing the specified payment method.
     */
    public function edit(PaymentMethod $paymentMethod)
    {
        $providers = ['stripe', 'paypal', 'wise'];
        $credentials = $paymentMethod->getCredentials();

        return view('admin.payment-methods.edit', compact('paymentMethod', 'providers', 'credentials'));
    }

    /**
     * Update the specified payment method in storage.
     */
    public function update(Request $request, PaymentMethod $paymentMethod)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'provider' => 'required|in:stripe,paypal,wise',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'credentials' => 'required|array',
            'credentials.*.key' => 'required|string',
            'credentials.*.value' => 'required|string',
        ]);

        // Convert credentials array to associative array
        $credentialsArray = [];
        foreach ($request->input('credentials', []) as $credential) {
            $credentialsArray[$credential['key']] = $credential['value'];
        }

        $paymentMethod->fill($validated);
        $paymentMethod->setCredentials($credentialsArray);
        $paymentMethod->is_active = $request->boolean('is_active', true);
        $paymentMethod->save();

        return redirect()->route('admin.payment-methods.index')
            ->with('success', 'Payment method updated successfully');
    }

    /**
     * Remove the specified payment method from storage.
     */
    public function destroy(PaymentMethod $paymentMethod)
    {
        $paymentMethod->delete();

        return redirect()->route('admin.payment-methods.index')
            ->with('success', 'Payment method deleted successfully');
    }

    /**
     * Test the payment method connection.
     */
    public function test(PaymentMethod $paymentMethod)
    {
        try {
            $credentials = $paymentMethod->getCredentials();

            // Test based on provider
            $isValid = match ($paymentMethod->provider) {
                'stripe' => isset($credentials['api_key']) && !empty($credentials['api_key']),
                'paypal' => isset($credentials['client_id']) && !empty($credentials['client_id']),
                'wise' => isset($credentials['api_token']) && !empty($credentials['api_token']),
                default => false,
            };

            if ($isValid) {
                return redirect()->back()
                    ->with('success', "{$paymentMethod->provider} credentials are valid");
            }

            return redirect()->back()
                ->with('error', "Invalid {$paymentMethod->provider} credentials");
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', "Error testing payment method: {$e->getMessage()}");
        }
    }
}
