<?php

namespace MtcPharmacy\Subscriptions\Classes\PaymentGateways;

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Mtc\Modules\Members\Classes\Member;
use MtcPharmacy\Subscriptions\Classes\PaymentGatewayInterface;
use MtcPharmacy\Subscriptions\Classes\Subscription;
use Order;




class StripePaymentGateway extends PaymentGatewayInterface
{

    public function processPayment()
    {
        $new_order = new Order($this->order->id);
        $subscription = Subscription::find($this->order->subscription_id);

        $order_ref = TRANSACTION_PREFIX . $new_order->getId();
        $total_amount = number_format($new_order->getTotalCost(), 2, '.', '');

        // Add order ref for submitting to stripe
        $metadata = [
            'Order Reference' => $order_ref,
            'Order_Id' => $new_order->getId()
        ];

        $member = Member::find($this->order->member);

        // Determine the Stripe secret key from site constants (safe for CLI/cron context)
        if (defined('STRIPE_MTC_TEST') && STRIPE_MTC_TEST === true) {
            $stripeSecretKey = STRIPE_MTC_SECRET_KEY;
        } elseif (defined('STRIPE_LIVE') && STRIPE_LIVE === true) {
            $stripeSecretKey = STRIPE_SECRET_KEY;
        } else {
            $stripeSecretKey = STRIPE_TEST_SECRET_KEY;
        }

        try {

            if ($member->stripe_default_source !== '') {

                $stripe = new \Stripe\StripeClient($stripeSecretKey);

                $idempotencyKey = 'sub_order_' . $this->order->id . '_' . date('Ymd');

                $intent = $stripe->paymentIntents->create([
                    'description' => 'Payment for ' . SITE_NAME . ' order ' . $order_ref,
                    'amount' => $total_amount * 100,
                    'currency' => 'gbp',
                    'customer' => $member->stripe_customer_id,
                    'payment_method' => $member->stripe_default_source,
                    'confirm' => true,
                    'metadata' => $metadata,
                    'automatic_payment_methods' => ['enabled' => true],
                    'use_stripe_sdk' => true,
                    'off_session' => true,
                    'return_url' => SITE_URL . '/shop/checkout/stripe/complete.php',
                ], [
                    'idempotency_key' => $idempotencyKey,
                ]);

            }

            if (isset($intent) && $intent->status === 'succeeded') {
                // Mark order as paid and save stripe charge information
                $new_order->markPaid();
                $new_order->saveStripe([
                    'order_id' => $new_order->getId(),
                    'charge_id' => $intent->id,
                    'order_ref' => $order_ref,
                    'amount' => $total_amount,
                ]);
                // $new_order->postPaymentActions();

                return true;
            } else {
                Event::dispatch('subscriptions.paymentFailed', $subscription);
            }
        } catch (\Exception $e) {
            Log::error('Stripe payment failed: ' . $e->getMessage(), ['exception' => $e]);
            Event::dispatch('subscriptions.paymentFailed', $subscription);
        }

        return false;

    }

    public function getPreviousPaymentInfo()
    {
        return '';
    }
}