<?php

namespace api\classes;

use api\classes\API;

require_once 'API.php';

class API_apitoken extends API
{
    public function getTokens()
    {
        $query = "SELECT * FROM vc_api_tokens WHERE vc_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 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');
        $query = "INSERT INTO vc_api_tokens (api_token_uuid, user_uuid, api_token, api_token_expiration_timestamp, api_token_created_timestamp) VALUES (UUID(), ?, ?, ?, ?)";

        $stmt = $this->prepareStatement($query);

        $stmt->bind_param('ssii', $this->data['user_uuid'], $api_token_hash, $api_token_expiration_timestamp, time());

        $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 vc_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 vc_users.user_email, vc_users.user_uuid FROM vc_api_tokens INNER JOIN vc_users ON vc_api_tokens.user_uuid = vc_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 vc_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 vc_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 ? 're' : 'en') . 'voked successfully.']);
        }
    }
}