<?php

namespace App\Http\Controllers\Billing;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class BillingPaymentController extends Controller
{
    public function resume(Request $request, Payment $payment): JsonResponse
    {
        $user = $request->user();
        if (! $user || (int) $payment->user_id !== (int) $user->id) {
            abort(403);
        }

        if ((string) $payment->status !== 'pending') {
            return response()->json(['ok' => false, 'error' => 'payment_not_pending'], 409);
        }

        $provider = strtolower((string) $payment->provider);

        return match ($provider) {
            'paypal' => $this->resumePayPal($payment),
            'pakasir' => $this->resumePakasir($payment),
            default => response()->json(['ok' => false, 'error' => 'provider_unsupported'], 422),
        };
    }

    private function resumePayPal(Payment $payment): JsonResponse
    {
        $raw = is_array($payment->raw_payload) ? $payment->raw_payload : [];
        $links = is_array($raw['links'] ?? null) ? $raw['links'] : [];
        $approveUrl = null;
        foreach ($links as $link) {
            if (! is_array($link)) {
                continue;
            }
            if ((string) ($link['rel'] ?? '') === 'approve') {
                $href = trim((string) ($link['href'] ?? ''));
                if ($href !== '') {
                    $approveUrl = $href;
                    break;
                }
            }
        }

        if ($approveUrl === null) {
            return response()->json(['ok' => false, 'error' => 'resume_data_missing'], 422);
        }

        return response()->json([
            'ok' => true,
            'mode' => 'redirect',
            'provider' => 'paypal',
            'approve_url' => $approveUrl,
            'payment_id' => $payment->id,
        ]);
    }

    private function resumePakasir(Payment $payment): JsonResponse
    {
        $raw = is_array($payment->raw_payload) ? $payment->raw_payload : [];
        $pay = is_array($raw['payment'] ?? null)
            ? $raw['payment']
            : (is_array($raw['data'] ?? null) ? $raw['data'] : $raw);

        $paymentNumber = trim((string) (
            $pay['payment_number']
            ?? $pay['qris_string']
            ?? $pay['qr_string']
            ?? $pay['qr_value']
            ?? ''
        ));
        $expiredAt = trim((string) (
            $pay['expired_at']
            ?? $pay['expires_at']
            ?? $pay['expired']
            ?? ''
        ));
        $totalPayment = (int) (
            $pay['total_payment']
            ?? $pay['amount']
            ?? $raw['total_payment']
            ?? $raw['amount']
            ?? $payment->amount
        );
        $orderId = trim((string) (
            $pay['order_id']
            ?? $raw['order_id']
            ?? $payment->order?->provider_ref
            ?? ''
        ));

        if ($paymentNumber === '') {
            return response()->json(['ok' => false, 'error' => 'resume_data_missing'], 422);
        }

        if ($expiredAt !== '') {
            $ts = strtotime($expiredAt);
            if ($ts !== false && $ts < time()) {
                return response()->json(['ok' => false, 'error' => 'payment_expired'], 409);
            }
        }

        return response()->json([
            'ok' => true,
            'mode' => 'qris',
            'provider' => 'pakasir',
            'payment_id' => $payment->id,
            'payment_number' => $paymentNumber,
            'expired_at' => $expiredAt,
            'amount' => (int) $payment->amount,
            'total_payment' => $totalPayment,
            'order_id' => $orderId,
        ]);
    }
}
