<?php

/**
 *
 * @category MultiSafepay
 * @package  MultiSafepay_Msp
 */
require_once Mage::getModuleDir('', 'MultiSafepay_Msp') . DS . 'Model' . DS . 'Api' . DS . 'Client.php';

class MultiSafepay_Msp_Model_Observer_Shipment extends MultiSafepay_Msp_Model_Observer_Abstract
{
    public function sales_order_shipment_save_after(Varien_Event_Observer $observer)
    {
        /** @var $event Varien_Event */
        $event = $observer->getEvent();

        /** @var $shipment Mage_Sales_Model_Order_Shipment */
        $shipment = $event->getShipment();

        /** @var $order Mage_Sales_Model_Order */
        $order = $shipment->getOrder();

        /** @var $payment Mage_Payment_Model_Method_Abstract */
        $payment = $order->getPayment()->getMethodInstance();

        // Skip if payment method is not from MultiSafepay
        if (!$payment instanceof MultiSafepay_Msp_Model_Gateway_Abstract) {
            return $this;
        }

        // Check order's payment method is enabled now
        if (!in_array($payment->getCode(), $this->_getAllActivePaymentMethods($order->getStoreId()))) {
            return $this;
        }

        $invoiceId = $order->getInvoiceCollection()->getFirstItem()->getIncrementId();

        /** @var $checkout MultiSafepay_Msp_Model_Checkout */
        $checkout = Mage::getModel('msp/checkout');

        /** @var $base MultiSafepay_Msp_Model_Base */
        $base = $checkout->getBase($order->getId());

        $configGateway  = Mage::getStoreConfig('msp/settings', $order->getStoreId());

        $msp = new Client();

        if (in_array($payment->getCode(), array('msp_payafter', 'msp_einvoice', 'msp_klarna'))) {
            $settings = Mage::getStoreConfig('msp_gateways/' . $order->getPayment()->getMethodInstance()->getCode(), $order->getStoreId());

            $isTest = $settings['test_api_pad'] === 'test';
            $msp->setTestMode($isTest);

            $apiKey = $isTest ? $settings['api_key_pad_test'] : $settings['api_key_pad'];
            $msp->setApiKey($apiKey);
        } else {
            $isTest = $configGateway['test_api'] === 'test';
            $msp->setTestMode($isTest);
            $msp->setApiKey($configGateway['api_key']);
        }

        $msp->setDebug($configGateway['debug']);

        $mspShipmentData = [
            'invoice_id' => $invoiceId,
            'ship_date' => date('Y-m-d H:i:s'),
            'carrier' => $order->getShippingDescription(),
        ];

        if ($trackings = Mage::app()->getRequest()->getParam('tracking')) {
            $trackingNumbers = '';
            foreach ($trackings as $tracking) {
                $trackingNumbers .= $tracking['title'] . '|' . $tracking['number'] . ';';
            }
            $mspShipmentData['tracktrace_code'] = trim($trackingNumbers, ';');
        } else {
            $mspShipmentData['tracktrace_code'] = '';
        }

        $base->log("Invoice id: $invoiceId, Order id: {$order->getId()}, Transaction id: {$order->getIncrementId()}");

        // Send update JSON
        $endpoint = 'orders/' . $order->getIncrementId();
        try {
            $result = $msp->orders->patch($mspShipmentData, $endpoint);
        } catch (Exception $exception) {
            $base->log('Error ' . $exception->getMessage());
        }

        if ($result) {
            Mage::getSingleton('adminhtml/session')->addNotice(Mage::helper('msp')->__('The order has been successfully set to shipped within your MultiSafepay transaction, the process continues.'));
            if ($order->getPayment()->getMethodInstance()->getCode() == 'msp_klarna') {
                $mspDetails = $msp->orders->get('orders', $order->getIncrementId());

                $order->addStatusToHistory($order->getStatus(), Mage::helper('msp')->__('Klarna Invoice: ') . '<br /><a href="https://online.klarna.com/invoices/' . $mspDetails->payment_details->external_transaction_id . '.pdf">https://online.klarna.com/invoices/' . $mspDetails->payment_details->external_transaction_id . '.pdf</a>');
                $order->save();
            }
        } else {
            Mage::getSingleton('adminhtml/session')->addError($exception->getMessage());
        }

        return $this;
    }
}
