<?php

namespace KupShop\OrderingBundle\Tests\Order;

use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Compat\CtrlLoader;
use KupShop\OrderingBundle\Util\Order\ReplacementUtil;

class ReplacementTest extends \DatabaseTestCase
{
    /** @var ReplacementUtil */
    private $replacement;

    protected function setUp(): void
    {
        parent::setUp();

        // HACK to simulate administration
        global $ctrl;
        $ctrl = (new CtrlLoaderTest($this->get(UserContext::class), $this->get('request_stack')));
        global $txt_str;
        $txt_str = [];

        $this->replacement = $this->get(ReplacementUtil::class);
    }

    public function testReturnAll()
    {
        $order = $this->replacement->createOrder(1);
        $this->replacement->orderChangeStatus(1, $order);

        $query = 'SELECT oi.id id_item, oi.id_product, oi.id_variation, oi.pieces, oi.note, oi.descr, oi.piece_price, oi.total_price, tax, oi.price_buy
	                    FROM '.getTableName('order_items').' oi
	                    WHERE oi.id_order=1 AND oi.total_price > 0';
        $SQL = sqlQuery($query);

        foreach ($SQL as $row) {
            if (!empty($row['id_product'])) {
                $this->replacement->returnItem($order, $row);
            } else {
                $order->insertNonItem($order->id, -$row['total_price'], $row['piece_price'], -$row['pieces'], $row['tax'], $row['descr'], $row['note']);
            }
        }
        $order->recalculate();

        $this->assertEquals(-1692.8, $order->total_price->asFloat());
    }
}

class CtrlLoaderTest extends CtrlLoader
{
    public function field_admin()
    {
        return true;
    }
}
