<?php
// Check for affiliate code
if (isset($_GET['{GET_VAR}'])) {
  // Set cookie if not already set..
  if (!isset($_COOKIE['{COOKIE}'])) {
    setcookie('{COOKIE}', $_GET['{GET_VAR}'], time() + 60 * 60 * 24 * 180);
  }
  // Prepare array..
  $data = array(
    'apikey' => '{API_KEY}',
    'affiliate' => $_GET['{GET_VAR}'],
    'referrer' => array(
      'url' => (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''),
      'ip' => (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''),
      'product' => '{PRODUCT_ID}'
    )
  );
  // Send to API..
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, '{SITE_FOLDER}index.php');
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
  ));
  curl_setopt($ch, CURLOPT_TIMEOUT, 120);
  $r = json_decode(curl_exec($ch), true);
  curl_close($ch);
  // Do something with response..
  if (isset($r['status'])) {
    switch($r['status']) {
      case 'error':
        // Handle error message..
        break;
      case 'ok':
        // Reload page
        $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
        header("Location: " . $url);
        exit;
        break;
    }
  } else {
    // Check logs folder in Maian Affiliates, something went wrong
  }
}
?>