<?php
$admin_page = 'mesajlar';
$admin_title = 'Mesajlar';
include 'admin_header.php';

$view_id = (int)($_GET['view'] ?? 0);
$delete_id = (int)($_GET['delete'] ?? 0);

if ($delete_id) {
    db()->prepare("DELETE FROM vs_messages WHERE id=?")->execute([$delete_id]);
    header('Location: /volker/admin/mesajlar.php'); exit;
}

if ($view_id) {
    db()->prepare("UPDATE vs_messages SET is_read=1 WHERE id=?")->execute([$view_id]);
    $msg = db()->prepare("SELECT * FROM vs_messages WHERE id=?");
    $msg->execute([$view_id]);
    $message = $msg->fetch(PDO::FETCH_ASSOC);
}

$messages = db()->query("SELECT * FROM vs_messages ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="page-header"><h1>Mesajlar</h1></div>

<?php if ($view_id && !empty($message)): ?>
<div class="admin-card" style="padding:28px;max-width:700px;margin-bottom:24px;">
    <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:20px;">
        <div>
            <h2 style="font-size:17px;"><?= clean($message['subject'] ?: 'Konu yok') ?></h2>
            <p style="color:var(--gray);font-size:13px;margin-top:4px;"><?= clean($message['name']) ?> — <?= clean($message['email']) ?> — <?= date('d.m.Y H:i', strtotime($message['created_at'])) ?></p>
        </div>
        <a href="mesajlar.php" class="btn btn-outline btn-sm">← Geri</a>
    </div>
    <div style="background:var(--black4);border-radius:6px;padding:20px;line-height:1.8;color:#ddd;"><?= nl2br(clean($message['message'])) ?></div>
    <div style="margin-top:16px;display:flex;gap:12px;">
        <a href="mailto:<?= clean($message['email']) ?>?subject=Re: <?= clean($message['subject']) ?>" class="btn btn-primary btn-sm">Yanıtla</a>
        <a href="?delete=<?= $message['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Sil?')">Sil</a>
    </div>
</div>
<?php endif; ?>

<div class="admin-card">
    <table>
        <thead><tr><th>Gönderen</th><th>E-Posta</th><th>Konu</th><th>Tarih</th><th>İşlemler</th></tr></thead>
        <tbody>
        <?php foreach($messages as $m): ?>
        <tr style="<?= !$m['is_read']?'background:rgba(224,32,32,0.04);':'' ?>">
            <td style="font-weight:<?= !$m['is_read']?'700':'400' ?>"><?= clean($m['name']) ?></td>
            <td style="color:var(--gray);"><?= clean($m['email']) ?></td>
            <td><?= clean(mb_substr($m['subject']?:'(yok)',0,40)) ?></td>
            <td style="color:var(--gray);font-size:12px;"><?= date('d.m.Y H:i',strtotime($m['created_at'])) ?></td>
            <td>
                <a href="?view=<?= $m['id'] ?>" class="btn btn-outline btn-sm">Oku</a>
                <a href="?delete=<?= $m['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Sil?')">Sil</a>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php include 'admin_footer.php'; ?>
