<?php

namespace MtcPharmacy\Subscriptions\Classes\PaymentGateways;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Event;
use Mtc\Plugins\RyftPay\Classes\RyftPay;
use Mtc\Plugins\RyftPay\Classes\RyftPayment;
use MtcPharmacy\Subscriptions\Classes\Subscription;
use MtcPharmacy\Subscriptions\Classes\SubscriptionLog;
use MtcPharmacy\Subscriptions\Classes\PaymentGatewayInterface;


class RyftPaymentGateway extends PaymentGatewayInterface
{

    public function processPayment()
    {
        try {
            $subscription = Subscription::find($this->order->subscription_id);

            if (!$subscription) {
                Log::error('Ryft subscription payment failed: Subscription not found', [
                    'subscription_id' => $this->order->subscription_id,
                    'order_id' => $this->order->id,
                ]);
                return false;
            }

            $ryftPayment = RyftPayment::query()->where('remote_id', $subscription->previous_payment_id)->first();

            if ($ryftPayment) {
                $paymentSessionData = [
                    'amount' => ceil($this->order->cost_total * 100),
                    'currency' => 'GBP',
                    'customerEmail' => $this->order->info->email,
                    'metadata' => [
                        'orderId' => $this->order->id,
                        'customerId' => $this->order->member,
                    ],
                    "customerDetails" => [
                        "id" => $ryftPayment->customer_id,
                    ],
                    'previousPayment' => [
                        'id' => $ryftPayment->remote_id
                    ],
                    'attemptPayment' => [
                        'paymentMethod' => [
                            'id' => $ryftPayment->payment_method_id,
                        ]
                    ],
                    'paymentType' => 'Unscheduled',
                    'returnUrl' => config('app.url') . '/plugins/RyftPay/checkout/return.php',
                    'captureFlow' => config('ryftpay.manual_capture') ? 'Manual' : 'Automatic',
                ];

                $ryftPay = new RyftPay();
                $ryftPay->createPaymentSession($paymentSessionData);

                $paymentSession = $ryftPay->getFetchedPaymentSession();

                if (isset($paymentSession['id'])) {
                    Log::debug('Ryft payment session created', [
                        'payment_session_id' => $paymentSession['id'] ?? 'N/A',
                        'status' => $paymentSession['status'] ?? 'N/A',
                        'order_id' => $this->order->id,
                    ]);

                    $paymentData = [
                        'order_id' => $this->order->id,
                        'member_id' => $this->order->member,
                        'remote_id' => $paymentSession ? $paymentSession['id'] : null,
                        'amount' => $this->order->cost_total,
                        'currency' => 'GBP',
                        'status' => RyftPayment::STATUS_PENDING,
                        'method' => RyftPayment::METHOD_CARD,
                    ];

                    $ryftPay->createPayment($paymentData);

                    $orderObj = new \Order($this->order->id);

                    $ryftPay->initializePayment($orderObj);

                    SubscriptionLog::logPaymentAttempted(
                        $subscription,
                        $orderObj->getTotalCost(),
                        SubscriptionLog::SOURCE_SYSTEM,
                        ['command' => 'payment_attempted', 'order_id' => $this->order->id]
                    );

                    return true;
                } else {
                    Log::error("Payment Authorization Failure for subscription id: " . $subscription->id . " : " . json_encode($paymentSession));
                    Event::dispatch('subscriptions.paymentFailed', $subscription);
                    return false;
                }
            } else {
                Log::error('RYFT Payment Not Found for subscription id: ' . $subscription->id);
                Event::dispatch('subscriptions.paymentFailed', $subscription);
                return false;
            }
        } catch (\Exception $e) {
            Log::error('Ryft payment processing failed: ' . $e->getMessage(), ['exception' => $e]);
            return false;
        }
    }

    public function getPreviousPaymentInfo()
    {
        $ryftPayment = RyftPayment::query()->where('order_id', $this->order->id)->first();
        if ($ryftPayment) {
            return $ryftPayment->remote_id;
        }
        return null;
    }
}