<?php
// tell client, he hit correct endpoint ... 
header("X-ATEndpoint: YES");
// should be www.textgrid.de
header("Access-Control-Allow-Origin: *");

include '../include/config.inc.php';
include '../include/tgSqliteDB.class.php';
include '../include/tgLdap.class.php';
include '../include/tgImap.class.php';

$db = new tgSqliteDB($conf);
$ldap = new tgLdap($conf);
$imap = new tgImap($conf);

// work around magic_quotes_gpc
if (get_magic_quotes_gpc()) {
  $data = stripslashes($_POST['data']);
} else {
  $data = $_POST['data'];
}

/**
 * Validation 
 */
$in = json_decode($data, TRUE);
$out['status'] = 'validating';

// if no language selected default to english
if(!isset($in['lang'])) {
  $in['lang'] = 'en';
}

// email already used? -> query ldap
if($ldap->emailExists($in['email'])) {
  $out['error']['email'] = "registered";
} 

// userid already used? -> query ldap
if($ldap->uidExists($in['userid'])) {
  $out['error']['userid'] = "userid_used";
}

if(empty($in['email']) ) {
  $out['error']['email'] = "empty";
}

if(isset($out['error'])) {
  echo json_encode($out);
  return;
}

/**
 *  validation done, request -> db, mail to user and ...
 */
$db->insertUserRequest($in);

// send email
sendMails($conf, $imap, $db, $in);


/**
 * Here the data is returned
 */
echo json_encode(array("status" => "done"));



function sendMails($conf, $imap, $db, $data) {
  
  /**
   * notify user
   */
  $templateID = ($data['lang'] == 'de') ? 6 : 5;
  $mail = $db->getMailTemplate($templateID);
  
  $subject = 'Request for textgrid account';
  $imap->mail($data['email'], $mail['subject'], $mail['body']);
  
  /**
   * notify textgrid-team
   */
  $body = "";
  foreach($data as $key => $value) {
    $body .= $key . ': ' . $value . "\n";
  }
  $body .= "\nLink zum Backend : " . $conf['url'] . "\n";

  $imap->mail($conf['mail']['cc'], 'New Request', $body);
  
}  

?>