<?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 . 'OAuthAuthCode.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'OAuthAccessToken.php';

class AdminMyVetShopCliniqueSSOAppTokenController extends AdminController
{
    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function init(): void
    {
        if (!isset($_GET['code'])) {
            header('HTTP/1.0 Bad Request');
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Aucun AuthCode fourni']);
            exit();
        }

        $authCode = OAuthAuthCode::getByToken($_GET['code']);

        if (!$authCode) {
            header('HTTP/1.0 Bad Request');
            header('Content-Type: application/json');
            echo json_encode(['error' => 'AuthCode fourni invalide']);
            exit();
        } ?>
        <!doctype html>
        <html lang="en">
        <head>
            <meta charset="utf-8">
            <script type="text/javascript">
                window.authcode = <?php echo json_encode(['token' => $authCode->token, 'created' => (int) $authCode->created, 'expires' => (int) $authCode->expires]); ?>;
            </script>
        </head>
        <body style="color: white; background-color: white;">
        <?php echo htmlentities($authCode->token); ?>
        </body>
        </html>
        <?php
        exit();
    }
}
