<?php
/**
 * Kullanıcı Paneli - Destek Talebi Detayı (Mesajlaşma)
 * Konum: /magaza/kullanici/destek-detay.php
 */
require_once '../includes/db.php';
require_once '../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    header("Location: ../giris.php");
    exit;
}

$user_id = (int)$_SESSION['user_id'];
$mesaj = '';

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: destek.php");
    exit;
}
$ticket_id = (int)$_GET['id'];

// 1. TALEBİN KULLANICIYA AİT OLDUĞUNU DOĞRULA VE ÇEK
$stmt = $db->prepare("SELECT * FROM support_tickets WHERE id = ? AND user_id = ?");
$stmt->execute([$ticket_id, $user_id]);
$bilet = $stmt->fetch();

if (!$bilet) {
    header("Location: destek.php");
    exit;
}

// 2. YENİ MESAJ GÖNDERME
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cevap_yaz'])) {
    if ($bilet['status'] != 'closed') { // Kapanmış talebe mesaj atılamaz
        $yeni_mesaj = clean($_POST['message']);
        
        if (!empty($yeni_mesaj)) {
            try {
                // Mesajı ekle
                $msg_ins = $db->prepare("INSERT INTO ticket_messages (ticket_id, sender_id, message) VALUES (?, ?, ?)");
                $msg_ins->execute([$ticket_id, $user_id, $yeni_mesaj]);
                
                // Biletin durumunu güncelle (Kullanıcı yazınca statü "open" olur)
                $upd = $db->prepare("UPDATE support_tickets SET status = 'open', updated_at = NOW() WHERE id = ?");
                $upd->execute([$ticket_id]);
                
                // Mesajı tazelemek için sayfayı yeniden yükle
                header("Location: destek-detay.php?id=" . $ticket_id);
                exit;
            } catch (Exception $e) {
                $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: " . $e->getMessage() . "</div>";
            }
        }
    }
}

// 3. TALEBİ MÜŞTERİ KAPATIRSA
if (isset($_GET['kapat']) && $_GET['kapat'] == 1 && $bilet['status'] != 'closed') {
    $db->prepare("UPDATE support_tickets SET status = 'closed', updated_at = NOW() WHERE id = ?")->execute([$ticket_id]);
    header("Location: destek-detay.php?id=" . $ticket_id);
    exit;
}

// 4. MESAJ GEÇMİŞİNİ ÇEK
// Hem müşterinin hem de adminin yazdıklarını sırayla çekiyoruz.
$msg_stmt = $db->prepare("SELECT * FROM ticket_messages WHERE ticket_id = ? ORDER BY created_at ASC");
$msg_stmt->execute([$ticket_id]);
$mesajlar = $msg_stmt->fetchAll();

require_once '../header.php';
?>

<div class="container py-5 text-dark">
    <div class="row">
         <div class="col-lg-3 mb-4">
            <?php include 'sidebar.php'; ?>
        </div>

        <div class="col-lg-9">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2 class="fw-bold mb-0"><a href="destek.php" class="text-dark text-decoration-none"><i class="bi bi-arrow-left me-2"></i>Talep #<?= $bilet['id'] ?></a></h2>
                <div><?= getStatusBadge($bilet['status'], 'ticket') ?></div>
            </div>
            
            <?= $mesaj ?>

            <div class="card shadow-sm border-0 rounded-4 overflow-hidden d-flex flex-column" style="min-height: 500px; background-color: #f8f9fa;">
                
                <div class="card-header bg-white py-3 border-bottom d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-0 fw-bold text-dark">Konu: <?= htmlspecialchars($bilet['subject']) ?></h6>
                        <small class="text-muted">Açılış: <?= date('d.m.Y H:i', strtotime($bilet['created_at'])) ?></small>
                    </div>
                    <?php if($bilet['status'] != 'closed'): ?>
                        <a href="?id=<?= $ticket_id ?>&kapat=1" class="btn btn-sm btn-outline-danger rounded-pill px-3" onclick="return confirm('Talebi kapatmak istediğinize emin misiniz?')">Talebi Kapat</a>
                    <?php endif; ?>
                </div>

                <div class="card-body p-4 overflow-auto flex-grow-1" id="chatContainer">
                    
                    <?php foreach($mesajlar as $msg): ?>
                        <?php if($msg['sender_id'] == $user_id): // Müşterinin (Senin) Mesajın ?>
                            <div class="d-flex flex-column align-items-end mb-3">
                                <div class="bg-primary text-white rounded-4 rounded-bottom-0 rounded-start px-3 py-2 shadow-sm" style="max-width: 75%;">
                                    <?= nl2br(htmlspecialchars($msg['message'])) ?>
                                </div>
                                <small class="text-muted mt-1" style="font-size: 11px;"><?= date('d.m.Y H:i', strtotime($msg['created_at'])) ?></small>
                            </div>
                        <?php else: // Adminin (Müşteri Temsilcisinin) Cevabı ?>
                            <div class="d-flex flex-column align-items-start mb-3">
                                <span class="small fw-bold text-muted mb-1 ms-1"><i class="bi bi-headset text-success"></i> Müşteri Temsilcisi</span>
                                <div class="bg-white border text-dark rounded-4 rounded-bottom-0 rounded-end px-3 py-2 shadow-sm" style="max-width: 75%;">
                                    <?= nl2br(htmlspecialchars($msg['message'])) ?>
                                </div>
                                <small class="text-muted mt-1" style="font-size: 11px;"><?= date('d.m.Y H:i', strtotime($msg['created_at'])) ?></small>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>

                    <?php 
                    // Eğer admin eski yapıyla direkt bilet üzerinden "admin_reply" attıysa onu da gösterelim (Geriye dönük uyumluluk)
                    if (!empty($bilet['admin_reply'])): 
                    ?>
                        <div class="d-flex flex-column align-items-start mb-3">
                            <span class="small fw-bold text-muted mb-1 ms-1"><i class="bi bi-headset text-success"></i> Müşteri Temsilcisi</span>
                            <div class="bg-white border border-success text-dark rounded-4 rounded-bottom-0 rounded-end px-3 py-2 shadow-sm" style="max-width: 75%;">
                                <?= nl2br(htmlspecialchars($bilet['admin_reply'])) ?>
                            </div>
                            <small class="text-muted mt-1" style="font-size: 11px;"><?= date('d.m.Y H:i', strtotime($bilet['updated_at'])) ?></small>
                        </div>
                    <?php endif; ?>
                    
                </div>

                <div class="card-footer bg-white p-3 border-top">
                    <?php if($bilet['status'] != 'closed'): ?>
                        <form method="POST" action="destek-detay.php?id=<?= $ticket_id ?>">
                            <div class="input-group">
                                <input type="text" name="message" class="form-control form-control-lg border-2 bg-light" placeholder="Cevabınızı buraya yazın..." required autocomplete="off">
                                <button class="btn btn-primary px-4 fw-bold" type="submit" name="cevap_yaz"><i class="bi bi-send-fill me-1"></i> Gönder</button>
                            </div>
                        </form>
                    <?php else: ?>
                        <div class="text-center text-muted fw-bold py-2">
                            <i class="bi bi-lock-fill me-1"></i> Bu destek talebi kapatılmıştır. Yeni bir sorunuz varsa yeni talep açabilirsiniz.
                        </div>
                    <?php endif; ?>
                </div>

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

<script>
    var chatContainer = document.getElementById("chatContainer");
    chatContainer.scrollTop = chatContainer.scrollHeight;
</script>

<?php require_once '../footer.php'; ?>