<?php

declare(strict_types=1);

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

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

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

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

        return $this;
    }

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

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

        return $this;
    }

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

    public function manage(): void
    {
        /** @var WebserviceRequestCore $wsObject */
        $wsObject = $this->getWsObject();
        $id_employee = \method_exists($wsObject, 'getIdEmployee') ? $wsObject->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<mixed>|string
     */
    public function getContent()
    {
        if (!$this->objOutput) {
            return [];
        }

        return $this->objOutput->getObjectRender()->overrideContent($this->output);
    }
}
