<?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\ViisonPickwareMobile\Classes\ApiRequestCompatibility;

use DateTime;
use Shopware\Plugins\ViisonPickwareCommon\Classes\ApiRequestCompatibility\Layer;

class Variants20181216 extends Layer
{
    /**
     * @inheritdoc
     */
    public function getVersion()
    {
        return '2018-12-16';
    }

    /**
     * Checks the `filter` request parameter for a `lastStocktake` item and, if found, replaces it with the result of a
     * query that results in the IDs of all article details that need stocktaking.
     *
     * pre GET /api/variants
     */
    public function preIndexAction()
    {
        $filter = $this->request->getParam('filter', []);

        // Check for a `lastStocktake` filter
        $lastStocktakeFilterKey = null;
        foreach ($filter as $key => $filterElement) {
            if ($filterElement['property'] === 'lastStocktake') {
                $lastStocktakeFilterKey = $key;
                break;
            }
        }
        $warehouseId = $this->request->getParam('warehouseId', null);
        if ($lastStocktakeFilterKey !== null && $warehouseId) {
            // Evaluate the filter
            $noStocktakeSince = new DateTime($filter[$lastStocktakeFilterKey]['value']);
            $variantIds = $this->get('db')->fetchCol(
                'SELECT DISTINCT `articleDetails`.`id`
                 FROM `s_articles_details` AS `articleDetails`
                     INNER JOIN `s_articles_attributes` AS `attributes`
                        ON `attributes`.`articledetailsID` = `articleDetails`.`id`
                     LEFT JOIN `pickware_erp_bin_locations` AS `binLocations`
                        ON `binLocations`.`warehouseId` = :warehouseId
                     LEFT JOIN `pickware_erp_article_detail_bin_location_mappings` AS `binLocationMappings`
                        ON
                            `binLocationMappings`.`articleDetailId` = `articleDetails`.`id`
                            AND `binLocationMappings`.`binLocationId` = `binLocations`.`id`
                 WHERE
                     `attributes`.`pickware_stock_management_disabled` != 1
                     AND `binLocationMappings`.`id` IS NOT NULL
                     AND (
                         `binLocationMappings`.`lastStocktake` IS NULL
                         OR `binLocationMappings`.`lastStocktake` <= :noStocktakeSince
                     )',
                [
                    'noStocktakeSince' => $noStocktakeSince->format('Y-m-d'),
                    'warehouseId' => $warehouseId,
                ]
            );
            // Replace the original 'lastStocktake' filter element with one that filters the variant IDs
            $filter[$lastStocktakeFilterKey] = [
                'property' => 'id',
                'value' => (count($variantIds) > 0) ? $variantIds : 0,
            ];
        }

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