<?php

use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ObjectType;
use GuzzleHttp\Client;

include "lib/getGravatar.php";
$commentField = new ObjectType([
    "name" => "Comment",
    "fields" => [
        "name" => Type::string(),
        "comment" => Type::string(),
        "gravatarURL" => Type::string(),
        "id" => Type::int()
    ],
]);

function comments($article, $conn)
{
    $response = [];
    $article = $conn->real_escape_string($article);
    $result = $conn->query("SELECT * FROM comments WHERE article='$article'");
    while ($row = $result->fetch_assoc()) {
        $commentElement = [
            "name" => $row["name"],
            "comment" => $row["comment"],
            "gravatarURL" => get_gravatar($row["email"]),
            "id" => $row["id"]
        ];

        array_push($response, $commentElement);
    }
    return $response;
}

function newComment($conn, $article, $name, $email, $comment, $hCaptchaResponse)
{
    require "./lib/config.php";
    $data = array(
        'secret' => $secretkey,
        'response' => $hCaptchaResponse
    );
    $client = new Client();

    $response = $client->post("https://hcaptcha.com/siteverify", [
        "form_params" => $data
    ]);

    $responseData = json_decode($response->getBody());
    if (!$responseData->success) {
        return "Failed to verify Captcha";
    }

    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return "Invalid email address.";
    }

    $article = $conn->escape_string($article);
    $name = $conn->escape_string($name);
    $email = $conn->escape_string($email);
    $comment = $conn->escape_string($comment);

    $sql = "INSERT INTO comments (name, email, comment, article) VALUES ('$name', '$email', '$comment', '$article')";

    if ($conn->query($sql) === TRUE) {
        return "OK";
    } else {
        return "Error: " . $sql . "<br>" . $conn->error;
    }
}
