<?php

$ilanlar = tabloOku("ilanlar", $conn);

$sql = "SELECT * FROM mesajlar ORDER BY mesaj_id DESC";
$ornek = mysqli_query($conn, $sql);
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-coffee mb-0"><i class="bi bi-chat-left-quote text-coffee-gold me-2"></i> Okuyucu Mesajları</h3>
</div>

<div class="table-responsive border border-light rounded-4 shadow-sm bg-white p-3">
    <table class="table table-hover align-middle table-borderless mb-0">
        <thead>
        <tr class="table-light border-bottom">
          <th scope="col" class="py-3">İlgili Yazı</th>
          <th scope="col" class="py-3">Gönderen</th>
          <th scope="col" class="py-3">E-posta</th>
          <th scope="col" class="py-3">Tarih</th>
          <th scope="col" class="py-3">Cevap Durumu</th>
          <th scope="col" class="py-3 text-center" style="width: 240px;">İşlemler</th>
          </tr>
      </thead>
      <tbody>
    <?php
    while ($row = mysqli_fetch_array($ornek, MYSQLI_BOTH)) {
        $mesajID = $row["mesaj_id"];
        $ilanID = $row["ilan_id"];
        $gonderenAd = $row["gonderen_ad"];
        $gonderenEmail = $row["gonderen_email"];
        $tarih = $row["mesaj_tarih"];
        $cevap = $row["cevap"];

        if (isset($ilanlar[$ilanID]))
            $ilanBaslik = $ilanlar[$ilanID]["ilan_baslik"];
        else
            $ilanBaslik = "<span class='text-muted'>Silinmiş Yazı</span>";

        if (is_null($cevap) || trim($cevap) == "")
            $durum = "<span class=\"badge rounded-pill bg-warning text-dark px-3 py-1.5\"><i class='bi bi-hourglass-split me-1'></i> Bekliyor</span>";
        else
            $durum = "<span class=\"badge rounded-pill bg-success px-3 py-1.5\"><i class='bi bi-check-all me-1'></i> Cevaplandı</span>";

        echo "<tr class=\"border-bottom\">";
        echo "<td class=\"py-3\"><strong>$ilanBaslik</strong></td>";
        echo "<td class=\"py-3\"><strong class=\"text-dark\">$gonderenAd</strong></td>";
        echo "<td class=\"py-3 text-muted small\">$gonderenEmail</td>";
        echo "<td class=\"py-3 text-muted small\">$tarih</td>";
        echo "<td class=\"py-3\">$durum</td>";
        echo "<td class=\"py-3 text-center\">";
        echo "  <a href=\"?sayfa=mesajdetay&mesajID=$mesajID\" class=\"btn btn-sm btn-outline-coffee rounded-pill px-3 py-1.5 me-1\"><i class=\"bi bi-eye me-1\"></i> Oku</a>";
        echo "  <a href=\"?sayfa=mesajSil&mesajID=$mesajID\" onclick=\"return confirm('Bu mesajı silmek istediğinize emin misiniz?');\" class=\"btn btn-sm btn-outline-danger rounded-pill px-3 py-1.5\"><i class=\"bi bi-trash me-1\"></i> Sil</a>";
        echo "</td>";
        echo "</tr>";
    }
    echo "</tbody></table></div>";
