<?php

declare(strict_types=1);

class WebserviceSpecificManagementOrderReturns implements WebserviceSpecificManagementInterface
{
    /** @var WebserviceOutputBuilderCore */
    protected $objOutput;

    /** @var mixed */
    protected $output;

    /** @var WebserviceRequestCore */
    protected $wsObject;

    public function setObjectOutput(WebserviceOutputBuilderCore $obj)
    {
        $this->objOutput = $obj;

        return $this;
    }

    public function getObjectOutput()
    {
        return $this->objOutput;
    }

    public function setWsObject(WebserviceRequestCore $obj)
    {
        $this->wsObject = $obj;

        return $this;
    }

    public function getWsObject()
    {
        return $this->wsObject;
    }

    public function manage(): void
    {
        /** @var WebserviceRequestCore $wsObject */
        $wsObject = $this->getWsObject();
        $id_employee = method_exists($wsObject, 'getIdEmployee') ? $this->getWsObject()->getIdEmployee() : 0;

        $db = Db::getInstance();

        $returns = $db->executeS(
            'SELECT `od`.* FROM `ps_order_return` `od`
                INNER JOIN `ps_orders` `o` ON `o`.`id_order` = `od`.`id_order`
                INNER JOIN `ps_myvetshop_clinique` `mc` ON `o`.`id_carrier` = `mc`.`id_carrier` OR `o`.`id_carrier` = `mc`.`id_carrier_home`
                WHERE `mc`.`id_employee` = ' . (int) $id_employee . '
                ORDER BY `od`.`id_order_return` DESC'
        );

        $ret = [];

        if (!is_array($returns)) {
            $returns = [];
        }

        foreach ($returns as $return) {
            $orderReturn = new OrderReturn($return['id_order_return']);
            $order = new Order($return['id_order']);
            $return['associations']['order_return_rows'] = $orderReturn->getOrdersReturnProducts($return['id_order_return'], $order);

            $ret[] = $return;
        }

        header('Content-Type: application/json');
        echo json_encode(['order_returns' => $ret]);
        exit();
    }

    /**
     * This must be return an array with specific values as WebserviceRequest expects.
     *
     * @return array
     */
    public function getContent(): array
    {
        return $this->objOutput->getObjectRender()->overrideContent($this->output);
    }
}
