<?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\ViisonPickwareCommon\Subscribers\Api;

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;

class Orders extends Base
{
    /**
     * @see \Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base::getSubscribedEvents()
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Controllers_Api_Orders::indexAction::before' => 'onBeforeIndexAction',
            'Shopware_Controllers_Api_Orders::indexAction::after' => 'onAfterIndexAction',
        ];
    }

    /**
     * Checks the request for a 'filter' parameter on a fake property 'pickwareFullCustomerName', uses this to identify
     * orders where the customer's full name or their company name matches the filter's value and converts this to a
     * filter matching the IDs of those orders.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onBeforeIndexAction(\Enlight_Hook_HookArgs $args)
    {
        /** @var \Shopware_Controllers_Api_Orders $subject */
        $subject = $args->getSubject();

        $request = $subject->Request();
        $filter = $request->getParam('filter');

        if (!is_array($filter)) {
            return;
        }

        // Check for 'full customer name' filter
        $fullCustomerNameFilterIndex = -1;
        foreach ($filter as $index => $filterElement) {
            if (is_array($filterElement) && $filterElement['property'] === 'pickwareFullCustomerName') {
                $fullCustomerNameFilterIndex = $index;
            }
        }

        if ($fullCustomerNameFilterIndex > -1) {
            $query = $filter[$fullCustomerNameFilterIndex]['value'];
            unset($filter[$fullCustomerNameFilterIndex]);
            // Fetch the IDs of all orders whose billing address' name or company match the query
            $orderIds = $this->get('db')->fetchCol(
                'SELECT orderID
                FROM s_order_billingaddress
                WHERE LOWER(CONCAT(firstname, \' \', lastname)) LIKE :query
                OR LOWER(company) LIKE :query',
                [
                    'query' => mb_strtolower($query),
                ]
            );
            if (count($orderIds) > 0) {
                $filter[] = [
                    'property' => 'id',
                    'value' => array_unique($orderIds),
                    'operator' => true,
                ];
            }
        }

        $request->setParam('filter', $filter);
    }

    /**
     * Adds rich information to each of the orders loaded by the main implementation
     * that is required by the Pickware apps.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onAfterIndexAction(\Enlight_Hook_HookArgs $args)
    {
        // Get data
        $data = $args->getSubject()->View()->data;
        if (empty($data)) {
            return;
        }

        $orders = $this->get('viison_pickware_common.rest_api_orders_resource_service')->enrichOrderListData(
            $data,
            $args->getSubject()->Request()
        );

        // Assign changed values
        $args->getSubject()->View()->data = $orders;
    }
}
