<?php

declare(strict_types=1);

/**
 * Created by Aurélien RICHAUD (13/02/2018 17:04).
 */
require_once __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'classes' . \DIRECTORY_SEPARATOR . 'OAuthClient.php';
require_once __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'classes' . \DIRECTORY_SEPARATOR . 'OAuthAuthCode.php';

class AdminMyVetShopCliniqueSSOAuthorizationController extends AdminController
{
    public function init(): void
    {
        // ///////////////////////////////////////
        // Enregistre les informations OAuth dans le cookie
        if (Tools::getValue('response_type')) {
            $this->context->cookie->response_type = Tools::getValue('response_type');
        }
        if (Tools::getValue('client_id')) {
            $this->context->cookie->client_id = Tools::getValue('client_id');
        }
        if (Tools::getValue('client_secret')) {
            $this->context->cookie->client_secret = Tools::getValue('client_secret');
        }
        if (Tools::getValue('redirect_uri')) {
            $this->context->cookie->redirect_uri = Tools::getValue('redirect_uri');
        }
        if (Tools::getValue('scope')) {
            $this->context->cookie->scope = Tools::getValue('scope');
        }
        // $this->context->cookie->update();

        // Paramètres obligatoires
        if (!$this->context->cookie->response_type
            || !$this->context->cookie->client_id
            || !$this->context->cookie->redirect_uri
            || !$this->context->cookie->scope) {
            header('HTTP/1.0 400 Bad Request');
            exit;
        }

        try {
            $client = OAuthClient::getByRandomId($this->context->cookie->client_id);
        } catch (PrestaShopDatabaseException $e) {
            $client = null;
        } catch (PrestaShopException $e) {
            $client = null;
        }

        // ///////////////////////////////////////
        // Client invalide
        if (!$client) {
            header('HTTP/1.0 400 Bad Request');
            exit;
        }

        // ///////////////////////////////////////
        // Secret invalide
        /*
        if ( $client->secret != $this->context->cookie->client_secret) {
            header('HTTP/1.0 403 Forbidden');
            exit();
        }*/

        // ///////////////////////////////////////
        // RedirectUri invalide
        if (!in_array($this->context->cookie->redirect_uri, explode(',', $client->redirect_uris))) {
            header('HTTP/1.0 403 Forbidden');
            echo 'redirect_uri invalide' . ($client->redirect_uris . ' .' . $this->context->cookie->redirect_uri);
            exit;
        }

        // ///////////////////////////////////////
        // Force la connexion de l'utilisateur
        if (!isset($this->context->employee) || !$this->context->employee->isLoggedBack()) {
            Tools::redirectAdmin($this->context->link->getAdminLink('AdminLogin') . '&redirect=' . $this->controller_name);
        }

        // ///////////////////////////////////////
        // / Création d'un AuthCode
        try {
            $authCode = new OAuthAuthCode();
            $authCode->client_id = $client->id_oauth_client;
            $authCode->id_employee = $this->context->employee->id;
            $authCode->redirect_uri = $this->context->cookie->redirect_uri;
            $authCode->scope = $this->context->cookie->scope;  /* @phpstan-ignore-line */
            $authCode->created = time();
            $authCode->expires = time() + 15 * 60; // 15 minutes
        } catch (PrestaShopDatabaseException $e) {
            header('HTTP/1.0 500 Internal Server Error');
            exit;
        } catch (PrestaShopException $e) {
            header('HTTP/1.0 500 Internal Server Error');
            exit;
        }

        // Sauvegarde l'AuthCode
        try {
            $authCode->save();
        } catch (PrestaShopException $e) {
            header('HTTP/1.0 500 Internal Server Error');
            exit;
        }

        // ///////////////////////////////////////
        // / Redirrige vers l'URL de retour
        header('Location: ' . $this->context->cookie->redirect_uri . (!str_contains($this->context->cookie->redirect_uri, '?') ? '?' : '&') . 'code=' . $authCode->token);
        exit;
    }
}
