<?php
header('Content-Type: text/plain; charset=utf-8');
header("HTTP/1.0 200 OK");

require_once 'config/database.php';

$subject = isset($_POST['subject']) ? trim($_POST['subject']) : 'Rapport ParkGare';
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
$site_id = isset($_POST['site_id']) ? trim($_POST['site_id']) : '';
$lang = isset($_POST['lang']) ? trim($_POST['lang']) : 'FR';

if (empty($message)) {
    echo "ERR|Message vide";
    exit;
}

$site_name = 'Inconnu';
if (!empty($site_id)) {
    try {
        $stmt = $pdo->prepare("SELECT Nom_Site, Nom_SiteAR FROM Sites WHERE SiteID = ?");
        $stmt->execute([$site_id]);
        $site = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($site) {
            $site_name = ($lang === 'AR' && !empty($site['Nom_SiteAR'])) ? $site['Nom_SiteAR'] : $site['Nom_Site'];
        }
    } catch (Exception $e) {
        $site_name = 'Inconnu (Erreur BdD)';
    }
}

$from_name = mb_encode_mimeheader("Rapport envoyer depuis l'aplication Parking du Site ($site_name)", "UTF-8", "Q");

$to = 'r.benamer@transub.dz, c.lamraoui@transub.dz, m.meflah@transub.dz';
$headers = "From: \"$from_name\" <noreply@transub.dz>\r\n";
$headers .= "Reply-To: noreply@transub.dz\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

if (mail($to, $subject, $message, $headers)) {
    echo "OK|Email envoyé";
} else {
    echo "ERR|Erreur lors de l'envoi de l'email";
}
?>
