<?php

$loader = $this->registry->get('load');
$loader->controller('payment/payment_info');

class ControllerPaymentPagseguroAPILib extends ControllerPaymentPaymentInfo
{

    public function load()
    {
        $this->load->dmodel('checkout/order');

        $language = $this->language->load('payment/pagseguro_api');
        $this->data = array_merge($this->data, $language);

        $this->data['back'] = $this->url->link('checkout/checkout', '', 'SSL');
        $this->data['continue'] = $this->url->link('checkout/success');
    }

    public function getOrder()
    {
        $this->load->dmodel('checkout/order');

        $this->order_info = $this->dmodel_checkout_order->getOrder($this->session->data['order_id']);

        $this->dmodel_checkout_order->confirm($this->order_info['order_id'], $this->config->get('pagseguro_api_order_status_pending'), '');

        return $this->order_info;
    }

    public function getTransactionInfo($payment_type)
    {
        parent::setPaymentInfo();
        parent::setPaymentProducts();

        $order_id = $this->order_info['order_id'];
        $phoneType = $this->paymentInfo->getTelefone()->tipo == Type_PaymentPhone::Tp_Celular ? 'MOBILE' : 'BUSINESS';

        $phoneData = array(
            'country' => Type_CountryCode::Tp_Brazil,
            'area' => preg_replace("/[^0-9]/", "", $this->paymentInfo->getTelefone()->ddd),
            'number' => preg_replace("/[^0-9]/", "", $this->paymentInfo->getTelefone()->telefone),
            'type' => $phoneType,
        );

        $customerData = array(
            'name' => $this->paymentInfo->getNome(),
            'email' => $this->paymentInfo->getEmail(),
            'tax_id' => $this->paymentInfo->getDocumento()->numero,
            'phones' => [$phoneData],
        );

        $productData = [];
        foreach ($this->paymentInfo->getProducts() as $product) {
            $productData[] = array(
                'reference_id' => $product->getId(),
                'name' => $product->getDescricao(),
                'quantity' => $product->getQuantity(),
                'unit_amount' => (integer)(number_format($product->getPrice(), 2, '.', '')*100)
            );
        }

        $shippingAddress = array(
            'postal_code' => $this->paymentInfo->getShippingAddress()->getPostcode(),
            'street' => $this->paymentInfo->getShippingAddress()->getRua(),
            'number' => $this->paymentInfo->getShippingAddress()->getNumero(),
            'complement' => $this->paymentInfo->getShippingAddress()->getComplemento() ?? 'não informado',
            'locality' => $this->paymentInfo->getShippingAddress()->getBairro(),
            'city' => $this->paymentInfo->getShippingAddress()->getCidade(),
            'region_code' => $this->paymentInfo->getShippingAddress()->getUf(),
            'region' => $this->paymentInfo->getShippingAddress()->getUfName(),
            'country' => Type_mktCountryIso3::Tp_PaisBrasil,
        );

        $notification_url = $this->urlloja->link('', '', 'NONSSL', false) . 'pagseguroapicallback';

        $value = $this->paymentInfo->getParam('amount')*100;
        $amount = array(
            'value' => intval("$value"), // Preço em centavos, essas aspas na variavel é necessário porque o PHP tem um bug pra converter float para integer :[
            'currency' => Type_CodigoMoeda::Tp_MoedReal,
        );

        $data = array(
            'reference_id' => $order_id,
            'customer' => $customerData,
            'items' => $productData,
            'shipping' => ['address' => $shippingAddress],
            'notification_urls' => [$notification_url],
        );

        $payment_method = $this->getPaymentMethod($payment_type, $data);

        $charges = [
            'reference_id' => $order_id,
            'description' => 'Pedido ' . $order_id,
            'amount' => $amount,
            'payment_method' => $payment_method,
            'notification_urls' => [$notification_url],
        ];

        $data['charges'] = [$charges];

        return $data;
    }

    private function getPaymentMethod($payment_type, $data)
    {
        switch ($payment_type) {
            case Type_PaymentOption::Tp_CreditCard:
            {
                parent::setPaymentCreditCard();
//                $card = [
//                    'number' => $this->paymentInfo->getCreditCard()->getNumero(),
//                    'exp_month' => $this->paymentInfo->getCreditCard()->getDataExp()->mes,
//                    'exp_year' => $this->paymentInfo->getCreditCard()->getDataExp()->ano,
//                    'security_code' => $this->paymentInfo->getCreditCard()->getCodigo(),
//                    'holder' => ['name' => $data['customer']['name']],
//                    'store' => false,
//                ];
                return [
                    'type' => Type_PagseguroPagamento::Tp_CreditCard,
                    'installments' => $this->paymentInfo->getCreditCard()->getParcelas(),
                    'capture' => true,
//                    'card' => $card,
                ];
            }
            case Type_PaymentOption::Tp_Billet:
            {
                $dueDateDays = ($this->config->get('pagseguro_api_billet')['validade'] ? $this->config->get('pagseguro_api_billet')['validade'] : 3);
                $dueDate = new DateTime();
                $dueDate->add(new DateInterval('P' . $dueDateDays . 'D'));
                $dueDate = $dueDate->format('Y-m-d');

                $billingAddress = array(
                    'postal_code' => $this->paymentInfo->getPaymentAddress()->getPostcode(),
                    'street' => $this->paymentInfo->getPaymentAddress()->getRua(),
                    'number' => $this->paymentInfo->getPaymentAddress()->getNumero(),
                    'complement' => $this->paymentInfo->getPaymentAddress()->getComplemento() ?? '',
                    'locality' => $this->paymentInfo->getPaymentAddress()->getBairro(),
                    'city' => $this->paymentInfo->getPaymentAddress()->getCidade(),
                    'region_code' => $this->paymentInfo->getPaymentAddress()->getUf(),
                    'region' => $this->paymentInfo->getPaymentAddress()->getUfName(),
                    'country' => Type_mktCountryIso3::Tp_PaisBrasil,
                );
                $holder = [
                    'name' => $this->paymentInfo->getNome(),
                    'tax_id' => $this->paymentInfo->getDocumento()->numero,
                    'email' => $this->paymentInfo->getEmail(),
                    'address' => $billingAddress,
                ];
                $boleto = [
                    'due_date' => $dueDate,
//                    'instruction_lines' => $instruction_lines,
                    'holder' => $holder,
                ];
                return [
                    'type' => Type_PagseguroPagamento::Tp_Billet,
                    'boleto' => $boleto,
                ];
            }
        }
    }

}
