<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class PaymentMethodController extends Controller
{
    public function index()
    {
        $methods = \App\Models\PaymentMethod::where('is_active', true)->get()->map(function ($method) {
            $config = $method->config ?? [];
            $publicConfig = [];

            if ($method->type === 'stripe') {
                $mode = $config['stripe_mode'] ?? 'sandbox';
                if ($mode === 'live') {
                    $publicConfig['publishable_key'] = $config['stripe_live_publishable_key'] ?? null;
                } else {
                    $publicConfig['publishable_key'] = $config['stripe_sandbox_publishable_key'] ?? $config['stripe_publishable_key'] ?? null;
                }
            } elseif ($method->type === 'paypal') {
                $mode = $config['paypal_mode'] ?? 'sandbox';
                $publicConfig['mode'] = $mode;
                
                if ($mode === 'live') {
                    $publicConfig['client_id'] = $config['paypal_live_client_id'] ?? null;
                } else {
                    $publicConfig['client_id'] = $config['paypal_sandbox_client_id'] ?? $config['paypal_client_id'] ?? null;
                }
            } elseif ($method->type === 'paytm') {
                $publicConfig['merchant_id'] = $config['paytm_merchant_id'] ?? null;
                $publicConfig['environment'] = $config['paytm_environment'] ?? 'TEST';
            } elseif ($method->type === 'razorpay') {
                $publicConfig['key_id'] = $config['razorpay_key_id'] ?? null;
            }

            return [
                'id' => $method->id,
                'name' => $method->name,
                'slug' => $method->slug,
                'type' => $method->type,
                'logo' => $method->logo ? (str_starts_with($method->logo, 'http') ? $method->logo : route('public.media', ['path' => $method->logo])) : null,
                'is_active' => $method->is_active,
                'config' => $publicConfig,
            ];
        });

        return response()->json(['data' => $methods]);
    }
}
