<?php
$pageTitle = "Nouveau message";
require_once __DIR__ . '/header.php';

$success = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_email'])) {
    $to      = trim(filter_var($_POST['to'] ?? '', FILTER_SANITIZE_EMAIL));
    $subject = trim($_POST['subject'] ?? '');
    $body    = trim($_POST['body'] ?? '');

    if (empty($to) || empty($subject) || empty($body)) {
        $error = "Tous les champs sont obligatoires.";
    } elseif (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
        $error = "Adresse email invalide.";
    } else {
        $headers  = "From: " . MAIL_FROM_NAME . " <" . ADMIN_EMAIL . ">\r\n";
        $headers .= "Reply-To: " . ADMIN_EMAIL . "\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

        $signature = "\r\n\r\n--\r\n" . MAIL_FROM_NAME . "\r\nAvocat au Barreau du Maroc\r\nBoulevard Mohamed Taieb Naciri, Casablanca\r\nTél: +212 601 53 57 68\r\nEmail: " . ADMIN_EMAIL . "\r\n";

        if (@mail($to, $subject, $body . $signature, $headers)) {
            try {
                $db = getDB();
                $db->prepare("INSERT INTO email_logs (user_id, to_email, subject, body, status) VALUES (?, ?, ?, ?, 'sent')")
                   ->execute([$currentUser['id'], $to, $subject, $body]);
            } catch (Exception $e) {}

            $success = true;
            $_POST = []; // Reset form
        } else {
            $error = "Erreur lors de l'envoi de l'email.";
        }
    }
}
?>

<div class="page-header">
    <div class="page-header-left">
        <div class="page-eyebrow">— Composer</div>
        <h1 class="page-title">Nouveau <span class="italic">message</span></h1>
        <p class="page-subtitle">Envoyer un email depuis votre adresse professionnelle</p>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert success">
        <i class="fas fa-check-circle"></i>
        <div><strong>Email envoyé avec succès !</strong><br>Votre message a bien été envoyé.</div>
    </div>
<?php elseif ($error): ?>
    <div class="alert error">
        <i class="fas fa-exclamation-circle"></i>
        <span><?= escape($error) ?></span>
    </div>
<?php endif; ?>

<form method="POST" class="compose-form">
    <input type="hidden" name="send_email" value="1">

    <div class="form-row">
        <label>De</label>
        <input type="text" value="<?= escape(MAIL_FROM_NAME) ?> <<?= escape(ADMIN_EMAIL) ?>>" readonly style="color: var(--gris);">
    </div>

    <div class="form-row">
        <label>À</label>
        <input type="email" name="to" placeholder="destinataire@email.com" required value="<?= escape($_POST['to'] ?? '') ?>">
    </div>

    <div class="form-row">
        <label>Sujet</label>
        <input type="text" name="subject" placeholder="Objet du message" required value="<?= escape($_POST['subject'] ?? '') ?>">
    </div>

    <textarea name="body" class="form-textarea" placeholder="Rédigez votre message ici..." required><?= escape($_POST['body'] ?? '') ?></textarea>

    <div class="form-actions">
        <p style="font-size: 13px; color: var(--gris); font-style: italic;">
            <i class="fas fa-info-circle" style="color: var(--or);"></i>
            Une signature professionnelle sera ajoutée automatiquement
        </p>
        <div style="display: flex; gap: 12px;">
            <a href="dashboard.php" class="btn btn-secondary">
                <i class="fas fa-times"></i>
                <span>Annuler</span>
            </a>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-paper-plane"></i>
                <span>Envoyer</span>
            </button>
        </div>
    </div>
</form>

<?php require_once __DIR__ . '/footer.php'; ?>
