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

/*
|--------------------------------------------------------------------------
| İLETİŞİM MESAJ DETAYI
|--------------------------------------------------------------------------
| contact-message-view.php
| İletişim formundan gelen mesaj detay okuma ve yönetim ekranı
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Mesaj Detayı';
$pageDescription = 'İletişim formundan gelen mesajın tüm detaylarını görüntüleyin.';

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

$id = (int)($_GET['id'] ?? 0);
$row = [];
$notice = '';
$noticeType = '';

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

function cmv_columns(PDO $pdo, string $table): array
{
    try {
        $cols = [];
        $q = $pdo->query("SHOW COLUMNS FROM `$table`");

        while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
            $cols[] = (string)$r['Field'];
        }

        return $cols;
    } catch (Throwable $e) {
        return [];
    }
}

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

function cmv_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 cmv_date_full(string $date): string
{
    if ($date === '' || $date === '-') {
        return '-';
    }

    $time = strtotime($date);

    if ($time === false) {
        return $date;
    }

    return date('d.m.Y H:i:s', $time);
}

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

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

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

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

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

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

            header('Location: contact-messages.php');
            exit;
        }

        if ($action === 'read' && cmv_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';
        }
    }

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

    $stmt = $pdo->prepare("SELECT * FROM contact_messages WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

    if (!$row) {
        throw new RuntimeException('Mesaj bulunamadı.');
    }
} catch (Throwable $e) {
    $notice = $e->getMessage();
    $noticeType = 'error';
}

$name = cmv_val($row, ['name','full_name','sender_name','fullname'], 'Ziyaretçi');
$email = cmv_val($row, ['email'], '-');
$phone = cmv_val($row, ['phone','gsm','mobile'], '-');
$subject = cmv_val($row, ['subject','title'], 'Konu Yok');
$body = cmv_val($row, ['message','content','body','text'], '-');
$date = cmv_date_full(cmv_val($row, ['created_at','date'], '-'));
$ip = cmv_val($row, ['ip_address','ip'], '-');
$status = strtolower(cmv_val($row, ['status'], 'read'));
$isMember = !empty($row['user_id']);
$senderType = $isMember ? 'Üye' : 'Ziyaretçi';
?>

<style>
.message-detail-page{
    display:grid;
    gap:24px;
}

.detail-hero{
    position:relative;
    overflow:hidden;
    padding:34px;
    border-radius:36px;
    background:
        radial-gradient(circle at top right,rgba(245,182,66,.28),transparent 35%),
        radial-gradient(circle at bottom left,rgba(185,0,0,.20),transparent 38%),
        linear-gradient(135deg,rgba(255,255,255,.08),rgba(255,255,255,.035));
    border:1px solid rgba(255,255,255,.10);
    box-shadow:0 26px 75px rgba(0,0,0,.22);
}

.detail-hero h2{
    margin:0 0 8px;
    color:#f5b642;
    font-size:32px;
}

.detail-hero p{
    margin:0;
    color:#dce3ef;
    font-weight:800;
    line-height:1.6;
}

.detail-layout{
    display:grid;
    grid-template-columns:.36fr 1fr;
    gap:22px;
}

.info-card,
.message-card{
    padding:28px;
    border-radius:32px;
    background:rgba(255,255,255,.055);
    border:1px solid rgba(255,255,255,.09);
    box-shadow:0 22px 65px rgba(0,0,0,.18);
}

.sender-card{
    position:relative;
    overflow:hidden;
    text-align:center;
}

.sender-card:before{
    content:"";
    position:absolute;
    width:160px;
    height:160px;
    border-radius:50%;
    right:-70px;
    top:-70px;
    background:rgba(245,182,66,.14);
}

.sender-type{
    position:relative;
    width:110px;
    height:110px;
    margin:0 auto 18px;
    border-radius:34px;
    background:linear-gradient(135deg,#f5b642,#b90000);
    display:flex;
    align-items:center;
    justify-content:center;
    color:#111;
    font-size:22px;
    font-weight:1000;
    box-shadow:0 24px 50px rgba(0,0,0,.35);
}

.sender-card h3{
    position:relative;
    margin:0 0 8px;
    color:#fff;
    font-size:25px;
}

.sender-card .email{
    position:relative;
    display:block;
    color:#aeb7c7;
    font-weight:800;
    font-size:13px;
    word-break:break-word;
}

.badge{
    display:inline-flex;
    min-height:34px;
    padding:0 14px;
    border-radius:999px;
    align-items:center;
    justify-content:center;
    font-size:12px;
    font-weight:1000;
    white-space:nowrap;
}

.badge-type{
    margin-top:16px;
    background:rgba(245,182,66,.14);
    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);
}

.badge-new{
    background:rgba(245,182,66,.15);
    color:#f5b642;
    border:1px solid rgba(245,182,66,.28);
}

.info-list{
    display:grid;
    gap:12px;
    margin-top:22px;
}

.info-row{
    padding:14px;
    border-radius:17px;
    background:rgba(0,0,0,.22);
    border:1px solid rgba(255,255,255,.07);
}

.info-row small{
    display:block;
    color:#9aa3b2;
    font-weight:900;
    margin-bottom:6px;
}

.info-row b{
    color:#dce3ef;
    word-break:break-word;
}

.message-card h3{
    margin:0 0 10px;
    color:#f5b642;
    font-size:28px;
    line-height:1.25;
}

.message-meta{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:20px;
}

.message-content{
    min-height:260px;
    padding:24px;
    border-radius:26px;
    background:rgba(0,0,0,.24);
    border:1px solid rgba(255,255,255,.08);
    color:#e5ebf5;
    line-height:1.9;
    font-size:16px;
    white-space:pre-wrap;
    word-break:break-word;
}

.action-row{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-top:20px;
}

.btn-delete{
    min-height:42px;
    padding:0 16px;
    border-radius:14px;
    background:rgba(185,0,0,.20);
    border:1px solid rgba(255,80,80,.30);
    color:#ffdede;
    font-weight:900;
    cursor:pointer;
}

.btn-delete:hover{
    background:rgba(185,0,0,.30);
    color:#fff;
}

.form-alert{
    padding:15px 18px;
    border-radius:16px;
    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;
}

@media(max-width:980px){
    .detail-layout{
        grid-template-columns:1fr;
    }
}
</style>

<section class="message-detail-page">

    <div class="detail-hero">
        <h2>Mesaj Detayı</h2>
        <p>İletişim formundan gelen mesajın tüm ayrıntılarını buradan görüntüleyebilirsiniz.</p>
    </div>

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

    <?php if ($row): ?>
        <div class="detail-layout">

            <aside class="info-card sender-card">
                <div class="sender-type">
                    <?= cmv_e($senderType) ?>
                </div>

                <h3><?= cmv_e($name) ?></h3>
                <span class="email"><?= cmv_e($email) ?></span>

                <span class="badge badge-type">
                    <?= cmv_e($senderType) ?>
                </span>

                <div class="info-list">
                    <div class="info-row">
                        <small>Telefon</small>
                        <b><?= cmv_e($phone) ?></b>
                    </div>

                    <div class="info-row">
                        <small>IP Adresi</small>
                        <b><?= cmv_e($ip) ?></b>
                    </div>

                    <div class="info-row">
                        <small>Gönderim Tarihi</small>
                        <b><?= cmv_e($date) ?></b>
                    </div>

                    <div class="info-row">
                        <small>Durum</small>
                        <b><?= cmv_e($status ?: 'read') ?></b>
                    </div>
                </div>

                <div class="action-row">
                    <a href="contact-messages.php" class="admin-btn admin-btn-dark">Listeye Dön</a>
                </div>
            </aside>

            <main class="message-card">
                <h3><?= cmv_e($subject) ?></h3>

                <div class="message-meta">
                    <span class="badge <?= $status === 'read' ? 'badge-read' : 'badge-new' ?>">
                        <?= $status === 'read' ? 'Okundu' : 'Yeni Mesaj' ?>
                    </span>

                    <span class="badge badge-type">
                        <?= cmv_e($date) ?>
                    </span>
                </div>

                <div class="message-content"><?= cmv_e($body) ?></div>

                <div class="action-row">
                    <form method="post">
                        <input type="hidden" name="action" value="read">
                        <button type="submit" class="admin-btn">Okundu Yap</button>
                    </form>

                    <form method="post" onsubmit="return confirm('Bu mesaj silinsin mi?');">
                        <input type="hidden" name="action" value="delete">
                        <button type="submit" class="btn-delete">Mesajı Sil</button>
                    </form>

                    <a href="contact-messages.php" class="admin-btn admin-btn-dark">Listeye Dön</a>
                </div>
            </main>

        </div>
    <?php endif; ?>

</section>

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