<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Services\PhonePeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;

class PhonePePaymentController extends Controller
{
    protected PhonePeService $phonePeService;

    public function __construct(PhonePeService $phonePeService)
    {
        $this->phonePeService = $phonePeService;
    }

    /**
     * Initiate PhonePe Production Payment for an existing order.
     */
    public function initiate(Request $request)
    {
        $orderNumber = trim($request->input('order_number') ?? $request->input('orderId') ?? '');

        if (empty($orderNumber)) {
            return response()->json([
                'success' => false,
                'message' => 'Order number is required to initiate PhonePe payment.'
            ], 422);
        }

        $order = Order::where('order_number', $orderNumber)->first();

        if (!$order) {
            return response()->json([
                'success' => false,
                'message' => "Order '{$orderNumber}' not found."
            ], 404);
        }

        if ($order->payment_status === 'paid') {
            return response()->json([
                'success' => false,
                'message' => 'This order has already been paid for.'
            ], 400);
        }

        // Construct redirect and webhook callback URLs
        $appBaseUrl = config('app.url', 'http://127.0.0.1:8000');
        $redirectUrl = $appBaseUrl . '/api/v1/payment/phonepe/redirect?order_number=' . urlencode($order->order_number);
        $callbackUrl = $appBaseUrl . '/api/v1/payment/phonepe/callback';

        $result = $this->phonePeService->initiatePayment($order, $redirectUrl, $callbackUrl);

        if ($result['success'] && !empty($result['redirect_url'])) {
            return response()->json([
                'success' => true,
                'order_number' => $order->order_number,
                'merchant_transaction_id' => $result['merchant_transaction_id'] ?? null,
                'redirect_url' => $result['redirect_url'],
                'message' => 'Redirecting to PhonePe Gateway...'
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => $result['message'] ?? 'Failed to initiate PhonePe payment.'
        ], 500);
    }

    /**
     * Handle Server-to-Server Webhook Callback from PhonePe.
     */
    public function callback(Request $request)
    {
        Log::info('PhonePe Callback Webhook Hit:', $request->all());

        $content = $request->getContent();
        $xVerify = $request->header('X-VERIFY') ?? '';

        // Decode PhonePe callback payload
        $responsePayload = $request->input('response');
        $decodedData = [];

        if ($responsePayload) {
            $decodedData = json_decode(base64_decode($responsePayload), true) ?? [];
        }

        $merchantTransactionId = $decodedData['data']['merchantTransactionId'] ?? $request->input('merchantTransactionId');

        if ($merchantTransactionId) {
            $order = Order::where('transaction_id', $merchantTransactionId)->first();

            if ($order) {
                // Securely double-verify with PhonePe Status Check API
                $verification = $this->phonePeService->verifyStatus($merchantTransactionId);

                if ($verification['payment_status'] === 'paid') {
                    $order->update([
                        'payment_status' => 'paid',
                        'order_status' => 'processing',
                        'phonepe_reference_id' => $verification['phonepe_reference_id'] ?? null,
                        'payment_details' => json_encode($verification)
                    ]);
                    Log::info("Order {$order->order_number} marked as PAID via PhonePe Webhook.");
                } else if ($verification['payment_status'] === 'failed') {
                    $order->update([
                        'payment_status' => 'failed',
                        'order_status' => 'cancelled',
                        'payment_details' => json_encode($verification)
                    ]);
                    Log::info("Order {$order->order_number} marked as FAILED via PhonePe Webhook.");
                }
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Callback processed successfully.'
        ]);
    }

    /**
     * Target for customer browser redirect after PhonePe checkout.
     */
    public function redirectUrl(Request $request)
    {
        $orderNumber = $request->input('order_number') ?? $request->query('order_number');
        $merchantTransactionId = $request->input('merchantTransactionId') ?? $request->input('transactionId');

        Log::info("PhonePe Browser Redirect hit for Order: {$orderNumber}");

        if ($orderNumber) {
            $order = Order::where('order_number', $orderNumber)->first();
            if ($order && $order->transaction_id) {
                // Perform status verification
                $verification = $this->phonePeService->verifyStatus($order->transaction_id);
                if ($verification['payment_status'] === 'paid') {
                    $order->update([
                        'payment_status' => 'paid',
                        'order_status' => 'processing',
                        'phonepe_reference_id' => $verification['phonepe_reference_id'] ?? null,
                    ]);
                } else if ($verification['payment_status'] === 'failed') {
                    $order->update([
                        'payment_status' => 'failed',
                        'order_status' => 'cancelled',
                    ]);
                }
            }
        }

        // Redirect customer browser to React Checkout status view
        $frontendUrl = 'http://127.0.0.1:5173/checkout?order_number=' . urlencode($orderNumber ?: '') . '&status=check';
        return redirect()->away($frontendUrl);
    }

    /**
     * Secure status verification endpoint for React frontend.
     */
    public function verifyStatus(Request $request, string $orderNumber)
    {
        $order = Order::where('order_number', $orderNumber)->first();

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

        if ($order->transaction_id && $order->payment_status !== 'paid') {
            $verification = $this->phonePeService->verifyStatus($order->transaction_id);
            if ($verification['payment_status'] === 'paid') {
                $order->update([
                    'payment_status' => 'paid',
                    'order_status' => 'processing',
                    'phonepe_reference_id' => $verification['phonepe_reference_id'] ?? null,
                ]);
            } else if ($verification['payment_status'] === 'failed') {
                $order->update([
                    'payment_status' => 'failed',
                    'order_status' => 'cancelled',
                ]);
            }
        }

        return response()->json([
            'success' => true,
            'payment_status' => $order->payment_status,
            'order_status' => $order->order_status,
            'order' => [
                'id' => $order->id,
                'order_number' => $order->order_number,
                'total_amount' => (float) $order->total_amount,
                'payment_status' => $order->payment_status,
                'order_status' => $order->order_status,
                'customer_name' => $order->customer_name,
            ]
        ]);
    }
}
