<?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
        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');
        }
        $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');
            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');
            $this->ajaxDie(
                Tools::jsonEncode(
                    [
                        'errors' => ['client not found'],
                    ]
                )
            );
        }

        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->ajaxDie(Tools::jsonEncode($return));
        }

        $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->ajaxDie(
                Tools::jsonEncode(
                    [
                        'errors' => ['La date d\'ajout du client n\'a pu être instanciée'],
                    ]
                )
            );
            exit();
        }

        $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');
            exit();
        }

        /////////////////////////////////////////
        /// 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->scope = $this->context->cookie->scope;
            $authCode->created = time();
            $authCode->expires = time() + 15 * 60; // 15 minutes
        } catch (PrestaShopDatabaseException $e) {
            header('HTTP/1.0 500 Internal Server Error');
            $this->ajaxDie(
                Tools::jsonEncode(
                    [
                        'errors' => [$e->getMessage()],
                    ]
                )
            );
        } catch (PrestaShopException $e) {
            header('HTTP/1.0 500 Internal Server Error');
            $this->ajaxDie(
                Tools::jsonEncode(
                    [
                        'errors' => [$e->getMessage()],
                    ]
                )
            );
        }

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

        /////////////////////////////////////////
        /// Redirrige vers l'URL de retour
        $this->ajaxDie(
            Tools::jsonEncode(
                [
                    'authcode' => $authCode->token,
                    'created' => $authCode->created,
                    'expires' => $authCode->expires,
                ]
            )
        );
    }
}
