<?php

namespace App\Services;

use App\Models\Booking;
use App\Models\Order;
use Unicodeveloper\Paystack\Facades\Paystack;

class PaystackService implements PaymentService
{
    /**
     * Initialize a payment with Paystack.
     *
     * @param array $data
     * @return array
     */
    public function initializePayment(array $data): array
    {
        try {
            // Paystack expects amount in kobo (cents)
            $data['amount'] = $data['amount'] * 100;
            $payment = Paystack::getAuthorizationUrl($data);
            $prop = null;

            $authorizationUrl = $payment->url ?? $payment->authorizationUrl ?? null;
            $ref = new \ReflectionObject($payment);
            if ($ref->hasProperty('url')) {
                $prop = $ref->getProperty('url');
                $prop->setAccessible(true);
            } elseif ($ref->hasProperty('authorizationUrl')) {
                $prop = $ref->getProperty('authorizationUrl');
                $prop->setAccessible(true);
            }

            $authorizationUrl = $prop->getValue($payment);


            if ($authorizationUrl) {
                $reference = $data['orderID'] ?? null;
                return [
                    'status' => true,
                    'authorization_url' => $authorizationUrl,
                    'reference' => $reference,
                ];
            }

            return ['status' => false, 'message' => 'Paystack initialization failed: No authorization URL returned.'];

        } catch (\Exception $e) {
            \Log::error('PaystackService initializePayment Error: ' . $e->getMessage(), ['exception' => $e]);
            return ['status' => false, 'message' => 'Paystack service error during initialization: ' . $e->getMessage()];
        }
    }

    /**
     * Verify a payment with Paystack.
     *
     * @param string $reference
     * @return array
     */
    public function verifyPayment(string $reference): array
    {
        try {
            $paymentDetails = Paystack::getPaymentData($reference);
            if ($paymentDetails['status'] && $paymentDetails['data']['status'] === 'success') {
                $booking = Booking::where('reference_id', $reference)->first();
                if ($booking) {
                    $booking->status = 'paid';
                    $booking->payload = $paymentDetails['data'];
                    $booking->save();
                } else {
                    $order = Order::find($reference);
                    if($order) {
                        $order->status = 'paid';
                        $order->payload = $paymentDetails['data'];
                        $order->save();
                    }
                }
                return [
                    'status' => true,
                    'data' => (array) $paymentDetails['data'], // Cast to array for consistency
                ];
            }

            return ['status' => false, 'message' => $paymentDetails['message'] ?? 'Paystack verification failed.'];
        } catch (\Exception $e) {
            \Log::error('PaystackService verifyPayment Error: ' . $e->getMessage(), ['exception' => $e]);
            return ['status' => false, 'message' => 'Paystack service error during verification: ' . $e->getMessage()];
        }
    }
}