<?php

namespace App\Http\Controllers\Payment;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Services\Payment\PayPalService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PayPalController extends Controller
{
    protected $paypalService;

    public function __construct(PayPalService $paypalService)
    {
        $this->paypalService = $paypalService;
    }

    /**
     * Create PayPal order
     */
    public function createOrder(Request $request)
    {
        $request->validate([
            'payment_id' => 'required|exists:payments,id',
        ]);

        $payment = Payment::findOrFail($request->payment_id);

        if ($payment->status !== 'pending') {
            return response()->json([
                'success' => false,
                'message' => 'Payment is not in pending status'
            ], 400);
        }

        try {
            $order = $this->paypalService->createOrder(
                $payment->amount,
                $payment->currency,
                [
                    'payment_id' => $payment->id,
                    'user_id' => $payment->user_id,
                    'type' => $payment->type
                ]
            );

            $payment->update([
                'transaction_id' => $order['id']
            ]);

            return response()->json([
                'success' => true,
                'order_id' => $order['id'],
                'approval_url' => $order['links'][1]['href'] ?? null
            ]);

        } catch (\Exception $e) {
            Log::error('PayPal order creation failed: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Failed to create PayPal order'
            ], 500);
        }
    }

    /**
     * Capture PayPal payment
     */
    public function capture(Request $request)
    {
        $request->validate([
            'order_id' => 'required|string',
            'payment_id' => 'required|exists:payments,id'
        ]);

        $payment = Payment::findOrFail($request->payment_id);

        try {
            $result = $this->paypalService->captureOrder($request->order_id);

            if ($result['status'] === 'COMPLETED') {
                $payment->update([
                    'status' => 'completed',
                    'transaction_id' => $request->order_id,
                    'payment_details' => json_encode($result)
                ]);

                // Activate subscription if payment is for subscription
                if ($payment->subscription_id) {
                    $payment->subscription->update(['status' => 'active']);
                }

                return response()->json([
                    'success' => true,
                    'message' => 'Payment captured successfully',
                    'payment' => $payment
                ]);
            }

            return response()->json([
                'success' => false,
                'message' => 'Payment capture failed',
                'status' => $result['status']
            ], 400);

        } catch (\Exception $e) {
            Log::error('PayPal capture failed: ' . $e->getMessage());

            $payment->update(['status' => 'failed']);

            return response()->json([
                'success' => false,
                'message' => 'Payment capture failed'
            ], 500);
        }
    }

    /**
     * Handle PayPal webhook
     */
    public function webhook(Request $request)
    {
        $payload = $request->all();

        try {
            // Verify webhook signature (implement as needed)
            $eventType = $payload['event_type'] ?? null;

            switch ($eventType) {
                case 'PAYMENT.CAPTURE.COMPLETED':
                    $this->handlePaymentSuccess($payload);
                    break;

                case 'PAYMENT.CAPTURE.DENIED':
                    $this->handlePaymentFailure($payload);
                    break;

                case 'PAYMENT.CAPTURE.REFUNDED':
                    $this->handleRefund($payload);
                    break;

                default:
                    Log::info('Unhandled PayPal webhook event: ' . $eventType);
            }

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

        } catch (\Exception $e) {
            Log::error('PayPal webhook error: ' . $e->getMessage());
            return response()->json(['error' => 'Webhook error'], 400);
        }
    }

    /**
     * Handle successful payment
     */
    protected function handlePaymentSuccess($payload)
    {
        $orderId = $payload['resource']['supplementary_data']['related_ids']['order_id'] ?? null;

        if ($orderId) {
            $payment = Payment::where('transaction_id', $orderId)->first();

            if ($payment && $payment->status === 'pending') {
                $payment->update([
                    'status' => 'completed',
                    'payment_details' => json_encode($payload)
                ]);

                if ($payment->subscription_id) {
                    $payment->subscription->update(['status' => 'active']);
                }
            }
        }
    }

    /**
     * Handle failed payment
     */
    protected function handlePaymentFailure($payload)
    {
        $orderId = $payload['resource']['supplementary_data']['related_ids']['order_id'] ?? null;

        if ($orderId) {
            $payment = Payment::where('transaction_id', $orderId)->first();

            if ($payment) {
                $payment->update([
                    'status' => 'failed',
                    'payment_details' => json_encode($payload)
                ]);
            }
        }
    }

    /**
     * Handle refund
     */
    protected function handleRefund($payload)
    {
        $orderId = $payload['resource']['supplementary_data']['related_ids']['order_id'] ?? null;

        if ($orderId) {
            $payment = Payment::where('transaction_id', $orderId)->first();

            if ($payment) {
                $payment->update([
                    'status' => 'refunded',
                    'payment_details' => json_encode($payload)
                ]);
            }
        }
    }

    /**
     * Process refund
     */
    public function refund(Request $request)
    {
        $request->validate([
            'payment_id' => 'required|exists:payments,id',
            'amount' => 'nullable|numeric|min:0',
            'note' => 'nullable|string'
        ]);

        $payment = Payment::findOrFail($request->payment_id);

        if ($payment->status !== 'completed') {
            return response()->json([
                'success' => false,
                'message' => 'Only completed payments can be refunded'
            ], 400);
        }

        try {
            // Get capture ID from payment details
            $paymentDetails = json_decode($payment->payment_details, true);
            $captureId = $paymentDetails['purchase_units'][0]['payments']['captures'][0]['id'] ?? null;

            if (!$captureId) {
                throw new \Exception('Capture ID not found');
            }

            $refund = $this->paypalService->refundPayment(
                $captureId,
                $request->amount,
                $payment->currency,
                $request->note
            );

            $payment->update([
                'status' => 'refunded',
                'payment_details' => json_encode(array_merge(
                    $paymentDetails,
                    ['refund' => $refund]
                ))
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Refund processed successfully',
                'refund' => $refund
            ]);

        } catch (\Exception $e) {
            Log::error('PayPal refund failed: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Refund processing failed'
            ], 500);
        }
    }
}
