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

$id = (int)($_GET['id'] ?? 0);
$replySuccess = false;
$replyError = '';

try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM messages WHERE id = ?");
    $stmt->execute([$id]);
    $message = $stmt->fetch();

    if (!$message) {
        echo '<div class="alert error"><i class="fas fa-exclamation-circle"></i><span>Message introuvable</span></div>';
        echo '<a href="messages.php" class="btn btn-primary"><i class="fas fa-arrow-left"></i> <span>Retour</span></a>';
        require_once __DIR__ . '/footer.php';
        exit;
    }

    // Marquer comme lu
    if (!$message['is_read']) {
        $db->prepare("UPDATE messages SET is_read = 1 WHERE id = ?")->execute([$id]);
        $message['is_read'] = 1;
    }

    // Send reply
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_reply'])) {
        $replyBody = trim($_POST['reply_body'] ?? '');
        $replySubject = trim($_POST['reply_subject'] ?? '') ?: ('Re: ' . $message['subject']);

        if (empty($replyBody)) {
            $replyError = "Le message ne peut pas être vide.";
        } else {
            // Send email via PHP mail()
            $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($message['email'], $replySubject, $replyBody . $signature, $headers)) {
                // Log + marquer comme répondu
                $db->prepare("UPDATE messages SET replied = 1 WHERE id = ?")->execute([$id]);
                $db->prepare("INSERT INTO email_logs (user_id, to_email, subject, body, status) VALUES (?, ?, ?, ?, 'sent')")
                   ->execute([$currentUser['id'], $message['email'], $replySubject, $replyBody]);
                $replySuccess = true;
                $message['replied'] = 1;
            } else {
                $replyError = "Erreur lors de l'envoi. Veuillez réessayer.";
            }
        }
    }

} catch (Exception $e) {
    echo '<div class="alert error"><i class="fas fa-exclamation-circle"></i><span>Erreur: ' . escape($e->getMessage()) . '</span></div>';
    require_once __DIR__ . '/footer.php';
    exit;
}
?>

<div class="page-header">
    <div class="page-header-left">
        <div class="page-eyebrow">— Lecture du message</div>
        <h1 class="page-title">Détails du <span class="italic">message</span></h1>
    </div>
    <a href="messages.php" class="btn btn-secondary">
        <i class="fas fa-arrow-left"></i>
        <span>Retour</span>
    </a>
</div>

<?php if ($replySuccess): ?>
    <div class="alert success">
        <i class="fas fa-check-circle"></i>
        <div>
            <strong>Réponse envoyée avec succès !</strong><br>
            Votre réponse a été envoyée à <?= escape($message['email']) ?>
        </div>
    </div>
<?php elseif ($replyError): ?>
    <div class="alert error">
        <i class="fas fa-exclamation-circle"></i>
        <span><?= escape($replyError) ?></span>
    </div>
<?php endif; ?>

<!-- MESSAGE CONTENT -->
<div class="message-view">
    <div class="message-view-header">
        <h2 class="message-view-subject"><?= escape($message['subject']) ?></h2>
        <div class="message-view-meta">
            <div class="meta-item">
                <i class="fas fa-user"></i>
                <span><?= escape($message['name']) ?></span>
            </div>
            <div class="meta-item">
                <i class="fas fa-envelope"></i>
                <a href="mailto:<?= escape($message['email']) ?>"><?= escape($message['email']) ?></a>
            </div>
            <div class="meta-item">
                <i class="fas fa-phone"></i>
                <a href="tel:<?= escape($message['phone']) ?>"><?= escape($message['phone']) ?></a>
            </div>
            <div class="meta-item">
                <i class="far fa-clock"></i>
                <span><?= formatDate($message['created_at']) ?></span>
            </div>
            <?php if ($message['replied']): ?>
                <div class="meta-item" style="color: var(--green);">
                    <i class="fas fa-reply"></i>
                    <span style="color: var(--green);">Déjà répondu</span>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="message-view-body"><?= nl2br(escape($message['message'])) ?></div>

    <div class="message-view-actions">
        <a href="https://wa.me/<?= preg_replace('/[^0-9]/', '', $message['phone']) ?>" target="_blank" class="btn btn-or">
            <i class="fab fa-whatsapp"></i>
            <span>WhatsApp</span>
        </a>
        <a href="tel:<?= escape($message['phone']) ?>" class="btn btn-secondary">
            <i class="fas fa-phone"></i>
            <span>Appeler</span>
        </a>
        <a href="mailto:<?= escape($message['email']) ?>" class="btn btn-secondary">
            <i class="fas fa-envelope"></i>
            <span>Email externe</span>
        </a>
    </div>
</div>

<!-- REPLY FORM -->
<div class="card">
    <div class="card-header">
        <h2 class="card-title">Répondre</h2>
    </div>

    <form method="POST" class="compose-form" style="background: transparent; padding: 0;">
        <input type="hidden" name="send_reply" value="1">

        <div class="form-row">
            <label>À</label>
            <input type="text" value="<?= escape($message['name']) ?> <<?= escape($message['email']) ?>>" readonly style="color: var(--gris);">
        </div>

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

        <textarea name="reply_body" class="form-textarea" placeholder="Bonjour <?= escape($message['name']) ?>,&#10;&#10;Merci pour votre message..." required><?= escape($_POST['reply_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>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-paper-plane"></i>
                <span>Envoyer la réponse</span>
            </button>
        </div>
    </form>
</div>

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