<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\PaymentMethod;
use App\Services\Payment\StripeService;
use App\Services\Payment\PayPalService;
use App\Services\Payment\PaytmService;
use Illuminate\Support\Str;

class PaymentController extends Controller
{
    public function initiate(Request $request)
    {
        $request->validate([
            'payment_method_id' => 'required|exists:payment_methods,id',
            'amount' => 'required|numeric|min:0.01',
            'currency' => 'nullable|string|max:10',
        ]);

        $paymentMethod = PaymentMethod::find($request->payment_method_id);
        
        if (!$paymentMethod->is_active) {
            return response()->json(['message' => 'Payment method is not active'], 400);
        }

        $config = $paymentMethod->config ?? [];
        $currency = $request->currency ?? 'USD';
        $callbackUrl = $request->callback_url;
        $user = $request->user() ?? (object)['id' => 'guest_' . Str::random(10)];

        try {
            if ($paymentMethod->type === 'stripe') {
                $service = new StripeService($config);
                $result = $service->createPaymentIntent($request->amount, $currency);
                return response()->json([
                    'status' => 'success',
                    'client_secret' => $result['client_secret'],
                    'payment_intent_id' => $result['id'],
                    'publishable_key' => $service->getPublishableKey(),
                ]);
            } elseif ($paymentMethod->type === 'paypal') {
                $service = new PayPalService($config);
                $result = $service->createOrder($request->amount, $currency, $callbackUrl);
                return response()->json([
                    'status' => 'success',
                    'order_id' => $result['id'],
                    'approval_link' => collect($result['links'])->firstWhere('rel', 'approve')['href'] ?? null
                ]);
            } elseif ($paymentMethod->type === 'paytm') {
                $service = new PaytmService($config);
                $orderId = 'ORD-' . strtoupper(Str::random(10));
                // Callback URL should be handled by the app or a backend endpoint that redirects to the app
                // For mobile apps, usually we verify transaction status manually after the flow returns
                $callbackUrl = route('api.payment.paytm.callback'); 
                
                $result = $service->initiateTransaction($orderId, $request->amount, (string)$user->id, $callbackUrl);
                return response()->json([
                    'status' => 'success',
                    'txnToken' => $result['txnToken'],
                    'orderId' => $result['orderId'],
                    'mid' => $result['mid'],
                    'environment' => $config['paytm_environment'] ?? 'TEST',
                ]);
            }
            
            return response()->json([
                'status' => 'success',
                'message' => 'Payment initiation not required for this method (e.g. COD)'
            ], 200);

        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Payment Initiation Error: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function paytmCallback(Request $request) {
        // This is just a placeholder callback. 
        // Real implementation would verify the checksum posted by Paytm.
        return response()->json(['message' => 'Callback received', 'data' => $request->all()]);
    }
}
