<?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 */
    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
    {
        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();

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

        $orderId = intval(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::getCliniqueByCarrier((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
     */
    public function getContent(): array
    {
        return $this->objOutput->getObjectRender()->overrideContent($this->output);
    }
}
