<?php

declare(strict_types=1);

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

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

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

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

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

        return $this;
    }

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

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

        return $this;
    }

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

    public function manage(): void
    {
        if (!defined('_PS_PICKUP_SIGNATURES_IMG_DIR_')) {
            \define('_PS_PICKUP_SIGNATURES_IMG_DIR_', _PS_IMG_DIR_ . 'pickup_signatures/');
        }
        if (!\is_dir(_PS_PICKUP_SIGNATURES_IMG_DIR_)) {
            \mkdir(_PS_PICKUP_SIGNATURES_IMG_DIR_);
        }

        /** @var WebserviceRequestCore $wsObject */
        $wsObject = $this->getWsObject();
        \assert($wsObject instanceof AppWebserviceRequest);

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

        $orderId = (int) \str_replace(['pickup_signatures/', 'pickup_signatures'], ['', ''], $_REQUEST['url']);
        $ret = [];

        // Si pas d'ID fourni, on ne fait rien !
        if (!$orderId) {
            $ret = [
                'errors' => [
                    ['code' => 0, 'message' => "Vous devez spécifier un ID de commande dans l'URL"],
                ],
            ];
            \header('Content-Type: application/json');
            echo \json_encode($ret);
            exit;
        }

        $order = new \Order($orderId);

        // Vérification de sécurité
        $clinique = new \Clinique(\Clinique::getCliniqueIdByCarrier((int) $order->id_carrier));

        if ($clinique->id_employee != $id_employee) {
            $ret = [
                'errors' => [
                    ['code' => 0, 'message' => "Vous n'avez pas accès à cette commande"],
                ],
            ];
            \header('Content-Type: application/json');
            echo \json_encode($ret);
            exit;
        }

        switch ($_SERVER['REQUEST_METHOD']) {
            case 'GET':
                if (\is_file(_PS_PICKUP_SIGNATURES_IMG_DIR_ . $order->id . '.png')) {
                    \header('Content-Type: text/plain');
                    echo(
                        \Tools::usingSecureMode()
                            ? \Tools::getShopDomainSSL(true)
                            : \Tools::getShopDomain(true)
                    ) . '/img/pickup_signatures/' . $order->id . '.png';
                    exit;
                } else {
                    \header('Content-Type: text/plain');
                    exit;
                }

                // no break
            case 'POST':
                $content = (string) \file_get_contents('php://input');

                // Ecriture du fichier PNG
                if (0 === \strpos($content, 'data:image/png;base64,')) {
                    \file_put_contents(
                        _PS_PICKUP_SIGNATURES_IMG_DIR_ . $order->id . '.png',
                        (string) \file_get_contents($content)
                    );
                    $ret = ['success' => true];
                }
                break;
        }

        \header('Content-Type: application/json');
        echo \json_encode($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);
    }
}
