<?php
/*
|--------------------------------------------------------------------------
| RadyoHost.BiZ / Profesyonel Radyo Hosting ve Web Tasarım Hizmetleri
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| İLETİŞİM MESAJLARI
|--------------------------------------------------------------------------
| contact-messages.php
| İletişimden gelen mesajları listeleme, okuma ve silme ekranı
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'İletişim Mesajları';
$pageDescription = 'İletişim formundan gelen mesajları yönetin.';

require_once __DIR__ . '/includes/admin-layout.php';

$messages = [];
$notice = '';
$noticeType = '';

function cm_e($value): string
{
    return function_exists('admin_e')
        ? admin_e($value)
        : htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function cm_columns(PDO $pdo, string $table): array
{
    try {
        $cols = [];
        $q = $pdo->query("SHOW COLUMNS FROM `$table`");
        while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
            $cols[] = (string)$row['Field'];
        }
        return $cols;
    } catch (Throwable $e) {
        return [];
    }
}

function cm_has(array $cols, string $col): bool
{
    return in_array($col, $cols, true);
}

function cm_val(array $row, array $keys, string $default = '-'): string
{
    foreach ($keys as $key) {
        if (isset($row[$key]) && trim((string)$row[$key]) !== '') {
            return (string)$row[$key];
        }
    }
    return $default;
}

function cm_short(string $text, int $limit = 30): string
{
    $text = trim(preg_replace('/\s+/', ' ', $text) ?? '');

    if (mb_strlen($text, 'UTF-8') <= $limit) {
        return $text;
    }

    return mb_substr($text, 0, $limit, 'UTF-8') . '...';
}

function cm_date_only(string $date): string
{
    if ($date === '' || $date === '-') {
        return '-';
    }

    $time = strtotime($date);
    return $time ? date('d.m.Y', $time) : $date;
}

function cm_phone_short(string $phone): string
{
    $phone = trim($phone);

    if ($phone === '' || $phone === '-') {
        return '-';
    }

    return mb_substr($phone, 0, 15, 'UTF-8');
}

try {
    if (!isset($pdo) || !$pdo instanceof PDO) {
        throw new RuntimeException('Veritabanı bağlantısı bulunamadı.');
    }

    $columns = cm_columns($pdo, 'contact_messages');

    if (!$columns) {
        throw new RuntimeException('contact_messages tablosu bulunamadı.');
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = trim((string)($_POST['action'] ?? ''));
        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            throw new RuntimeException('Geçersiz mesaj ID.');
        }

        if ($action === 'delete') {
            $stmt = $pdo->prepare("DELETE FROM contact_messages WHERE id = ?");
            $stmt->execute([$id]);

            $notice = 'Mesaj başarıyla silindi.';
            $noticeType = 'success';
        }

        if ($action === 'read') {
            if (cm_has($columns, 'status')) {
                $stmt = $pdo->prepare("UPDATE contact_messages SET status = 'read' WHERE id = ?");
                $stmt->execute([$id]);

                $notice = 'Mesaj okundu olarak işaretlendi.';
                $noticeType = 'success';
            } else {
                $notice = 'Status kolonu bulunmadığı için okundu işlemi yapılamadı.';
                $noticeType = 'error';
            }
        }
    }

    $messages = $pdo->query("
        SELECT *
        FROM contact_messages
        ORDER BY id DESC
        LIMIT 200
    ")->fetchAll(PDO::FETCH_ASSOC) ?: [];

} catch (Throwable $e) {
    $notice = $e->getMessage();
    $noticeType = 'error';
}

$totalMessages = count($messages);
$newMessages = 0;
$readMessages = 0;
$thisMonth = 0;

foreach ($messages as $row) {
    $status = strtolower(cm_val($row, ['status'], 'new'));
    $date = cm_val($row, ['created_at','date'], '');

    if (in_array($status, ['new','unread','pending','0'], true)) {
        $newMessages++;
    } else {
        $readMessages++;
    }

    if ($date !== '') {
        $time = strtotime($date);
        if ($time !== false && date('Y-m', $time) === date('Y-m')) {
            $thisMonth++;
        }
    }
}
?>

<style>
.contact-page{display:grid;gap:24px}
.contact-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:18px}
.contact-stat{position:relative;overflow:hidden;min-height:140px;padding:24px;border-radius:30px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.09);box-shadow:0 22px 60px rgba(0,0,0,.18)}
.contact-stat:after{content:"";position:absolute;right:18px;bottom:14px;width:76px;height:76px;border-radius:24px;background:rgba(245,182,66,.10)}
.contact-stat span{display:block;color:#aeb7c7;font-size:14px;font-weight:900;margin-bottom:16px}
.contact-stat strong{display:block;color:#f5b642;font-size:38px;font-weight:1000}
.contact-stat em{position:absolute;right:34px;bottom:31px;font-size:38px;font-style:normal;opacity:.75}

.contact-panel{overflow:hidden;border-radius:34px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.09);box-shadow:0 24px 70px rgba(0,0,0,.20)}
.panel-head{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:28px;border-bottom:1px solid rgba(255,255,255,.08)}
.panel-head h2{margin:0 0 6px;color:#f5b642;font-size:28px}
.panel-head p{margin:0;color:#dce3ef;font-weight:800}

.table-wrap{width:100%;overflow-x:auto}
.contact-table{width:100%;min-width:1020px;border-collapse:collapse}
.contact-table th,.contact-table td{padding:18px;border-bottom:1px solid rgba(255,255,255,.07);text-align:left;vertical-align:middle;color:#dce3ef;font-size:14px}
.contact-table th{color:#f5b642;background:rgba(0,0,0,.18);font-weight:1000}
.contact-table tr:hover td{background:rgba(255,255,255,.035)}

.sender-info strong{display:block;color:#fff;font-size:15px;font-weight:1000;margin-bottom:5px}
.sender-info span{display:block;color:#9aa3b2;font-size:12px;font-weight:800}

.msg-subject{max-width:180px;color:#fff;font-weight:1000;margin-bottom:5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.msg-preview{max-width:180px;color:#9aa3b2;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}

.badge{display:inline-flex;min-height:32px;padding:0 13px;border-radius:999px;align-items:center;justify-content:center;font-size:12px;font-weight:1000}
.badge-new{background:rgba(245,182,66,.15);color:#f5b642;border:1px solid rgba(245,182,66,.28)}
.badge-read{background:rgba(0,150,70,.18);color:#d8ffe8;border:1px solid rgba(0,255,120,.25)}

.action-group{display:flex;gap:8px;flex-wrap:nowrap}
.action-link,.action-btn{min-height:38px;padding:0 13px;border-radius:13px;display:inline-flex;align-items:center;justify-content:center;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.10);color:#fff;font-size:12px;font-weight:1000;text-decoration:none;cursor:pointer;white-space:nowrap}
.action-link:hover,.action-btn:hover{border-color:rgba(245,182,66,.35);color:#f5b642}
.action-btn.delete{background:rgba(185,0,0,.18);border-color:rgba(255,80,80,.25);color:#ffdede}
.action-btn.delete:hover{background:rgba(185,0,0,.30);color:#fff}

.form-alert{padding:16px 18px;border-radius:18px;font-weight:900}
.form-alert.success{background:rgba(0,150,70,.20);border:1px solid rgba(0,255,120,.30);color:#d8ffe8}
.form-alert.error{background:rgba(185,0,0,.20);border:1px solid rgba(255,80,80,.30);color:#ffdede}
.empty-state{padding:34px;text-align:center;color:#aeb7c7;font-weight:900}

@media(max-width:1100px){.contact-stats{grid-template-columns:repeat(2,1fr)}}
@media(max-width:620px){.contact-stats{grid-template-columns:1fr}.panel-head{display:block}}
</style>

<section class="contact-page">

    <?php if ($notice !== ''): ?>
        <div class="form-alert <?= cm_e($noticeType) ?>">
            <?= cm_e($notice) ?>
        </div>
    <?php endif; ?>

    <div class="contact-stats">
        <div class="contact-stat">
            <span>Toplam Mesaj</span>
            <strong><?= cm_e((string)$totalMessages) ?></strong>
            <em>📩</em>
        </div>

        <div class="contact-stat">
            <span>Yeni Mesaj</span>
            <strong><?= cm_e((string)$newMessages) ?></strong>
            <em>🔔</em>
        </div>

        <div class="contact-stat">
            <span>Okunan Mesaj</span>
            <strong><?= cm_e((string)$readMessages) ?></strong>
            <em>✅</em>
        </div>

        <div class="contact-stat">
            <span>Bu Ay Gelen</span>
            <strong><?= cm_e((string)$thisMonth) ?></strong>
            <em>📅</em>
        </div>
    </div>

    <div class="contact-panel">
        <div class="panel-head">
            <div>
                <h2>Mesaj Listesi</h2>
                <p>İletişim formundan gelen mesajları buradan okuyabilir, okundu yapabilir veya silebilirsiniz.</p>
            </div>
        </div>

        <div class="table-wrap">
            <table class="contact-table">
                <thead>
                    <tr>
                        <th>Gönderen</th>
                        <th>Mesaj</th>
                        <th>Telefon</th>
                        <th>Durum</th>
                        <th>Tarih</th>
                        <th>İşlem</th>
                    </tr>
                </thead>

                <tbody>
                <?php if ($messages): ?>
                    <?php foreach ($messages as $row): ?>
                        <?php
                            $id = (int)($row['id'] ?? 0);

                            $email = cm_val($row, ['email'], '-');
                            $phone = cm_phone_short(cm_val($row, ['phone','gsm','mobile'], '-'));
                            $subject = cm_val($row, ['subject','title'], 'Konu Yok');
                            $body = cm_val($row, ['message','content','body','text'], '-');
                            $date = cm_date_only(cm_val($row, ['created_at','date'], '-'));

                            $status = strtolower(cm_val($row, ['status'], 'new'));
                            $isNew = in_array($status, ['new','unread','pending','0'], true);

                            $senderType = !empty($row['user_id']) ? 'Üye' : 'Ziyaretçi';
                            $senderSub = !empty($row['user_id'])
                                ? cm_val($row, ['username','email'], $email)
                                : $email;
                        ?>

                        <tr>
                            <td>
                                <div class="sender-info">
                                    <strong><?= cm_e($senderType) ?></strong>
                                    <span><?= cm_e($senderSub) ?></span>
                                </div>
                            </td>

                            <td>
                                <div class="msg-subject"><?= cm_e(cm_short($subject, 20)) ?></div>
                                <div class="msg-preview"><?= cm_e(cm_short($body, 30)) ?></div>
                            </td>

                            <td><?= cm_e($phone) ?></td>

                            <td>
                                <span class="badge <?= $isNew ? 'badge-new' : 'badge-read' ?>">
                                    <?= $isNew ? 'Yeni' : 'Okundu' ?>
                                </span>
                            </td>

                            <td><?= cm_e($date) ?></td>

                            <td>
                                <div class="action-group">
                                    <a href="contact-message-view.php?id=<?= $id ?>" class="action-link">Detay</a>

                                    <form method="post">
                                        <input type="hidden" name="action" value="read">
                                        <input type="hidden" name="id" value="<?= $id ?>">
                                        <button type="submit" class="action-btn">Okundu</button>
                                    </form>

                                    <form method="post" onsubmit="return confirm('Bu mesaj silinsin mi?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $id ?>">
                                        <button type="submit" class="action-btn delete">Sil</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6">
                            <div class="empty-state">Henüz iletişim mesajı bulunamadı.</div>
                        </td>
                    </tr>
                <?php endif; ?>
                </tbody>

            </table>
        </div>
    </div>

</section>

<?php require_once __DIR__ . '/includes/admin-footer.php'; ?>