<?php 
if (file_exists('../../../'.$_REQUEST['tenant'].'/config.php')) {
    require_once('../../../'.$_REQUEST['tenant'].'/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

// Retrieve ticket ID securely
$ticket_id = isset($_GET['ticket_id']) ? mysqli_real_escape_string($admin_con, $_GET['ticket_id']) : '';

if (!$ticket_id) {
    echo "Invalid ticket ID.";
    exit();
}

$replies_query = "SELECT * FROM support_ticket_replies WHERE ticket_id = '$ticket_id' ORDER BY date_sent DESC";
$replies_result = mysqli_query($admin_con, $replies_query);

// Display each reply in the correct format
while ($reply = mysqli_fetch_assoc($replies_result)): ?>
<div class="card mb-2 shadow-2-strong">
    <div class="p-2 <?= $reply['sender_type'] === 'Admin' ? 'bg-dark text-white' : 'bg-secondary text-white' ?>">
        <strong><?= ucfirst($reply['sender_type']); ?>:</strong><small class="float-end"><?= date("d/m/Y H:i", strtotime($reply['date_sent'])); ?></small>
    </div>
    <div class="card-body ">

        <p><?= nl2br(htmlspecialchars($reply['message'])); ?></p>
        <?php if ($reply['attachment']): 
            $filePath = "../../../admin.enrep.co.uk/ticket_files/" . htmlspecialchars($reply['attachment']);
            $urlPath = ADMIN_URL . "/ticket_files/" . htmlspecialchars($reply['attachment']);
            $fileExtension = pathinfo($reply['attachment'], PATHINFO_EXTENSION);
            $isImage = in_array(strtolower($fileExtension), ['jpg', 'jpeg', 'png', 'gif']);
        ?>
        <p><strong>Attachment:</strong></p>

        <?php if ($isImage): ?>
        <!-- Image thumbnail with download on click -->
        <a href="<?= $urlPath ?>" target="_blank">
            <img src="<?= $urlPath ?>" alt="attachment" style="width: 100px; height: auto; border-radius: 4px; margin-bottom: 10px;">
        </a>
        <?php else: ?>
        <!-- File icon with filename and download on click -->
        <a href="<?= $urlPath ?>" target="_blank" class="d-flex align-items-center">
            <i class="fad fa-file-alt fa-2x me-2"></i> <?= basename($reply['attachment']); ?>
        </a>
        <?php endif; ?>
        <?php endif; ?>

    </div>
</div>
<?php endwhile; ?>