<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

function connect(){

  $link = mysql_connect('127.0.0.1','eligibilite','B3Kg7z6d') or die(mysql_error());
  mysql_select_db('eligibilite', $link) or die(mysql_error());
}

function executeQuery($requete) {
  $resultat = mysql_query($requete) or die(mysql_error());

  if(substr($requete, 0, 6) === 'SELECT'){
    while($donnees = mysql_fetch_array($resultat)){
      $resultats[] = $donnees;
    }
    if (!isset($resultats)) {
      return null;
    }
    return $resultats;
  }
  else if(substr($requete, 0, 6) === 'INSERT'){
    $resultats = mysql_insert_id();
  }
  else {
    $resultats = 'ok';
  }

  return $resultats;
}

connect();

if(isset($_POST['query'])) {
  $resultat = executeQuery($_POST['query']);
  echo json_encode($resultat);
  return;
}

if(isset($_POST['mail'])) {
  $email = 'ftth@manchenumerique.fr';
  $bcc   = 'ftth@manchenumerique.fr';

  if(isset($_POST['siteEmail'])) {
    $email = $_POST['siteEmail'];
  }

  $headers  = "";
  $headers .= "Reply-To:".$email."\r\n"."X-Mailer: PHP/".phpversion(). "\r\n";
  $headers .= "MIME-Version: 1.0"."\r\n";
  $headers .= "Content-type: text/html; charset=iso-8859-1"."\r\n";
  $headers .= "Bcc: ".$bcc."\r\n";
  $headers .= "From: ".utf8_decode("Manche Numérique")." <".$email.">"."\r\n";

  $subject = utf8_decode($_POST['mail']['sujet']);
  $subject = mb_encode_mimeheader($subject, "UTF-8");

  // Envoi
  $to = $_POST['mail']['to'];
  $resultat = mail($to, $subject, utf8_decode($_POST['mail']['message']), $headers, "-f ".$email);
}

if(isset($resultat)){
  echo json_encode($resultat);
}
?>