<?php


use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use GraphQL\GraphQL;

// Mock database (array)
$users = [
    "1" => ["id" => "1", "name" => "Sanny", "email" => "sanny@example.com"],
    "2" => ["id" => "2", "name" => "Aliyu", "email" => "aliyu@example.com"],
];

// Define User Type
$userType = new ObjectType([
    "name" => "User",
    "fields" => [
        "id" => Type::string(),
        "name" => Type::string(),
        "email" => Type::string(),
    ]
]);

// Query: Get user by id
$queryType = new ObjectType([
    "name" => "Query",
    "fields" => [
        "user" => [
            "type" => $userType,
            "args" => [
                "id" => ["type" => Type::string()]
            ],
            "resolve" => function ($root, $args) use (&$users) {
                return $users[$args["id"]] ?? null;
            }
        ],
        "users" => [
            "type" => Type::listOf($userType),
            "resolve" => function () use (&$users) {
                return array_values($users);
            }
        ]
    ]
]);

// Mutation: Add a new user
$mutationType = new ObjectType([
    "name" => "Mutation",
    "fields" => [
        "addUser" => [
            "type" => $userType,
            "args" => [
                "id" => ["type" => Type::string()],
                "name" => ["type" => Type::string()],
                "email" => ["type" => Type::string()],
            ],
            "resolve" => function ($root, $args) use (&$users) {
                $users[$args["id"]] = [
                    "id" => $args["id"],
                    "name" => $args["name"],
                    "email" => $args["email"]
                ];
                return $users[$args["id"]];
            }
        ]
    ]
]);

// Schema
$schema = new Schema([
    "query" => $queryType,
    "mutation" => $mutationType
]);

// Run a query (normally this comes from AJAX request)
try {
    $rawInput = file_get_contents("php://input");
    $input = json_decode($rawInput, true);
    $query = $input["query"];
    $result = GraphQL::executeQuery($schema, $query);
    $output = $result->toArray();
} catch (\Exception $e) {
    $output = ["error" => ["message" => $e->getMessage()]];
}

header("Content-Type: application/json");
echo json_encode($output);
