<?php

use PHPMailer\PHPMailer\Exception;
use Jenssegers\Blade\Blade;
use Carbon\Carbon;

require '../vendor/autoload.php';

require '../src/Token.php';
require '../src/Mailer.php';
require '../src/SimpleCors.php';

function json_response($data = null, $httpStatus = 200)
{
  header("Content-Type: application/json");
  http_response_code($httpStatus);
  echo json_encode($data);
  exit();
}

$APP_PATH = dirname(__DIR__);

$cors = new SimpleCors(array(
  'allowedHeaders' => [],
  'allowedMethods' => 'GET,POST',
  'allowedOrigins' => 'http://localhost:3000,https://fxpoizat.netlify.app,http://fxpoizat.com,http://www.fxpoizat.com',
  'maxAge' => '86400',
  'supportsCredentials' => '1'
));
$cors->handle() or exit();

$blade = new Blade($APP_PATH . '/views', $APP_PATH . '/cache');

function verify_integrity($data)
{
  if (!isset($data['email']) || $data['email'] != '') {
    json_response([
      'message' => 'Le message est allé directement dans les SPAMs',
      'clear'   => true,
      'err' => true
    ], 201);
  }
  if (
    !isset($data['token'])
    || !Token::isValid($data['token'])
  ) {
    json_response([
      'message' => 'Message non transmis, problème de sécurité.',
      'clear'   => false,
      'err'     => true
    ], 202);
  }
  return true;
}

function sanitize_post_data($fieldNames, $data)
{

  $output = [];
  foreach ($fieldNames as $fieldName) {
    $output[$fieldName] = htmlspecialchars($data[$fieldName]);
  }
  return $output;
}

try {
  if ($_SERVER['SERVER_NAME'] == 'mail.services.fxpoizat.com') {
    $db = new mysqli("alphaliffxp.mysql.db", "alphaliffxp", "siddarSQL17", "alphaliffxp");
  } else {
    $db = new mysqli("localhost", "root", "oulesoleilestfroid", "fxpoizat-directus");
  }
  if (!$db) {
    echo 'erreur';
    $emailTo = 'hugues.tavernier@protonmail.com';
    $emailToName = 'Hugues Tavernier';
  } else {
    $req = $db->query('SELECT * FROM config LIMIT 1');
    $config = $req->fetch_assoc();

    $emailTo = $config['mail_to'];
    $emailToName = $config['mail_to_name'];
  }

  $json = file_get_contents('php://input');
  $data = (array)json_decode($json);

  // vérifie si ce n'est pas un spam
  verify_integrity($data);
  $data['email'] = $data['other'];

  // netoyage des input
  $data = sanitize_post_data(['name', 'email', 'message', 'subject'], $data);
  // $data = [
  //   'name' => 'toto',
  //   'email' => 'toto@amzon.com',
  //   'message'=> 'Long message',
  //   'subject'=> 'le sujet',
  //   'website' => 'huguestavernier.com'
  // ];
  $data['date'] = Carbon::now()->formatLocalized('%e %h %k:%M');
  $data['website'] = 'fxpoizat.com';


  $mail = Mailer::getInstance();
  $mail->addAddress($emailTo, $emailToName);

  $mail->addReplyTo($data['email'], $data['name']);
  $mail->Subject = '[' . $data['website'] . '] ' . \strip_tags($data['subject']);
  $mail->Body = $blade->render('contact', $data);

  $mail->send();
  // sleep(60);
  json_response(array(
    'message' => 'Thanks for your message. I will respond as soon as possible.',
    'clear'   => true,
    'err' => false
  ));
} catch (Exception $e) {
  json_response(array(
    'message' => 'Message not transmitted, error while sending.',
    'clear'   => false,
    'err' => true
  ), 500);
}
