<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Plugin;

use Magento\Quote\Api\Data\PaymentInterface;
use Psr\Log\LoggerInterface;

/**
 * Plugin to save SimplyIN account creation data to payment additional information
 *
 * Sets data on the PaymentInterface object before Magento processes it.
 * No explicit quote save needed — Magento's savePaymentInformation handles persistence.
 */
class SaveSimplyinAccountData
{
    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * @param LoggerInterface $logger
     */
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * Before save payment information and place order - capture SimplyIN data
     *
     * @param \Magento\Checkout\Model\PaymentInformationManagement $subject
     * @param int $cartId
     * @param PaymentInterface $paymentMethod
     * @param \Magento\Quote\Api\Data\AddressInterface|null $billingAddress
     * @return array
     */
    public function beforeSavePaymentInformationAndPlaceOrder(
        \Magento\Checkout\Model\PaymentInformationManagement $subject,
        $cartId,
        PaymentInterface $paymentMethod,
        ?\Magento\Quote\Api\Data\AddressInterface $billingAddress = null
    ) {
        $this->processSimplyinData($paymentMethod);
        return [$cartId, $paymentMethod, $billingAddress];
    }

    /**
     * Before save payment information (without place order)
     *
     * @param \Magento\Checkout\Model\PaymentInformationManagement $subject
     * @param int $cartId
     * @param PaymentInterface $paymentMethod
     * @param \Magento\Quote\Api\Data\AddressInterface|null $billingAddress
     * @return array
     */
    public function beforeSavePaymentInformation(
        \Magento\Checkout\Model\PaymentInformationManagement $subject,
        $cartId,
        PaymentInterface $paymentMethod,
        ?\Magento\Quote\Api\Data\AddressInterface $billingAddress = null
    ) {
        $this->processSimplyinData($paymentMethod);
        return [$cartId, $paymentMethod, $billingAddress];
    }

    /**
     * Process SimplyIN data from payment method additional data
     *
     * Sets simplyin_create_account and simplyin_phone_number on the payment's
     * additional_information. Magento's core will persist this when it saves
     * the payment method to the quote — no explicit cartRepository->save() needed.
     *
     * @param PaymentInterface $paymentMethod
     * @return void
     */
    private function processSimplyinData(PaymentInterface $paymentMethod): void
    {
        try {
            // Skip if this is SimplyIN payment - it handles its own data
            if ($paymentMethod->getMethod() === 'simplyin_payment') {
                return;
            }

            $additionalData = $paymentMethod->getAdditionalData();

            if (!is_array($additionalData)) {
                return;
            }

            $createAccount = $additionalData['simplyin_create_account'] ?? false;
            $phoneNumber = $additionalData['simplyin_phone_number'] ?? null;

            if ($createAccount && $phoneNumber) {
                // Set on the payment object's additional_information
                // Magento will persist this when it processes the payment method
                $paymentMethod->setAdditionalInformation('simplyin_create_account', $createAccount);
                $paymentMethod->setAdditionalInformation('simplyin_phone_number', $phoneNumber);

                $this->logger->info('SimplyIN Plugin: Set account creation data on payment', [
                    'create_account' => $createAccount,
                    'payment_method' => $paymentMethod->getMethod()
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN Plugin Error: ' . $e->getMessage());
        }
    }
}
