<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Payment\ProcessPaymentRequest;
use App\Http\Resources\PaymentResource;
use App\Models\Order;
use App\Models\Payment;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class PaymentController extends Controller
{
    public function process(ProcessPaymentRequest $request): JsonResponse
    {
        $order = Order::findOrFail($request->order_id);

        // Check authorization
        $user = $request->user();
        if ($user && $user->isCustomer() && $order->user_id !== $user->id) {
            return response()->json([
                'message' => 'Unauthorized',
            ], 403);
        }

        // Check if order is already paid
        if ($order->isPaid()) {
            return response()->json([
                'message' => 'Order is already paid',
            ], 422);
        }

        DB::beginTransaction();

        try {
            // Create payment record
            $payment = Payment::create([
                'order_id' => $order->id,
                'payment_method' => $request->payment_method,
                'payment_intent_id' => $request->payment_intent_id,
                'status' => 'pending',
                'amount' => $order->total,
                'currency' => $order->currency,
                'metadata' => $request->metadata,
            ]);

            // Process payment based on method
            switch ($request->payment_method) {
                case 'stripe':
                    $this->processStripePayment($payment, $request);
                    break;
                case 'cash':
                case 'bank_transfer':
                    // For cash/bank transfer, mark as processing
                    $payment->update(['status' => 'processing']);
                    break;
            }

            DB::commit();

            return response()->json([
                'message' => 'Payment processed',
                'data' => new PaymentResource($payment->load('order')),
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();

            return response()->json([
                'message' => 'Payment processing failed',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    protected function processStripePayment(Payment $payment, ProcessPaymentRequest $request): void
    {
        // Mock Stripe payment processing
        // In production, integrate with Stripe SDK:
        // $stripe = new \Stripe\StripeClient(config('services.stripe.secret'));
        // $intent = $stripe->paymentIntents->retrieve($request->payment_intent_id);
        
        // For now, simulate payment success
        if ($request->payment_intent_id) {
            // Mock: Assume payment succeeds if intent ID is provided
            $payment->markAsSucceeded();
            $payment->order->update([
                'status' => 'paid',
                'paid_at' => now(),
            ]);
        } else {
            // Mock: Create payment intent
            $payment->update([
                'payment_intent_id' => 'pi_mock_' . uniqid(),
                'payment_details' => [
                    'client_secret' => 'pi_mock_' . uniqid() . '_secret',
                ],
            ]);
        }
    }

    public function confirm(Request $request, Payment $payment): JsonResponse
    {
        // Check authorization
        $user = $request->user();
        if ($user && $user->isCustomer() && $payment->order->user_id !== $user->id) {
            return response()->json([
                'message' => 'Unauthorized',
            ], 403);
        }

        DB::beginTransaction();

        try {
            // Confirm payment (for cash/bank transfer)
            if ($payment->status === 'processing') {
                $payment->markAsSucceeded();
                $payment->order->update([
                    'status' => 'paid',
                    'paid_at' => now(),
                ]);
            }

            DB::commit();

            return response()->json([
                'message' => 'Payment confirmed',
                'data' => new PaymentResource($payment->load('order')),
            ]);
        } catch (\Exception $e) {
            DB::rollBack();

            return response()->json([
                'message' => 'Failed to confirm payment',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function webhook(Request $request): JsonResponse
    {
        // Handle Stripe webhook
        // Verify webhook signature
        // Process payment status updates
        
        $payload = $request->all();
        
        // Mock webhook handler
        if (isset($payload['type']) && $payload['type'] === 'payment_intent.succeeded') {
            $paymentIntentId = $payload['data']['object']['id'] ?? null;
            
            if ($paymentIntentId) {
                $payment = Payment::where('payment_intent_id', $paymentIntentId)->first();
                
                if ($payment) {
                    $payment->markAsSucceeded();
                    $payment->order->update([
                        'status' => 'paid',
                        'paid_at' => now(),
                    ]);
                }
            }
        }

        return response()->json(['received' => true]);
    }
}
