<?php

${basename(__FILE__, '.php')} = function () {
    if (
        $this->get_request_method() == "POST"
        and $this->isAuthenticated()
        and isset($this->_request['peer'])
        and !empty($this->_request['peer'])
        and isset($this->_request['email'])
        and !empty($this->_request['email'])
    ) {
        try {
            $wg = new wireguard('wg0');
            $data = [
                "result" => $wg->addPeer($this->_request['peer'],$this->_request['email'])
            ];
            $data = $this->json($data);
            $this->response($data, 200);
        } catch (Exception $e) {
            $data = [
                "error" => $e->getMessage()
            ];
            $data = $this->json($data);
            $this->response($data, 403);
        }
    } else {
        $data = [
            "error" => "Bad request"
        ];
        $data = $this->json($data);
        $this->response($data, 400);
    }
};