<?php

namespace MtcPharmacy\Subscriptions\Classes\PaymentGateways;

use Illuminate\Support\Facades\Log;
use Mtc\Plugins\MolliePay\Classes\MolliePay;
use MtcPharmacy\Subscriptions\Classes\PaymentGatewayInterface;

class MolliePaymentGateway extends PaymentGatewayInterface
{
    public function processPayment()
    {
        try {
            Log::info('Processing subscription payment', [
                'order_id' => $this->order->id,
                'subscription_id' => $this->order->subscription_id
            ]);

            // Get the subscription for this order
            $subscription = \MtcPharmacy\Subscriptions\Classes\Subscription::find($this->order->subscription_id);
            if (!$subscription) {
                Log::error('Subscription not found for recurring payment', [
                    'order_id' => $this->order->id,
                    'subscription_id' => $this->order->subscription_id
                ]);
                return false;
            }

            // Get the Mollie client
            $mollie = MolliePay::getClient();

            // If we have a previous payment ID, use it for recurring payment
            if (!empty($subscription->previous_payment_id)) {
                $previousPayment = $mollie->payments->get($subscription->previous_payment_id);

                // Check if we have a customerId
                $customerId = null;
                if (!empty($previousPayment->customerId)) {
                    $customerId = $previousPayment->customerId;
                } elseif (!empty($subscription->customer_id)) {
                    $customerId = $subscription->customer_id;
                }

                if (!$customerId) {
                    Log::error('No customer ID found for recurring payment', [
                        'order_id' => $this->order->id,
                        'subscription_id' => $subscription->id
                    ]);
                    return false;
                }

                // Create the payment
                $payment = $mollie->payments->create([
                    'amount' => [
                        'currency' => 'GBP',
                        'value' => number_format($this->order->cost_total, 2, '.', '')
                    ],
                    'customerId' => $customerId,
                    'sequenceType' => 'recurring',
                    'description' => 'Subscription payment for order #' . $this->order->id,
                    'metadata' => [
                        'order_id' => $this->order->id,
                        'subscription_id' => $subscription->id,
                        'is_subscription' => true
                    ],
                    'webhookUrl' => MolliePay::WEBHOOK_PAYMENT_URL
                ]);

                Log::info('Created recurring payment', [
                    'order_id' => $this->order->id,
                    'payment_id' => $payment->id,
                    'subscription_id' => $subscription->id
                ]);

                // Only mark as paid when Mollie confirms payment -- open/pending need webhook confirmation
                if ($payment->isFailed() || $payment->isCanceled() || $payment->isExpired()) {
                    Log::error('Mollie payment failed/cancelled/expired', [
                        'order_id' => $this->order->id,
                        'payment_id' => $payment->id,
                        'status' => $payment->status
                    ]);
                    return false;
                }

                // Save the Mollie payment record regardless of status
                \Mtc\Plugins\MolliePay\Classes\OrderMollie::create([
                    'order_id' => $this->order->id,
                    'amount' => $payment->amount->value,
                    'tr_id' => $payment->id,
                    'method' => 'recurring',
                    'customer_id' => $customerId
                ]);

                // Update subscription's previous_payment_id to the new Mollie payment
                $subscription->previous_payment_id = $payment->id;
                $subscription->save();

                if ($payment->isPaid()) {
                    $order_obj = new \Order($this->order->id);
                    $order_obj->markPaid(MolliePay::NAME);

                    Log::info('Mollie payment confirmed as paid', [
                        'order_id' => $this->order->id,
                        'payment_id' => $payment->id
                    ]);

                    return true;
                }

                // Payment is open or pending -- webhook will handle final confirmation
                Log::info('Mollie payment pending/open -- awaiting webhook confirmation', [
                    'order_id' => $this->order->id,
                    'payment_id' => $payment->id,
                    'status' => $payment->status
                ]);

                return false;
            } else {
                Log::error('No previous payment ID found for recurring payment', [
                    'order_id' => $this->order->id,
                    'subscription_id' => $subscription->id
                ]);
                return false;
            }
        } catch (\Exception $e) {
            Log::error('Error processing payment: ' . $e->getMessage(), [
                'order_id' => $this->order->id,
                'trace' => $e->getTraceAsString()
            ]);
            return false;
        }
    }

    public function getPreviousPaymentInfo()
    {
        try {
            if (!empty($this->order->subscription_id)) {
                $subscription = \MtcPharmacy\Subscriptions\Classes\Subscription::find($this->order->subscription_id);
                if ($subscription && !empty($subscription->previous_payment_id)) {
                    return $subscription->previous_payment_id;
                }
            }

            // Fallback to looking in order_mollie
            $paymentRecord = \Mtc\Plugins\MolliePay\Classes\OrderMollie::where('order_id', $this->order->id)
                ->first();

            if ($paymentRecord) {
                return $paymentRecord->tr_id;
            }
        } catch (\Exception $e) {
            Log::error('Error getting previous payment ID: ' . $e->getMessage());
        }

        return null;
    }
}