<?php
/**
 * Fonction helper pour envoyer des e-mails via SMTP avec authentification
 * ou via la fonction mail() standard en dernier recours.
 */
function send_site_notification($pdo, $subject, $message_content) {
    // Récupérer tous les réglages SMTP
    $stmt = $pdo->query("SELECT `key`, `value` FROM site_settings WHERE `key` LIKE 'smtp_%' OR `key` = 'contact_recipient'");
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    $to = $settings['contact_recipient'] ?? 'mairie@kutzenhausen.fr';
    $host = $settings['smtp_host'] ?? '';
    $port = $settings['smtp_port'] ?? '587';
    $user = $settings['smtp_user'] ?? '';
    $pass = $settings['smtp_pass'] ?? '';
    $secure = $settings['smtp_secure'] ?? 'tls';

    $body = "Notification du site Kutzenhausen\n";
    $body .= "----------------------------------\n\n";
    $body .= $message_content . "\n\n";
    $body .= "----------------------------------\n";
    $body .= "Ceci est un message automatique, merci de ne pas y répondre.";

    // Si on a un host configuré et que ce n'est pas localhost, on tente une connexion SMTP directe
    if (!empty($host) && $host !== 'localhost') {
        try {
            return send_smtp_direct($host, $port, $user, $pass, $secure, $to, "Notification: " . $subject, $body);
        } catch (Exception $e) {
            // En cas d'échec SMTP, on peut logguer l'erreur si besoin
            error_log("Erreur SMTP : " . $e->getMessage());
        }
    }

    // Fallback sur la fonction mail() standard
    $from = $user ?: 'noreply@kutzenhausen.fr';
    $headers = "From: Kutzenhausen Site <$from>\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    return mail($to, "Notification: " . $subject, $body, $headers);
}

/**
 * Client SMTP ultra-léger pour supporter l'authentification sans PHPMailer
 */
function send_smtp_direct($host, $port, $user, $pass, $secure, $to, $subject, $body) {
    $timeout = 10;
    $socket_host = ($secure === 'ssl') ? 'ssl://' . $host : $host;
    
    // Création d'un contexte de flux pour désactiver la vérification SSL si le certificat pose problème
    // (Très courant dans les environnements de test locaux comme XAMPP)
    $context = stream_context_create([
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ]
    ]);

    $socket = stream_socket_client($socket_host . ':' . $port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
    
    if (!$socket) throw new Exception("Impossible de se connecter au serveur SMTP: $errstr ($errno)");

    $getResponse = function($socket) {
        $res = "";
        while($str = fgets($socket, 515)) {
            $res .= $str;
            if(substr($str, 3, 1) == " ") break;
        }
        return $res;
    };

    $sendCommand = function($socket, $cmd) use ($getResponse) {
        fputs($socket, $cmd . "\r\n");
        return $getResponse($socket);
    };

    $getResponse($socket); // Banner
    $sendCommand($socket, "EHLO " . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
    
    if ($secure === 'tls') {
        $res = $sendCommand($socket, "STARTTLS");
        if (strpos($res, '220') === false) throw new Exception("STARTTLS échoué: $res");
        if (!stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
            throw new Exception("Échec de l'activation du chiffrement TLS");
        }
        $sendCommand($socket, "EHLO " . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
    }

    if (!empty($user)) {
        $res = $sendCommand($socket, "AUTH LOGIN");
        if (strpos($res, '334') === false) throw new Exception("AUTH LOGIN échoué: $res");
        $sendCommand($socket, base64_encode($user));
        $res = $sendCommand($socket, base64_encode($pass));
        if (strpos($res, '235') === false) throw new Exception("Authentification échouée: $res");
    }

    $sendCommand($socket, "MAIL FROM: <$user>");
    $sendCommand($socket, "RCPT TO: <$to>");
    $res = $sendCommand($socket, "DATA");
    
    $headers = "To: $to\r\n";
    $headers .= "From: $user\r\n";
    $headers .= "Subject: $subject\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
    
    fputs($socket, $headers . $body . "\r\n.\r\n");
    $res = $getResponse($socket);
    
    $sendCommand($socket, "QUIT");
    fclose($socket);
    
    return strpos($res, '250') !== false;
}
?>
