<?php

/*
 * @author     M2E Pro Developers Team
 * @copyright  M2E LTD
 * @license    Commercial use is forbidden
 */

class Ess_M2ePro_Model_Ebay_Order_ExternalTransaction_Builder extends Mage_Core_Model_Abstract
{
    //########################################

    public function initialize(array $data)
    {
        // Init general data
        // ---------------------------------------
        $this->setData('order_id', $data['order_id']);
        $this->setData('transaction_id', $data['transaction_id']);
        $this->setData('transaction_date', $data['transaction_date']);
        $this->setData('fee', (float)$data['fee']);
        $this->setData('sum', (float)$data['sum']);
        $this->setData('is_refund', (int)$data['is_refund']);
        // ---------------------------------------
    }

    //########################################

    /**
     * @return Ess_M2ePro_Model_Ebay_Order_ExternalTransaction
     * @throws Exception
     */
    public function process()
    {
        /** @var Ess_M2ePro_Model_Ebay_Order_ExternalTransaction $transaction */
        $transaction = Mage::getModel('M2ePro/Ebay_Order_ExternalTransaction')->getCollection()
            ->addFieldToFilter('order_id', $this->getData('order_id'))
            ->addFieldToFilter('transaction_id', $this->getData('transaction_id'))
            ->getFirstItem();

        foreach ($this->getData() as $key => $value) {
            if ($transaction->getId() && (!$transaction->hasData($key) || $transaction->getData($key) == $value)) {
                continue;
            }

            if ($key === 'transaction_date') {
                $newDate = new DateTime($value, new DateTimeZone('UTC'));
                if ($newDate->format('Y-m-d H:i:s') === $transaction->getData($key)) {
                    continue;
                }
            }

            $transaction->addData($this->getData());
            $transaction->save();
            break;
        }

        return $transaction;
    }

    //########################################
}
