<?php

declare(strict_types=1);

/**
 * Created by Aurélien RICHAUD (31/07/2019 11:00)
 */
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'OAuthAccessToken.php';

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

    /**
     * @var OAuthAccessToken|null
     */
    protected $accessToken = null;

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function init(): void
    {
        header('Content-Type: application/json');

        $token = OAuthAccessToken::getTokenFromRequest();
        if (!$token) {
            header('HTTP/1.0 403 Forbidden');
            echo json_encode(['error' => 'No authorization'], JSON_PRETTY_PRINT);
            exit();
        }

        $accessToken = OAuthAccessToken::getByToken($token);

        if (!$accessToken) {
            header('HTTP/1.0 403 Forbidden');
            echo json_encode(['error' => 'Non-existant token'], JSON_PRETTY_PRINT);
            exit();
        }

        if ($accessToken->expires < time()) {
            header('HTTP/1.0 403 Forbidden');
            echo json_encode(['error' => 'Expired token'], JSON_PRETTY_PRINT);
            exit();
        }

        if (!$accessToken->id_customer) {
            header('HTTP/1.0 403 Forbidden');
            echo json_encode(['error' => 'No customer associated with token'], JSON_PRETTY_PRINT);
            exit();
        }

        // Chargement du Customer
        $customer = new Customer($accessToken->id_customer);
        $this->context->cookie->id_customer = (int) ($customer->id);
        $this->context->cookie->customer_lastname = $customer->lastname;
        $this->context->cookie->customer_firstname = $customer->firstname;
        $this->context->cookie->logged = 1;
        $this->context->cookie->mobile_app = 1;
        $customer->logged = true;
        $this->context->cookie->is_guest = $customer->isGuest();
        $this->context->cookie->passwd = $customer->passwd;
        $this->context->cookie->email = $customer->email;

        if (!$this->context->cookie->isSessionAlive()) {
            $this->context->cookie->registerSession(new CustomerSession());
        }

        // Add customer to the context
        $this->context->customer = $customer;

        // Enregistre le token dans le Controller
        $this->accessToken = $accessToken;

        parent::init();
    }
}
