<?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 
 */

//print_r($_POST);
//echo $data;

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

//print_r($in);
//echo $in['email'];
// 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($out['error']) {
  echo json_encode($out);
  return;
}

/**
 *  validation done, request -> db, mail to user and ...
 */

//print_r($db->getUserRequests());

$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['imap']['cc'], 'New Request', $body);
  
}  

?>