<?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;

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function init(): void
    {
        \assert(null !== $this->context->cookie);

        \header('Content-Type: application/json');

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

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

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

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

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

        // Rechargement de la session uniquement si besoin (sinon c'est géré dans la classe Cookie !)
        if ((int) $this->context->cookie->id_customer !== (int) $accessToken->id_customer) {
            // 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 = true;
            $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
            if (!$this->context->cart && empty($this->cookie->id_cart)) {
                $cart = new Cart();
                $cart->id_lang = (int) $this->context->cookie->id_lang;
                $cart->id_currency = (int) $this->context->cookie->id_currency;
                $cart->id_guest = (int) $this->context->cookie->id_guest;
                $cart->id_shop_group = $this->context->shop?->id_shop_group ?? 1;
                $cart->id_shop = $this->context->shop?->id ?? 1;
                $cart->id_customer = (int) $customer->id;
                $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);
                $cart->id_address_invoice = (int) $cart->id_address_delivery;
                $this->context->cart = $cart;
            }
            $this->context->updateCustomer($customer);
        }

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

        parent::init();
    }
}
