<?php
/*
Sample call:

require 'ZakStuntsApi.php';
$api = new ZakStuntsApi('<your API client id>', '<your API client secret>');
$response = $api->updateEvent([
  "id"           => "r4k-2021-09",
  "name"         => "2021-09 - Tropical Springs Stunt Park",
  "url"          => "http://www.raceforkicks.com/index.php?page=race&race=2021-09",
  "opens_on"     => "2021-09-01T15:59:00+02:00",
  "closes_on"    => "2021-09-27T01:59:00+02:00",
// these fields are optional, all three or none
  "track_title"  => "Tropical Springs Stunt Park",
  "track_author" => "KyLiE",
  "track_url"    => "http://www.raceforkicks.com/tracks/r4k14.trk"
]);

echo var_export($response, true);
*/

class ZakStuntsApi
{
  const BASE_URL = 'http://zak.stunts.hu/api/';
  const EVENTS_ENDPOINT = 'events';

  private $clientId, $clientSecret;

  public function __construct($clientId, $clientSecret)
  {
    $this->clientId = $clientId;
    $this->clientSecret = $clientSecret;
  }

  public function updateEvent(array $eventData)
  {
    return $this->postForm(self::EVENTS_ENDPOINT, $eventData);
  }

  private function postForm($endpoint, $data)
  {
    $headers = 'Content-Type: application/x-www-form-urlencoded';
    $content = http_build_query($data + [
      'client_id' => $this->clientId,
      'client_secret' => $this->clientSecret,
    ]);
    return $this->request($endpoint, 'POST', $headers, $content);
  }

  private function request($endpoint, $method = 'GET', $headers = '', $content = '')
  {
    $url = self::BASE_URL . $endpoint;
    $context = stream_context_create([ 'http' => [
      'method' => $method,
      'header' => $headers,
      'content' => $content,
      'ignore_errors' => true,
    ]]);
    return json_decode(file_get_contents($url, false, $context));
  }
}
