<?php

namespace MercadoPago\Woocommerce\Transactions;

use Exception;
use MercadoPago\Woocommerce\Gateways\AbstractGateway;
use MercadoPago\Woocommerce\Helpers\Numbers;
use MercadoPago\PP\Sdk\Entity\Payment\Payment;
use WC_Order;

abstract class AbstractPaymentTransaction extends AbstractTransaction
{
    /**
     * @var Payment
     */
    public $transaction;

    /**
     * Payment Transaction constructor
     * @throws Exception
     */
    public function __construct(AbstractGateway $gateway, WC_Order $order, array $checkout)
    {
        parent::__construct($gateway, $order, $checkout);

        $this->transaction = $this->getSdk()->getPaymentInstance();

        $this->setCommonTransaction();
        $this->setPayerTransaction();
        $this->setAdditionalInfoTransaction();

        $this->transaction->description        = implode(', ', $this->listOfItems);
        $this->transaction->transaction_amount = Numbers::format($this->orderTotal);
    }

    /**
     * Create Payment
     *
     * @return array
     * @throws Exception
     */
    public function createPayment()
    {
        $this->logTransactionPayload();
        if (!empty($this->checkout['session_id'])) {
            $this->transaction->session_id = $this->checkout['session_id'];
        }

        $apiRoute = $this->transaction->getUris()['post'] ?? 'unknown';

        try {
            $data = $this->transaction->save();
            $this->mercadopago->logs->file->info('Payment created', $this->gateway::LOG_SOURCE, $data);
            $this->sendPaymentCreateResultMetric($apiRoute, null, $data);
            return $data;
        } catch (Exception $e) {
            $this->sendApiErrorMetric($apiRoute, $e);
            $this->sendPaymentCreateResultMetric($apiRoute, $e);
            throw $e;
        }
    }

    /**
     * Set payer transaction
     *
     * @return void
     */
    public function setPayerTransaction(): void
    {
        $payer             = $this->transaction->payer;
        $payer->email      = $this->mercadopago->orderBilling->getEmail($this->order);
        $payer->first_name = $this->mercadopago->orderBilling->getFirstName($this->order);
        $payer->last_name  = $this->mercadopago->orderBilling->getLastName($this->order);

        $this->setPayerAddressInfo();
    }

    private function setPayerAddressInfo(): void
    {
        $this->transaction->payer->address->city         = $this->mercadopago->orderBilling->getCity($this->order);
        $this->transaction->payer->address->federal_unit = $this->mercadopago->orderBilling->getState($this->order);
        $this->transaction->payer->address->zip_code     = $this->mercadopago->orderBilling->getZipcode($this->order);
        $this->transaction->payer->address->street_name  = $this->mercadopago->orderBilling->getFullAddress($this->order);
    }
}
