<?php
// Headers de sécurité
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

require("/usr/share/php/libphp-phpmailer/autoload.php");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Set header to return JSON
header('Content-Type: application/json');

$mail = new PHPMailer(true);

$errors = [];
$myEmail = getenv('ASTRO_SMTP_FROM');
$myEmailSplitted = explode('@', $myEmail);
$domainFromMyEmail = (
    empty($myEmailSplitted[1])
    || count($myEmailSplitted) != 2
) ? ''
: $myEmailSplitted[1];

$wantedContact = filter_input(INPUT_POST, 'contactTo', FILTER_SANITIZE_SPECIAL_CHARS);
$wantedContact = (
    empty($wantedContact)
    || strpos($wantedContact, '@') !== false
    || strpos($wantedContact, '&') !== false
    || empty($domainFromMyEmail)
) ? $myEmail : "$wantedContact@$domainFromMyEmail" ;

/* hCaptcha */
$hcaptchaSecret = getenv('HCAPTCHA_SECRET_KEY');
$hcaptchaVerifyUrl = "https://api.hcaptcha.com/siteverify";

// Validation et assainissement des entrées
$name = filter_input(INPUT_POST, 'namezzz', FILTER_SANITIZE_STRING);
$emailAddress = filter_input(INPUT_POST, 'emailzzz', FILTER_SANITIZE_EMAIL);
$select = filter_input(INPUT_POST, 'select', FILTER_SANITIZE_STRING);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);
$subscribe = filter_input(INPUT_POST, 'subscribe', FILTER_SANITIZE_STRING);

if(empty($name) || empty($emailAddress) || empty($message)) {
    $errors[] = "Erreur : champs obligatoires manquants.";
}

if(!empty($_POST['name']) && !empty($_POST['email'])) {
    $errors[] = "Erreur : spam détecté.";
}

/* Captcha verification */
if(!empty($_POST['h-captcha-response'])) {
    $responseKey = $_POST['h-captcha-response'];
    $data = array(
        'secret' => $hcaptchaSecret,
        'response' => $responseKey
    );

    $checkRequest = curl_init();
    curl_setopt($checkRequest, CURLOPT_URL, $hcaptchaVerifyUrl);
    curl_setopt($checkRequest, CURLOPT_POST, 1);
    curl_setopt($checkRequest, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($checkRequest, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($checkRequest, CURLOPT_TIMEOUT, 10);
    curl_setopt($checkRequest, CURLOPT_SSL_VERIFYPEER, true);
    $response = curl_exec($checkRequest);
    curl_close($checkRequest);

    $responseData = json_decode($response, true);

    if(!$responseData['success']) {
        $errors[] = "Erreur lors de la validation du captcha.";
    }
} else {
    $errors[] = "Erreur lors de la validation du captcha.";
}

if (!filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Erreur d'adresse e-mail invalide.";
}

if(empty($errors)) {
    try {
        $emailSubject = "[Formulaire Astrolabe] Nouveau message";

        switch ($select) {
            case "option 1":
                $purpose = "Demande de rendez-vous";
                break;
            case "option 2":
                $purpose = "Demande de précisions sur le statut d'entrepreneur salarié";
                break;
            case "option 3":
                $purpose = "Proposition de misson";
                break;
            case "option 4":
                $purpose = "Proposition de partenariat";
                break;
            default:
                $purpose = "Autre demande";
        }
        $emailSubject .= " : " . htmlspecialchars($purpose, ENT_QUOTES, 'UTF-8');
        $emailBody = "Vous avez reçu un nouveau message depuis le formulaire du site Astrolabe :".
        "\r\n\r\nNom: " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . 
        "\r\nEmail: " . htmlspecialchars($emailAddress, ENT_QUOTES, 'UTF-8') . 
        "\r\nRaison: " . htmlspecialchars($purpose, ENT_QUOTES, 'UTF-8') .
        "\r\nSubscribe: " . (empty($subscribe) ? 'Non' : 'Oui') .
        "\r\n\r\n" . htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
        
        $emailBodyHTML = str_replace("\r\n", "<br>", $emailBody);
        
        $mail->isSMTP();
        $mail->Host       = getenv('ASTRO_SMTP_HOSTNAME');
        $mail->SMTPAuth   = true;
        $mail->Username   = getenv('ASTRO_SMTP_USERNAME');
        $mail->Password   = getenv('ASTRO_SMTP_PASSWORD');
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        //Options
        $mail->CharSet    = 'UTF-8';
        $mail->WordWrap   = 70;
                
        //Recipients
        $mail->setFrom($myEmail);
        $mail->addAddress($wantedContact);
        $mail->addReplyTo($emailAddress, htmlspecialchars($name, ENT_QUOTES, 'UTF-8'));
                
        // Content
        $mail->isHTML(true);
        $mail->Subject = $emailSubject;
        $mail->Body    = $emailBodyHTML;
        $mail->AltBody = $emailBody;
                
        $mail->send();

        // if subscribe add to mailing list
        if(!empty($subscribe)) {
            // process
            // enovoi mail add to mailing list
        }
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Message envoyé avec succès'
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'errors' => ["Erreur lors de l'envoi du message. Veuillez réessayer plus tard."]
        ]);
    }
} else {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'errors' => $errors
    ]);
}
