<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonSetArticles\Subscribers\Frontend;

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;
use Shopware\Plugins\ViisonSetArticles\Components\PluginConfigService;

/**
 * This Subscriber manipulates Shopware Frontend Account view. Use deactivated unfolding of set articles if configured.
 */
class AccountSubscriber extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Controllers_Frontend_Account::ordersAction::after' => 'editAccountOrderList',
        ];
    }

    /**
     * Manipulates frontend account/orders view. Hides sub articles if set articles unfolding is disabled. If sub
     * articles are shown, hide their regular prices (regular price and price per unit) by clearing the value fields.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function editAccountOrderList(\Enlight_Hook_HookArgs $args)
    {
        /** @var PluginConfigService $pluginConfigService */
        $pluginConfigService = $this->get('viison_set_articles.plugin_config');
        $hideSubArticles = $pluginConfigService->getDisplaySubArticlesOnDocuments() !== PluginConfigService::ALWAYS_SHOW_SUB_ARTICLES_ON_DOCUMENTS;
        $openOrders = $args->getSubject()->View()->sOpenOrders;
        foreach ($openOrders as &$order) {
            $filteredOrderDetails = [];
            foreach ($order['details'] as $orderDetail) {
                $orderDetailAttributes = $this->getOrderDetailAttributes($orderDetail['id']);

                // Clear prices of sub articles so the price fields are disabled in the frontend
                if ($orderDetailAttributes['isSubArticle']) {
                    $orderDetail['price'] = null;
                    $orderDetail['currentPrice'] = null;
                    $orderDetail['currentHas_pseudoprice'] = null;
                    $orderDetail['referenceunit'] = null; // Also hide price per unit
                }

                // Keep position if sub articles are not hidden, or position is not a sub article
                if (!$hideSubArticles || !$orderDetailAttributes['isSubArticle']) {
                    $filteredOrderDetails[] = $orderDetail;
                }
            }
            $order['details'] = $filteredOrderDetails;
        }
        // Set view changes
        $args->getSubject()->View()->sOpenOrders = $openOrders;
    }

    /**
     * Fetches information (attributes) for a specific OrderDetail item
     *
     * @param int $orderDetailId
     * @return array
     */
    private function getOrderDetailAttributes($orderDetailId)
    {
        $row = $this->get('db')->fetchRow(
            'SELECT
			  detailID,
			  viison_setarticle_orderid
			  FROM s_order_details_attributes
			  WHERE detailID = "' . $orderDetailId . '"'
        );
        $row['isSubArticle'] = ($row['viison_setarticle_orderid'] && ($row['detailID'] != $row['viison_setarticle_orderid']));

        return $row;
    }
}
