<?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.

use Shopware\Models\Attribute\Order as OrderAttribute;
use Shopware\Plugins\ViisonCommon\Classes\ApiException;

/**
 * This controller provides the custom 'pickingBoxes' API resource and all its available actions.
 */
class Shopware_Controllers_Api_ViisonPickwareMobilePickingBoxes extends Shopware_Controllers_Api_Rest
{
    /**
     * GET /api/pickingBoxes
     */
    public function indexAction()
    {
        // Fetch all used picking box IDs
        $result = $this->get('db')->fetchAll(
            'SELECT orderID AS orderId, pickware_batch_picking_box_id AS boxId
            FROM s_order_attributes
            WHERE pickware_batch_picking_box_id != \'\'
            AND pickware_batch_picking_box_id IS NOT NULL'
        );

        // Format the result
        $boxes = array_map(
            function ($row) {
                return [
                    'id' => intval($row['boxId']),
                    'assignedOrderId' => intval($row['orderId']),
                ];
            },
            $result
        );

        $this->View()->assign([
            'success' => true,
            'data' => $boxes,
            'total' => count($boxes),
        ]);
    }

    /**
     * PUT /api/pickingBoxes/{id}
     */
    public function putAction()
    {
        // The the request parameters
        $boxId = $this->Request()->getParam('id');
        if (!$boxId) {
            throw new ApiException('bad_request/id', 400);
        }

        // Update the assignmend
        $changedEntities = [];
        $post = $this->Request()->getPost();
        if (array_key_exists('assignedOrderId', $post)) {
            // Try to find an order (attribute) using the box ID
            $orderAttribute = $this->get('models')->getRepository(OrderAttribute::class)->findOneBy([
                'pickwareBatchPickingBoxId' => $boxId,
            ]);

            // Remove the current assigment if necessary
            if ($orderAttribute && $orderAttribute->getOrder()->getId() != $post['assignedOrderId']) {
                $orderAttribute->setPickwareBatchPickingBoxId(null);
                $changedEntities[] = $orderAttribute;
            }

            // Add a new assignment if necessary
            if ($post['assignedOrderId']) {
                $orderAttribute = $this->get('models')->getRepository(OrderAttribute::class)->findOneBy([
                    'orderId' => $post['assignedOrderId'],
                ]);
                if (!$orderAttribute) {
                    throw new ApiException('not_found/order', 404);
                }
                $orderAttribute->setPickwareBatchPickingBoxId($boxId);
                $changedEntities[] = $orderAttribute;
            }
        }

        // Save changes
        $this->get('models')->flush($changedEntities);

        $this->View()->assign([
            'success' => true,
        ]);
    }
}
