<?php

namespace api\classes;

use api\classes\API;
use api\classes\API_users;
use JetBrains\PhpStorm\NoReturn;

require_once 'API.php';

class API_apitoken extends API
{
    public function getTokens()
    {
        $query = "SELECT * FROM system_api_tokens WHERE system_api_tokens.user_uuid = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('s', $this->data['user_uuid']);
        $this->executeStatement($stmt);

        $result = $stmt->get_result();
        $tokens = [];

        while ($row = $result->fetch_assoc()) {
            $tokens[] = $row;
        }

        return $tokens;
    }

    public function getUserTokens($returnBoolean = false)
    {
        list($query, $types, $params) = $this->buildDynamicQuery('system_api_tokens');

        $items = $this->generalGetFunction($query, $types, $params, $returnBoolean, 'User');

        return $items;
    }

    public function checkTokenPermissions()
    {
        # First we need to find to what user the api_token belongs to if it's not given.
        # If the user_uuid is unknown, get the user_uuid based on the api_token_being.
        if (!$this->data['user_uuid']) {
            $_GET['builder'] = [1 => ['where' => [0 => 'api_token_uuid', 1 => $this->data['api_token_uuid']]]];
            $this->data['user_uuid'] = $this->getUserTokens()[0]['user_uuid'];
        }

        if ($this->getUserUuid() === $this->data['user_uuid']) {
            # The user is modifying its own api_token
            $this->checkPermissions('user-apitoken-self', 'RW');

        } else {
            # An API token is being modified owned by another user. We need to make sure the current user is allowed to
            # modify tokens of others.
            $this->checkPermissions('user-apitoken-others', 'RW');

            # Now get the user_group_uuid and then retrieve the group_weight
            require_once 'API_users.php';
            $API_users = new API_users();
            $_GET['builder'] = [1 => ['where' => [0 => 'user_uuid', 1 => $this->data['user_uuid']]]];
            $user_group_uuid = $API_users->getUser()[0]['user_group_uuid'];
            $user_group_weight = $API_users->getUserGroupWeight($user_group_uuid);

            if ($user_group_weight < $_SESSION['user']['user_group_weight']) {
                $this->apiOutput(401, ['error' => 'You are not authorized to access this resource.']);
            }
        }
    }

    #[NoReturn]
    public function createNewToken()
    {

        $api_token = bin2hex(random_bytes(64 / 2));

        $api_token_hash = password_hash($api_token, PASSWORD_BCRYPT, ["cost" => 12]);
        $api_token_expiration_timestamp = strtotime('+1 year');
        $api_token_name = $this->data['api_token_name'] ?? null;
        $query = "INSERT INTO system_api_tokens (api_token_uuid, user_uuid, api_token, api_token_name, api_token_expiration_timestamp, api_token_created_timestamp) VALUES (UUID(), ?, ?, ?, ?, ?)";
        $stmt = $this->prepareStatement($query);

        $created_timestamp = time();

        $stmt->bind_param('sssii', $this->data['user_uuid'], $api_token_hash, $api_token_name, $api_token_expiration_timestamp, $created_timestamp);

        $this->executeStatement($stmt);

        $result = $this->getNewToken();
        $_SESSION['tmp_api_token'] = $api_token;

        if ($result->num_rows > 0) {
            $api_token_data = $result->fetch_assoc();

            $_SESSION['tmp_api_token'] = $api_token_data['api_token_uuid'] . '.' . $api_token;

            $this->apiOutput(200, ['success' => $api_token_data], 'api_token_created');
        } else {
            $this->apiOutput(500, ['error' => 'Something went wrong creating the token on the server.'], 'error_contact_support');
        }
    }

    public function getNewToken()
    {
        $query = "SELECT * FROM system_api_tokens WHERE user_uuid = ? ORDER BY api_token_created_timestamp DESC LIMIT 1";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('s', $this->data['user_uuid']);
        $this->executeStatement($stmt);
        return $stmt->get_result();
    }


    public function getToken()
    {
        $query = "SELECT system_users.user_email, system_users.user_uuid FROM system_api_tokens INNER JOIN system_users ON system_api_tokens.user_uuid = system_users.user_uuid WHERE api_token_uuid = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('s', $this->data['api_token_uuid']);
        $this->executeStatement($stmt);
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            $this->apiOutput(404, ['error' => 'API token not found.']);
        }

        $api_token_data = $result->fetch_assoc();

        return $api_token_data;
    }

    public function deleteToken()
    {
        $query = "DELETE FROM system_api_tokens WHERE api_token_uuid = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('s', $this->data['api_token_uuid']);
        if ($this->executeStatement($stmt)) {
            $this->apiOutput(200, ['success' => 'API token deleted successfully.']);
        }
    }

    public function revokeToken()
    {

        $api_token_revoked = ($this->data['api_token_revoked']) ? 1 : 0;

        $query = "UPDATE system_api_tokens SET api_token_revoked = ? WHERE api_token_uuid = ?";
        $stmt = $this->prepareStatement($query);
        $stmt->bind_param('is', $api_token_revoked, $this->data['api_token_uuid']);

        if ($this->executeStatement($stmt)) {
            $this->apiOutput(200, ['success' => 'API token ' . ($api_token_revoked ? 'revoked' : 'envoked') . ' successfully.']);
        }
    }
}