<?php

namespace App\Http\Controllers\Api;

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

class PaymentMethodController extends \App\Http\Controllers\Controller
{
    /**
     * List active payment methods for checkout
     */
    public function index(): JsonResponse
    {
        $methods = PaymentMethod::where('is_active', true)->get();

        return response()->json([
            'success' => true,
            'data' => $methods->map(function ($method) {
                return [
                    'id' => $method->id,
                    'name' => $method->name,
                    'provider' => $method->provider,
                    'description' => $method->description,
                ];
            }),
            'count' => $methods->count(),
        ], 200);
    }

    /**
     * Admin: List all payment methods
     */
    public function adminIndex(Request $request): JsonResponse
    {
        $query = PaymentMethod::query();

        if ($request->has('provider')) {
            $query->where('provider', $request->input('provider'));
        }

        $methods = $query->paginate($request->input('per_page', 15));

        return response()->json([
            'success' => true,
            'data' => $methods->map(function ($method) {
                return [
                    'id' => $method->id,
                    'name' => $method->name,
                    'provider' => $method->provider,
                    'description' => $method->description,
                    'is_active' => $method->is_active,
                    'created_at' => $method->created_at,
                ];
            }),
            'pagination' => [
                'current_page' => $methods->currentPage(),
                'per_page' => $methods->perPage(),
                'total' => $methods->total(),
                'last_page' => $methods->lastPage(),
            ],
        ], 200);
    }

    /**
     * Admin: Get single payment method
     */
    public function show($id): JsonResponse
    {
        $method = PaymentMethod::find($id);

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

        // Don't expose credentials
        return response()->json([
            'success' => true,
            'data' => [
                'id' => $method->id,
                'name' => $method->name,
                'provider' => $method->provider,
                'description' => $method->description,
                'is_active' => $method->is_active,
                'created_at' => $method->created_at,
            ],
        ], 200);
    }

    /**
     * Admin: Create payment method
     */
    public function store(Request $request): JsonResponse
    {
        $providers = ['stripe', 'paypal', 'wise'];

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'provider' => 'required|in:' . implode(',', $providers),
            'description' => 'nullable|string',
            'credentials' => 'required|array',
            'is_active' => 'boolean',
        ]);

        $method = PaymentMethod::create([
            'name' => $validated['name'],
            'provider' => $validated['provider'],
            'description' => $validated['description'],
            'credentials' => $validated['credentials'],
            'is_active' => $validated['is_active'] ?? true,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Payment method created successfully',
            'data' => [
                'id' => $method->id,
                'name' => $method->name,
                'provider' => $method->provider,
            ],
        ], 201);
    }

    /**
     * Admin: Update payment method
     */
    public function update(Request $request, $id): JsonResponse
    {
        $method = PaymentMethod::find($id);

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

        $providers = ['stripe', 'paypal', 'wise'];

        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'provider' => 'sometimes|in:' . implode(',', $providers),
            'description' => 'nullable|string',
            'credentials' => 'sometimes|array',
            'is_active' => 'sometimes|boolean',
        ]);

        $method->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Payment method updated successfully',
            'data' => [
                'id' => $method->id,
                'name' => $method->name,
                'provider' => $method->provider,
            ],
        ], 200);
    }

    /**
     * Admin: Delete payment method
     */
    public function destroy($id): JsonResponse
    {
        $method = PaymentMethod::find($id);

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

        $method->delete();

        return response()->json([
            'success' => true,
            'message' => 'Payment method deleted successfully',
        ], 200);
    }

    /**
     * Admin: Test payment method credentials
     */
    public function test($id): JsonResponse
    {
        $method = PaymentMethod::find($id);

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

        try {
            if ($method->provider === 'stripe') {
                return $this->testStripeCredentials($method);
            } elseif ($method->provider === 'paypal') {
                return $this->testPayPalCredentials($method);
            } elseif ($method->provider === 'wise') {
                return $this->testWiseCredentials($method);
            }
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Credential test failed: ' . $e->getMessage(),
            ], 400);
        }

        return response()->json([
            'success' => false,
            'message' => 'Unknown provider',
        ], 400);
    }

    /**
     * Test Stripe credentials
     */
    private function testStripeCredentials(PaymentMethod $method): JsonResponse
    {
        try {
            \Stripe\Stripe::setApiKey($method->credentials['api_key'] ?? '');
            \Stripe\Account::retrieve();

            return response()->json([
                'success' => true,
                'message' => 'Stripe credentials are valid',
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Stripe credentials test failed: ' . $e->getMessage(),
            ], 400);
        }
    }

    /**
     * Test PayPal credentials
     */
    private function testPayPalCredentials(PaymentMethod $method): JsonResponse
    {
        // Placeholder for PayPal credential test
        if (!isset($method->credentials['client_id']) || !isset($method->credentials['client_secret'])) {
            return response()->json([
                'success' => false,
                'message' => 'Missing PayPal credentials',
            ], 400);
        }

        return response()->json([
            'success' => true,
            'message' => 'PayPal credentials appear valid',
        ], 200);
    }

    /**
     * Test Wise credentials
     */
    private function testWiseCredentials(PaymentMethod $method): JsonResponse
    {
        // Placeholder for Wise credential test
        if (!isset($method->credentials['api_token'])) {
            return response()->json([
                'success' => false,
                'message' => 'Missing Wise API token',
            ], 400);
        }

        return response()->json([
            'success' => true,
            'message' => 'Wise credentials appear valid',
        ], 200);
    }
}
