<?php

namespace KupShop\OrderingBundle\Util\Discount;

use KupShop\KupShopBundle\Util\StringUtil;
use Query\Operator;

class CouponExporter
{
    public function getXML(array $couponCodes, $pretty = false)
    {
        $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?> <COUPONS/>');

        foreach ($this->getCoupons($couponCodes) as $couponRow) {
            $couponElement = $xml->addChild('COUPON');
            $this->prepareXML($couponElement, $couponRow);
        }

        if ($pretty === true) {
            return StringUtil::prettyXML($xml->asXML());
        }

        return $xml->asXML();
    }

    public function prepareXML(&$couponElement, $couponRow)
    {
        $couponElement->CODE = $couponRow['code'];
        $couponElement->ID = $couponRow['id'];
        $couponElement->DESCRIPTION = $couponRow['descr'];

        $sourceOrder = $couponElement->addChild('SOURCE_ORDER');
        $sourceOrder->CURRENCY = $couponRow['currency'];
        $sourceOrder->RATE = $couponRow['currency_rate'];
        $sourceOrder->DATE_CREATED = $couponRow['order_date_created'];

        $item = $sourceOrder->addChild('ITEM');
        $item->PRICE = toDecimal($couponRow['piece_price'])->addVat($couponRow['vat'])->asFloat();
        $item->PRICE_WITHOUT_VAT = $couponRow['piece_price'];
        $item->VAT = $couponRow['vat'];
    }

    protected function getCoupons(array $couponCodes)
    {
        return sqlQueryBuilder()
            ->select('dc.*, d.descr, oi.piece_price, oi.tax as vat, o.currency, o.currency_rate, o.date_created as order_date_created')
            ->from('discounts_coupons', 'dc')
            ->join('dc', 'discounts', 'd', 'dc.id_discount = d.id')
            ->leftJoin('dc', 'order_items', 'oi', 'oi.id = dc.id_order_item')
            ->join('oi', 'orders', 'o', 'oi.id_order = o.id')
            ->where(Operator::inStringArray($couponCodes, 'code'))
            ->execute()
            ->fetchAllAssociative();
    }
}
