<?php

declare(strict_types=1);
/**
 * Created by Aurélien RICHAUD (08/08/2018 17:54).
 */
require_once __DIR__ . \DIRECTORY_SEPARATOR . 'Clinique.php';

class WebserviceSpecificManagementAnimals 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
    {
        require_once __DIR__ . \DIRECTORY_SEPARATOR . 'Animal.php';

        try {
            /** @var WebserviceRequestCore $wsObject */
            $wsObject = $this->getWsObject();

            $id_employee = \method_exists($wsObject, 'getIdEmployee') ? $wsObject->getIdEmployee() : 0;

            $id_animal = null;

            // Récupération de l'id animal
            $urlSegment = $wsObject->urlSegment;

            if (!isset($urlSegment[1]) || !$urlSegment[1] || 0 === (int) $urlSegment[1]) {
                \http_response_code(400);
                exit;
            }

            $id_animal = (int) $urlSegment[1];

            // Récupération de l'animal
            $animal = new Animal($id_animal);

            if (!$animal->id_customer || $animal->deleted) {
                \http_response_code(400);
                exit;
            }

            $customer = new Customer($animal->id_customer);

            // @phpstan-ignore-next-line
            if (!$customer->checkGroup($id_employee)) {
                \http_response_code(400);
                echo \json_encode(['error' => 'Le client n\'appartient pas à la clinique']);
                exit;
            }
            \header('Content-Type: application/json');
            // Modification de la ration uniquement
            if ('PUT' === $wsObject->method) {
                $json = \file_get_contents('php://input');

                if (!$json) {
                    throw new Exception('Une erreur s\'est produite lors de l\'extraction du contenu de la requête');
                }

                $values = \json_decode($json, true);
                if (!\is_array($values)) {
                    $values = [];
                }

                $animal->ration = $values['ration'] ?? '';
                $animal->id_product = $values['id_product'] ?? 0;

                $animal->save();

                echo \json_encode($animal);
                exit;
            } elseif ('DELETE' === $wsObject->method) {
                $animal->deleted = true;
                $result = $animal->update();

                $recommandation = $animal->getRecommandation();

                // Si suppression de l'animal, suppression de la reco associé
                if ($result && $recommandation) {
                    $recommandation->deleted = true;
                    $recommandation->update();
                }

                echo \json_encode($animal);
                exit;
            } elseif ('GET' === $wsObject->method) {
                echo \json_encode($animal);
                exit;
            }
        } catch (Exception $exception) {
            \http_response_code(500);
            \header('Content-Type: application/json');
            echo \json_encode(['error' => $exception->getMessage()]);
            exit;
        }

        \http_response_code(400);
        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);
    }
}
