<?php
namespace EasyChat\Controller;

use EasyChat\Library\EasyTokensGiftProvisioner;
use EasyChat\Model\Setting;

class Provisioning extends Base {

    protected $layouts = 'layoutclean';

    public function index() {
        header('Content-Type: application/json; charset=utf-8');
        header('X-Content-Type-Options: nosniff');
        $this->jsonError(404, 'challenge_not_found');
    }

    public function challenge() {
        header('Content-Type: application/json; charset=utf-8');
        header('X-Content-Type-Options: nosniff');

        $nonce = isset(\EasyChat\Library\RequestContext::get()['nonce']) ? trim((string)\EasyChat\Library\RequestContext::get()['nonce']) : '';
        if ($nonce === '') {
            $this->jsonError(404, 'nonce_required');
        }

        $model_setting = new Setting($this->registry);
        $stored_nonce = trim((string)$model_setting->get('chat_easytokens_gift_challenge_nonce', ''));
        $expires = (int)$model_setting->get('chat_easytokens_gift_challenge_expires', '0');
        if ($stored_nonce === '' || !hash_equals($stored_nonce, $nonce) || $expires < time()) {
            $this->jsonError(404, 'challenge_not_found');
        }

        $install_id = trim((string)$model_setting->get('chat_install_id', ''));
        $install_secret = trim((string)$model_setting->get('chat_install_secret', ''));
        $domain = EasyTokensGiftProvisioner::publicDomain(HTTP_SERVER);
        if ($install_id === '' || $install_secret === '' || $domain === '') {
            $this->jsonError(404, 'challenge_not_ready');
        }

        echo json_encode(array(
            'product' => 'easychat',
            'install_id' => $install_id,
            'domain' => $domain,
            'nonce' => $nonce,
            'signature' => EasyTokensGiftProvisioner::challengeSignature($install_id, $domain, $nonce, $install_secret),
        ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    private function jsonError($status, $code) {
        http_response_code((int)$status);
        echo json_encode(array('success' => false, 'code' => $code), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
}
