<?php

declare(strict_types=1);
/**
 * Created by Aurélien RICHAUD (31/01/2019 11:03).
 */
require_once __DIR__
    . \DIRECTORY_SEPARATOR . '..'
    . \DIRECTORY_SEPARATOR . '..'
    . \DIRECTORY_SEPARATOR . 'classes' . \DIRECTORY_SEPARATOR . 'OAuthAccessToken.php';
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 . 'OAuthClient.php';

class MyvetshopcliniqueRegisterModuleFrontController extends FrontController
{
    /**
     * @var bool
     */
    public $auth = false;
    /**
     * @var bool
     */
    public $ssl = true;

    public function init(): void
    {
        // Enregistre les informations OAuth dans le cookie
        $clientId = strval(\Tools::getValue('client_id'));
        if ($clientId) {
            $this->context->cookie->client_id = $clientId;
        }
        $clientSecret = \strval(\Tools::getValue('client_secret'));
        if ($clientSecret) {
            $this->context->cookie->client_secret = $clientSecret;
        }
        $this->context->cookie->update();

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

            return;
        }

        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');
            $this->ajaxRender(
                \json_encode(
                    [
                        'errors' => ['client not found'],
                    ]
                ) ?: null
            );
            exit;
        }

        parent::init();

        // Vérifie que l'utilisateur est connecté
        if (!$this->context->customer->id) {
            \header('HTTP/1.0 403 Forbidden');
            $return = [
                'errors' => ['Not connected'],
            ];
            $this->ajaxRender(\json_encode($return) ?: null);
        }

        $dateAdd = DateTime::createFromFormat('Y-m-d H:i:s', $this->context->customer->date_add);

        if (!$dateAdd) {
            \header('HTTP/1.0 500 Internal Server Error');
            $this->ajaxRender(
                \json_encode(
                    [
                        'errors' => ['La date d\'ajout du client n\'a pu être instanciée'],
                    ]
                ) ?: null
            );

            return;
        }

        $createdInterval = (new DateTime('now'))->diff($dateAdd);

        // Si le compte a été créé il y a plus de 15 minutes
        // cette méthode d'authentification n'est plus possible !
        // L'utilisateur est alors déconnecté de force
        if ($createdInterval->y > 0
            || $createdInterval->m > 0
            || $createdInterval->d > 0
            || $createdInterval->h > 0
            || $createdInterval->i >= 15) {
            $this->context->customer->mylogout();
            \Tools::redirect('/connexion?back=my-account&mobile_app=1');

            return;
        }

        // Création d'un AuthCode
        $redirectUris = \explode(',', $client->redirect_uris);
        try {
            $authCode = new OAuthAuthCode();
            $authCode->client_id = $client->id_oauth_client;
            $authCode->id_customer = $this->context->customer->id;
            $authCode->redirect_uri = count($redirectUris) ? $redirectUris[0] : '';
            $authCode->created = time();
            $authCode->expires = time() + 15 * 60; // 15 minutes
        } catch (\PrestaShopException $e) {
            \header('HTTP/1.0 500 Internal Server Error');
            $this->ajaxRender(
                \json_encode(
                    [
                        'errors' => [$e->getMessage()],
                    ]
                ) ?: null
            );

            return;
        }

        // Sauvegarde l'AuthCode
        try {
            $authCode->save();
        } catch (\PrestaShopException $e) {
            \header('HTTP/1.0 500 Internal Server Error');
            $this->ajaxRender(
                \json_encode(
                    [
                        'errors' => [$e->getMessage()],
                    ]
                ) ?: null
            );

            return;
        }

        // Redirrige vers l'URL de retour
        $this->ajaxRender(
            \json_encode(
                [
                    'authcode' => $authCode->token,
                    'created' => $authCode->created,
                    'expires' => $authCode->expires,
                ]
            ) ?: null
        );
    }

    /**
     * Réécriture de la méthode display (pas besoin de rendre un template, le controller doit etre utilisé en ajax
     */
    public function display(): bool
    {
        return true;
    }
}
