<?php

declare(strict_types=1);

require_once __DIR__ . \DIRECTORY_SEPARATOR . 'CliniquePush.php';

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

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

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

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

        return $this;
    }

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

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

        return $this;
    }

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

    public function manage(): void
    {
        $ret = [];

        if ('POST' === $_SERVER['REQUEST_METHOD']) {
            $ret = $this->registerAction();
        }

        echo json_encode($ret, \JSON_PRETTY_PRINT);
        exit;
    }

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    protected function registerAction(): CliniquePush
    {
        $id_employee = method_exists($this->getWsObject(), 'getIdEmployee') ? $this->getWsObject()->getIdEmployee() : 0;
        $clinique = Clinique::getCliniqueByEmployeeId((int) $id_employee);

        if (!$clinique->id) {
            http_response_code(500);

            throw new Exception();
        }

        $pushId = Tools::getValue('push_id');
        $pushType = Tools::getValue('push_type');
        $accessToken = OAuthAccessToken::getByToken(Tools::getValue('access_token'));

        if (!$pushId || !$pushType || !$accessToken) {
            http_response_code(400);

            throw new Exception();
        }

        $cliniquePush = CliniquePush::getCLiniquePushByToken($pushId);

        if (!$cliniquePush) { // création d'une clinique push à partir d'un id push
            $cliniquePush = new CliniquePush();
            $cliniquePush->push_id = $pushId;
            $cliniquePush->push_type = $pushType;
            $cliniquePush->id_oauth_access_token = (int) $accessToken->id;
            $cliniquePush->save();
        } else { // Modification de l'id push
            $cliniquePush->id_oauth_access_token = (int) $accessToken->id;
            $cliniquePush->update();
        }

        return $cliniquePush;
    }

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