<?php
/**
 * Admin - Destek Talepleri Yönetimi
 * Tek dosyada liste + detay + yanıtlama + e-posta bildirimi
 * @version 1.1.0
 */

// Header'dan ÖNCE yapılması gereken işlemler
require_once __DIR__ . '/../config.php';

// Admin kontrolü
if (!isLoggedIn() || !isAdmin()) {
    setFlash('error', 'Bu sayfaya erişim yetkiniz yok.');
    header('Location: ' . SITE_URL . '/giris.php');
    exit;
}

// ==================== E-POSTA FONKSİYONLARI ====================

/**
 * SMTP Ayarı oku
 */
function getSmtpSetting($db, $key, $default = '') {
    try {
        $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $value = $stmt->fetchColumn();
        return $value !== false ? $value : $default;
    } catch (PDOException $e) {
        return $default;
    }
}

/**
 * Mail şablonu oluştur
 */
function buildSupportEmailTemplate($siteName, $title, $content, $ticketNumber, $buttonText = '', $buttonUrl = '', $color = '#6366f1') {
    $buttonHtml = '';
    if ($buttonText && $buttonUrl) {
        $buttonHtml = '
        <div style="text-align:center;margin:30px 0;">
            <a href="' . htmlspecialchars($buttonUrl) . '" style="display:inline-block;background:linear-gradient(135deg,' . $color . ',#8b5cf6);color:#fff;text-decoration:none;padding:16px 40px;border-radius:12px;font-weight:600;font-size:15px;">
                ' . htmlspecialchars($buttonText) . '
            </a>
        </div>';
    }
    
    return '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin:0;padding:0;background:#0f172a;font-family:Arial,Helvetica,sans-serif;">
    <div style="max-width:600px;margin:0 auto;padding:40px 20px;">
        <div style="background:#1e293b;border-radius:24px;overflow:hidden;border:1px solid #334155;">
            
            <!-- Header -->
            <div style="background:linear-gradient(135deg,' . $color . ',#8b5cf6);padding:40px 30px;text-align:center;">
                <h1 style="margin:0;color:#fff;font-size:24px;font-weight:700;">' . htmlspecialchars($title) . '</h1>
                <p style="margin:10px 0 0;color:rgba(255,255,255,0.9);font-size:14px;">Talep No: <strong>' . htmlspecialchars($ticketNumber) . '</strong></p>
            </div>
            
            <!-- Body -->
            <div style="padding:40px 30px;">
                <div style="color:#e2e8f0;font-size:15px;line-height:1.8;">
                    ' . $content . '
                </div>
                
                ' . $buttonHtml . '
            </div>
            
            <!-- Footer -->
            <div style="background:#0f172a;padding:25px 30px;text-align:center;border-top:1px solid #1e293b;">
                <p style="color:#64748b;font-size:13px;margin:0 0 10px;">
                    Bu e-posta ' . htmlspecialchars($siteName) . ' destek sistemi tarafından gönderilmiştir.
                </p>
                <p style="color:#64748b;font-size:13px;margin:0;">
                    © ' . date('Y') . ' ' . htmlspecialchars($siteName) . ' - Tüm hakları saklıdır.
                </p>
            </div>
            
        </div>
    </div>
</body>
</html>';
}

/**
 * Destek maili gönder
 */
function sendSupportMail($db, $settings, $toEmail, $toName, $subject, $body) {
    // PHPMailer kontrol
    $phpmailerPath = __DIR__ . '/../includes/PHPMailer/PHPMailer.php';
    if (!file_exists($phpmailerPath)) {
        return ['success' => false, 'error' => 'PHPMailer kütüphanesi bulunamadı.'];
    }
    
    // SMTP aktif mi?
    $smtpEnabled = getSmtpSetting($db, 'smtp_enabled', '0');
    if ($smtpEnabled !== '1') {
        return ['success' => false, 'error' => 'SMTP devre dışı.'];
    }
    
    require_once __DIR__ . '/../includes/PHPMailer/Exception.php';
    require_once __DIR__ . '/../includes/PHPMailer/PHPMailer.php';
    require_once __DIR__ . '/../includes/PHPMailer/SMTP.php';
    
    $smtpHost = getSmtpSetting($db, 'smtp_host', '');
    $smtpPort = (int)getSmtpSetting($db, 'smtp_port', 587);
    $smtpUsername = getSmtpSetting($db, 'smtp_username', '');
    $smtpPassword = getSmtpSetting($db, 'smtp_password', '');
    $smtpEncryption = getSmtpSetting($db, 'smtp_encryption', 'tls');
    $smtpFromEmail = getSmtpSetting($db, 'smtp_from_email', $smtpUsername);
    $smtpFromName = getSmtpSetting($db, 'smtp_from_name', $settings->get('site_name', 'SMM Panel'));
    
    if (empty($smtpHost) || empty($smtpUsername) || empty($smtpPassword)) {
        return ['success' => false, 'error' => 'SMTP ayarları eksik.'];
    }
    
    try {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        
        $mail->isSMTP();
        $mail->Host = $smtpHost;
        $mail->Port = $smtpPort;
        $mail->SMTPAuth = true;
        $mail->Username = $smtpUsername;
        $mail->Password = $smtpPassword;
        
        if ($smtpEncryption === 'tls') {
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        } elseif ($smtpEncryption === 'ssl') {
            $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = false;
            $mail->SMTPAutoTLS = false;
        }
        
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];
        
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        
        $mail->setFrom($smtpFromEmail, $smtpFromName);
        $mail->addReplyTo($smtpFromEmail, $smtpFromName);
        $mail->addAddress($toEmail, $toName);
        
        $mail->isHTML(true);
        $mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
        $mail->Body = $body;
        $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $body));
        
        $mail->send();
        
        return ['success' => true];
        
    } catch (PHPMailer\PHPMailer\Exception $e) {
        return ['success' => false, 'error' => $mail->ErrorInfo];
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

// ==================== YAPILANDIRMA ====================

// Users tablosu kolon adını bul
$userNameColumn = 'username';
try {
    $columns = $db->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
    if (in_array('name', $columns)) {
        $userNameColumn = 'name';
    } elseif (in_array('username', $columns)) {
        $userNameColumn = 'username';
    } elseif (in_array('full_name', $columns)) {
        $userNameColumn = 'full_name';
    }
} catch (PDOException $e) {
    $userNameColumn = 'username';
}

$statusLabels = [
    'open' => 'Açık',
    'answered' => 'Yanıtlandı',
    'waiting' => 'Bekliyor',
    'closed' => 'Kapatıldı'
];

// ==================== DURUM GÜNCELLE ====================
if (isset($_POST['update_status']) && isset($_POST['ticket_id'])) {
    $ticketId = (int)$_POST['ticket_id'];
    $newStatus = $_POST['status'] ?? 'open';
    
    $validStatuses = ['open', 'answered', 'waiting', 'closed'];
    if (in_array($newStatus, $validStatuses)) {
        // Önce ticket bilgisini al
        $stmt = $db->prepare("SELECT t.*, u.{$userNameColumn} as user_name, u.email as user_email FROM support_tickets t LEFT JOIN users u ON t.user_id = u.id WHERE t.id = ?");
        $stmt->execute([$ticketId]);
        $ticketData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($ticketData) {
            $oldStatus = $ticketData['status'];
            
            // Durumu güncelle
            $db->prepare("UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?")->execute([$newStatus, $ticketId]);
            
            // Durum değiştiyse e-posta gönder
            if ($oldStatus !== $newStatus) {
                $recipientEmail = $ticketData['user_id'] ? $ticketData['user_email'] : $ticketData['guest_email'];
                $recipientName = $ticketData['user_id'] ? $ticketData['user_name'] : $ticketData['guest_name'];
                
                if ($recipientEmail) {
                    $siteName = $settings->get('site_name', 'SMM Panel');
                    $ticketUrl = SITE_URL . '/destek.php?ticket=' . $ticketData['ticket_number'];
                    
                    $emailSubject = "Destek Talebi Durum Güncelleme - " . $ticketData['ticket_number'];
                    $emailTitle = "Talep Durumu Güncellendi";
                    
                    $emailContent = '
                        <p style="margin:0 0 15px;">Merhaba <strong>' . htmlspecialchars($recipientName) . '</strong>,</p>
                        <p style="margin:0 0 20px;"><strong>' . htmlspecialchars($ticketData['ticket_number']) . '</strong> numaralı destek talebinizin durumu güncellenmiştir.</p>
                        
                        <div style="background:#0f172a;border-radius:12px;padding:20px;margin:20px 0;">
                            <table style="width:100%;border-collapse:collapse;">
                                <tr>
                                    <td style="padding:8px 0;color:#94a3b8;font-size:13px;">Konu:</td>
                                    <td style="padding:8px 0;color:#fff;font-size:14px;font-weight:600;">' . htmlspecialchars($ticketData['subject']) . '</td>
                                </tr>
                                <tr>
                                    <td style="padding:8px 0;color:#94a3b8;font-size:13px;">Eski Durum:</td>
                                    <td style="padding:8px 0;color:#f59e0b;font-size:14px;">' . $statusLabels[$oldStatus] . '</td>
                                </tr>
                                <tr>
                                    <td style="padding:8px 0;color:#94a3b8;font-size:13px;">Yeni Durum:</td>
                                    <td style="padding:8px 0;color:#10b981;font-size:14px;font-weight:600;">' . $statusLabels[$newStatus] . '</td>
                                </tr>
                            </table>
                        </div>
                        
                        <p style="margin:20px 0 0;color:#94a3b8;font-size:13px;">Talebinizi görüntülemek için aşağıdaki butona tıklayabilirsiniz.</p>
                    ';
                    
                    $emailBody = buildSupportEmailTemplate($siteName, $emailTitle, $emailContent, $ticketData['ticket_number'], 'Talebi Görüntüle', $ticketUrl, '#8b5cf6');
                    
                    @sendSupportMail($db, $settings, $recipientEmail, $recipientName, $emailSubject, $emailBody);
                }
            }
            
            setFlash('success', 'Durum güncellendi.');
        }
    }
    
    header('Location: ' . SITE_URL . '/admin/destek-talepleri.php' . (isset($_GET['id']) ? '?id=' . $ticketId : ''));
    exit;
}

// ==================== TALEP SİL ====================
if (isset($_GET['delete'])) {
    $deleteId = (int)$_GET['delete'];
    
    try {
        $db->beginTransaction();
        $db->prepare("DELETE FROM support_messages WHERE ticket_id = ?")->execute([$deleteId]);
        $db->prepare("DELETE FROM support_tickets WHERE id = ?")->execute([$deleteId]);
        $db->commit();
        setFlash('success', 'Talep silindi.');
    } catch (Exception $e) {
        $db->rollBack();
        setFlash('error', 'Talep silinemedi.');
    }
    
    header('Location: ' . SITE_URL . '/admin/destek-talepleri.php');
    exit;
}

// ==================== YANIT GÖNDER ====================
$replyError = '';
if (isset($_POST['send_reply']) && isset($_GET['id'])) {
    $ticketId = (int)$_GET['id'];
    $replyMessage = trim($_POST['reply_message'] ?? '');
    $newStatus = $_POST['new_status'] ?? 'answered';
    
    if (empty($replyMessage)) {
        $replyError = 'Yanıt mesajı boş olamaz.';
    } elseif (strlen($replyMessage) < 5) {
        $replyError = 'Yanıt en az 5 karakter olmalıdır.';
    } else {
        // Ticket bilgisini al
        $stmt = $db->prepare("SELECT t.*, u.{$userNameColumn} as user_name, u.email as user_email FROM support_tickets t LEFT JOIN users u ON t.user_id = u.id WHERE t.id = ?");
        $stmt->execute([$ticketId]);
        $ticketData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($ticketData) {
            // Ek dosyalar
            $attachments = [];
            if (!empty($_FILES['attachments']['name'][0])) {
                $uploadDir = __DIR__ . '/../uploads/support/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                
                $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                $maxSize = 5 * 1024 * 1024;
                
                for ($i = 0; $i < min(count($_FILES['attachments']['name']), 3); $i++) {
                    if ($_FILES['attachments']['error'][$i] === UPLOAD_ERR_OK) {
                        $tmpName = $_FILES['attachments']['tmp_name'][$i];
                        $fileName = $_FILES['attachments']['name'][$i];
                        $fileSize = $_FILES['attachments']['size'][$i];
                        
                        $finfo = finfo_open(FILEINFO_MIME_TYPE);
                        $mimeType = finfo_file($finfo, $tmpName);
                        finfo_close($finfo);
                        
                        if (in_array($mimeType, $allowedTypes) && $fileSize <= $maxSize) {
                            $ext = pathinfo($fileName, PATHINFO_EXTENSION);
                            $newFileName = 'admin_' . time() . '_' . $i . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                            if (move_uploaded_file($tmpName, $uploadDir . $newFileName)) {
                                $attachments[] = ['name' => $fileName, 'path' => 'uploads/support/' . $newFileName];
                            }
                        }
                    }
                }
            }
            
            try {
                $db->beginTransaction();
                
                // Mesaj ekle
                $stmt = $db->prepare("INSERT INTO support_messages (ticket_id, user_id, is_admin, message, attachments, created_at) VALUES (?, ?, 1, ?, ?, NOW())");
                $stmt->execute([$ticketId, $_SESSION['user_id'], $replyMessage, !empty($attachments) ? json_encode($attachments) : null]);
                
                // Durumu güncelle
                $db->prepare("UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?")->execute([$newStatus, $ticketId]);
                
                $db->commit();
                
                // E-posta bildirimi gönder
                $recipientEmail = $ticketData['user_id'] ? $ticketData['user_email'] : $ticketData['guest_email'];
                $recipientName = $ticketData['user_id'] ? $ticketData['user_name'] : $ticketData['guest_name'];
                
                if ($recipientEmail) {
                    $siteName = $settings->get('site_name', 'SMM Panel');
                    $ticketUrl = SITE_URL . '/destek.php?ticket=' . $ticketData['ticket_number'];
                    
                    $emailSubject = "Destek Talebinize Yanıt Verildi - " . $ticketData['ticket_number'];
                    $emailTitle = "Yeni Yanıt Aldınız!";
                    
                    $emailContent = '
                        <p style="margin:0 0 15px;">Merhaba <strong>' . htmlspecialchars($recipientName) . '</strong>,</p>
                        <p style="margin:0 0 20px;"><strong>' . htmlspecialchars($ticketData['ticket_number']) . '</strong> numaralı destek talebinize yanıt verildi.</p>
                        
                        <div style="background:#0f172a;border-radius:12px;padding:20px;margin:20px 0;">
                            <p style="margin:0 0 10px;color:#94a3b8;font-size:12px;text-transform:uppercase;letter-spacing:1px;">Talep Konusu</p>
                            <p style="margin:0;color:#fff;font-size:15px;font-weight:600;">' . htmlspecialchars($ticketData['subject']) . '</p>
                        </div>
                        
                        <div style="background:rgba(16,185,129,0.1);border:1px solid rgba(16,185,129,0.2);border-radius:12px;padding:20px;margin:20px 0;">
                            <p style="margin:0 0 10px;color:#10b981;font-size:12px;text-transform:uppercase;letter-spacing:1px;font-weight:600;">
                                <span style="margin-right:6px;">💬</span> Destek Ekibi Yanıtı
                            </p>
                            <p style="margin:0;color:#e2e8f0;font-size:14px;line-height:1.7;white-space:pre-wrap;">' . htmlspecialchars($replyMessage) . '</p>
                        </div>
                        
                        <p style="margin:20px 0 0;color:#94a3b8;font-size:13px;">Bu mesaja cevap vermek veya talebinizi görüntülemek için aşağıdaki butona tıklayın.</p>
                    ';
                    
                    $emailBody = buildSupportEmailTemplate($siteName, $emailTitle, $emailContent, $ticketData['ticket_number'], 'Yanıtla', $ticketUrl, '#10b981');
                    
                    $mailResult = sendSupportMail($db, $settings, $recipientEmail, $recipientName, $emailSubject, $emailBody);
                    
                    if ($mailResult['success']) {
                        setFlash('success', 'Yanıt gönderildi ve e-posta bildirimi yapıldı.');
                    } else {
                        setFlash('success', 'Yanıt gönderildi. (E-posta gönderilemedi: ' . $mailResult['error'] . ')');
                    }
                } else {
                    setFlash('success', 'Yanıt başarıyla gönderildi.');
                }
                
                header('Location: ' . SITE_URL . '/admin/destek-talepleri.php?id=' . $ticketId);
                exit;
                
            } catch (Exception $e) {
                $db->rollBack();
                $replyError = 'Yanıt gönderilemedi: ' . $e->getMessage();
            }
        }
    }
}

// ==================== HEADER DAHİL ====================
$adminPageTitle = 'Destek Talepleri';
require_once __DIR__ . '/header.php';

$categories = [
    'general' => 'Genel Soru',
    'order' => 'Sipariş Sorunu',
    'payment' => 'Ödeme Sorunu',
    'technical' => 'Teknik Sorun',
    'refund' => 'İade Talebi',
    'other' => 'Diğer'
];

$priorities = [
    'low' => ['Düşük', '#6b7280'],
    'normal' => ['Normal', '#3b82f6'],
    'high' => ['Yüksek', '#f59e0b'],
    'urgent' => ['Acil', '#ef4444']
];

$statuses = [
    'open' => ['Açık', '#3b82f6', 'fas fa-envelope-open'],
    'answered' => ['Yanıtlandı', '#10b981', 'fas fa-check'],
    'waiting' => ['Bekliyor', '#f59e0b', 'fas fa-clock'],
    'closed' => ['Kapatıldı', '#6b7280', 'fas fa-times-circle']
];

$errors = [];
if ($replyError) $errors[] = $replyError;

$currentView = isset($_GET['id']) ? 'detail' : 'list';
$selectedTicket = null;
$ticketMessages = [];

// Talep detayı
if (isset($_GET['id'])) {
    $ticketId = (int)$_GET['id'];
    
    $stmt = $db->prepare("
        SELECT t.*, 
               u.{$userNameColumn} as user_name, 
               u.email as user_email,
               o.order_number as linked_order_number
        FROM support_tickets t 
        LEFT JOIN users u ON t.user_id = u.id 
        LEFT JOIN orders o ON t.order_id = o.id
        WHERE t.id = ?
    ");
    $stmt->execute([$ticketId]);
    $selectedTicket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($selectedTicket) {
        $msgStmt = $db->prepare("SELECT m.*, u.{$userNameColumn} as sender_name FROM support_messages m LEFT JOIN users u ON m.user_id = u.id WHERE m.ticket_id = ? ORDER BY m.created_at ASC");
        $msgStmt->execute([$ticketId]);
        $ticketMessages = $msgStmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $errors[] = 'Talep bulunamadı.';
        $currentView = 'list';
    }
}

// Filtreler
$filterStatus = $_GET['status'] ?? '';
$filterCategory = $_GET['category'] ?? '';
$filterPriority = $_GET['priority'] ?? '';
$searchQuery = trim($_GET['q'] ?? '');

// Talepleri çek
$tickets = [];
if ($currentView === 'list') {
    $sql = "SELECT t.*, 
                   u.{$userNameColumn} as user_name, 
                   u.email as user_email,
                   (SELECT COUNT(*) FROM support_messages WHERE ticket_id = t.id) as message_count
            FROM support_tickets t 
            LEFT JOIN users u ON t.user_id = u.id 
            WHERE 1=1";
    $params = [];
    
    if ($filterStatus) {
        $sql .= " AND t.status = ?";
        $params[] = $filterStatus;
    }
    if ($filterCategory) {
        $sql .= " AND t.category = ?";
        $params[] = $filterCategory;
    }
    if ($filterPriority) {
        $sql .= " AND t.priority = ?";
        $params[] = $filterPriority;
    }
    if ($searchQuery) {
        $sql .= " AND (t.ticket_number LIKE ? OR t.subject LIKE ? OR t.guest_email LIKE ? OR t.guest_name LIKE ? OR u.email LIKE ?)";
        $searchParam = "%{$searchQuery}%";
        $params = array_merge($params, [$searchParam, $searchParam, $searchParam, $searchParam, $searchParam]);
    }
    
    $sql .= " ORDER BY 
              CASE t.status WHEN 'open' THEN 1 WHEN 'waiting' THEN 2 WHEN 'answered' THEN 3 WHEN 'closed' THEN 4 END,
              CASE t.priority WHEN 'urgent' THEN 1 WHEN 'high' THEN 2 WHEN 'normal' THEN 3 WHEN 'low' THEN 4 END,
              t.created_at DESC";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// İstatistikler
try {
    $stats = [
        'total' => $db->query("SELECT COUNT(*) FROM support_tickets")->fetchColumn(),
        'open' => $db->query("SELECT COUNT(*) FROM support_tickets WHERE status = 'open'")->fetchColumn(),
        'waiting' => $db->query("SELECT COUNT(*) FROM support_tickets WHERE status = 'waiting'")->fetchColumn(),
        'answered' => $db->query("SELECT COUNT(*) FROM support_tickets WHERE status = 'answered'")->fetchColumn(),
        'closed' => $db->query("SELECT COUNT(*) FROM support_tickets WHERE status = 'closed'")->fetchColumn(),
    ];
} catch (PDOException $e) {
    $stats = ['total' => 0, 'open' => 0, 'waiting' => 0, 'answered' => 0, 'closed' => 0];
}
?>

<style>
.stats-row { display: grid; grid-template-columns: repeat(5, 1fr); gap: 15px; margin-bottom: 25px; }
.stat-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 18px; text-align: center; transition: all 0.2s; }
.stat-card:hover { border-color: rgba(var(--primary-rgb), 0.3); }
.stat-card.active { border-color: var(--primary); background: rgba(var(--primary-rgb), 0.1); }
.stat-card h3 { font-size: 28px; font-weight: 800; margin: 0 0 5px; }
.stat-card p { font-size: 12px; color: var(--text-muted); margin: 0; text-transform: uppercase; letter-spacing: 0.5px; }
.stat-card a { display: block; color: inherit; }

.filters-row { display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; }
.filters-row .form-control, .filters-row .form-select { max-width: 180px; padding: 10px 14px; font-size: 13px; }
.filters-row .search-input { min-width: 250px; }

.ticket-table { width: 100%; }
.ticket-table th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-muted); font-weight: 600; padding: 12px 15px; background: rgba(0,0,0,0.15); border-bottom: 1px solid var(--border-color); }
.ticket-table td { padding: 15px; border-bottom: 1px solid var(--border-color); vertical-align: middle; }
.ticket-table tr:hover { background: rgba(var(--primary-rgb), 0.03); }
.ticket-table tr:last-child td { border-bottom: none; }

.ticket-number { font-family: monospace; font-weight: 600; color: var(--primary); font-size: 13px; }
.ticket-subject { font-weight: 600; color: var(--text-primary); margin-bottom: 4px; max-width: 300px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.ticket-meta { font-size: 12px; color: var(--text-muted); }

.ticket-user { display: flex; align-items: center; gap: 10px; }
.ticket-avatar { width: 36px; height: 36px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 13px; flex-shrink: 0; }
.ticket-avatar.user { background: var(--gradient); color: #fff; }
.ticket-avatar.guest { background: var(--bg-hover); color: var(--text-secondary); }
.ticket-user-info h6 { font-size: 13px; font-weight: 600; margin: 0; }
.ticket-user-info span { font-size: 11px; color: var(--text-muted); }

.priority-badge { display: inline-flex; align-items: center; gap: 5px; padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 600; }
.message-count { background: var(--bg-hover); padding: 4px 10px; border-radius: 15px; font-size: 11px; color: var(--text-secondary); }

.actions-cell { display: flex; gap: 6px; }
.action-btn { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 13px; transition: all 0.2s; border: none; cursor: pointer; }
.action-btn.view { background: rgba(59, 130, 246, 0.15); color: #3b82f6; }
.action-btn.view:hover { background: #3b82f6; color: #fff; }
.action-btn.delete { background: rgba(239, 68, 68, 0.15); color: #ef4444; }
.action-btn.delete:hover { background: #ef4444; color: #fff; }

.back-link { display: inline-flex; align-items: center; gap: 8px; color: var(--text-secondary); font-size: 13px; margin-bottom: 20px; transition: color 0.2s; }
.back-link:hover { color: var(--primary); }

.ticket-detail-header { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; padding: 25px; margin-bottom: 25px; }
.ticket-detail-top { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 20px; margin-bottom: 20px; }
.ticket-detail-title h2 { font-size: 20px; font-weight: 700; margin: 0 0 8px; }
.ticket-detail-title .ticket-number { font-size: 14px; }
.ticket-detail-actions { display: flex; gap: 10px; flex-wrap: wrap; }

.ticket-info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; padding-top: 20px; border-top: 1px solid var(--border-color); }
.ticket-info-item { display: flex; align-items: center; gap: 12px; }
.ticket-info-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; }
.ticket-info-content h6 { font-size: 11px; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; margin: 0 0 3px; }
.ticket-info-content p { font-size: 14px; font-weight: 600; margin: 0; }

.messages-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; margin-bottom: 25px; }
.messages-header { padding: 18px 25px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; justify-content: space-between; }
.messages-header h3 { font-size: 16px; font-weight: 600; margin: 0; display: flex; align-items: center; gap: 10px; }
.messages-header h3 i { color: var(--primary); }
.messages-body { padding: 25px; max-height: 500px; overflow-y: auto; }

.message-item { display: flex; gap: 15px; margin-bottom: 25px; }
.message-item:last-child { margin-bottom: 0; }
.message-item.admin { flex-direction: row-reverse; }
.message-avatar { width: 42px; height: 42px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 15px; flex-shrink: 0; }
.message-item:not(.admin) .message-avatar { background: var(--gradient); color: #fff; }
.message-item.admin .message-avatar { background: linear-gradient(135deg, #10b981, #059669); color: #fff; }
.message-bubble { flex: 1; max-width: 75%; background: rgba(255,255,255,0.03); border: 1px solid var(--border-color); border-radius: 14px; padding: 16px 20px; }
.message-item.admin .message-bubble { background: rgba(16, 185, 129, 0.08); border-color: rgba(16, 185, 129, 0.2); }
.message-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.message-sender { font-weight: 600; font-size: 13px; }
.message-item.admin .message-sender { color: #10b981; }
.message-time { font-size: 11px; color: var(--text-muted); }
.message-text { font-size: 14px; line-height: 1.6; color: var(--text-secondary); white-space: pre-wrap; }
.message-attachments { display: flex; gap: 10px; margin-top: 12px; flex-wrap: wrap; }
.message-attachment { width: 70px; height: 70px; border-radius: 8px; overflow: hidden; border: 1px solid var(--border-color); }
.message-attachment img { width: 100%; height: 100%; object-fit: cover; }

.reply-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; }
.reply-header { padding: 18px 25px; border-bottom: 1px solid var(--border-color); }
.reply-header h3 { font-size: 16px; font-weight: 600; margin: 0; display: flex; align-items: center; gap: 10px; }
.reply-header h3 i { color: var(--primary); }
.reply-body { padding: 25px; }
.reply-actions { display: flex; justify-content: space-between; align-items: center; gap: 15px; flex-wrap: wrap; }
.reply-actions .left { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }

.file-upload-btn { display: inline-flex; align-items: center; gap: 8px; padding: 10px 16px; background: var(--bg-hover); border: 1px solid var(--border-color); border-radius: 10px; color: var(--text-secondary); font-size: 13px; cursor: pointer; transition: all 0.2s; }
.file-upload-btn:hover { background: var(--bg-dark); color: var(--text-primary); }
.file-upload-btn input { display: none; }

.order-link { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: rgba(139, 92, 246, 0.15); color: #8b5cf6; border-radius: 6px; font-size: 12px; font-weight: 600; }
.order-link:hover { background: rgba(139, 92, 246, 0.25); color: #8b5cf6; }

@media (max-width: 1200px) { .stats-row { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 768px) {
    .stats-row { grid-template-columns: repeat(2, 1fr); }
    .stat-card h3 { font-size: 22px; }
    .filters-row .form-control, .filters-row .form-select { max-width: 100%; flex: 1; }
    .ticket-detail-top { flex-direction: column; }
    .message-bubble { max-width: 90%; }
    .reply-actions { flex-direction: column; align-items: stretch; }
    .reply-actions .left { justify-content: space-between; }
}
@media (max-width: 576px) { .stats-row { grid-template-columns: 1fr; } }
</style>

<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
    <i class="fas fa-exclamation-circle"></i>
    <?php echo implode('<br>', $errors); ?>
</div>
<?php endif; ?>

<?php if ($currentView === 'list'): ?>

<div class="stats-row">
    <div class="stat-card <?php echo !$filterStatus ? 'active' : ''; ?>">
        <a href="?"><h3><?php echo $stats['total']; ?></h3><p>Toplam</p></a>
    </div>
    <div class="stat-card <?php echo $filterStatus === 'open' ? 'active' : ''; ?>">
        <a href="?status=open"><h3 style="color: #3b82f6;"><?php echo $stats['open']; ?></h3><p>Açık</p></a>
    </div>
    <div class="stat-card <?php echo $filterStatus === 'waiting' ? 'active' : ''; ?>">
        <a href="?status=waiting"><h3 style="color: #f59e0b;"><?php echo $stats['waiting']; ?></h3><p>Bekliyor</p></a>
    </div>
    <div class="stat-card <?php echo $filterStatus === 'answered' ? 'active' : ''; ?>">
        <a href="?status=answered"><h3 style="color: #10b981;"><?php echo $stats['answered']; ?></h3><p>Yanıtlandı</p></a>
    </div>
    <div class="stat-card <?php echo $filterStatus === 'closed' ? 'active' : ''; ?>">
        <a href="?status=closed"><h3 style="color: #6b7280;"><?php echo $stats['closed']; ?></h3><p>Kapatıldı</p></a>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="card-title"><i class="fas fa-headset"></i> Destek Talepleri</h5>
    </div>
    <div class="card-body">
        <form method="GET" class="filters-row">
            <input type="text" name="q" class="form-control search-input" placeholder="Ara... (Ticket no, konu, email, isim)" value="<?php echo clean($searchQuery); ?>">
            <select name="status" class="form-select" onchange="this.form.submit()">
                <option value="">Tüm Durumlar</option>
                <?php foreach ($statuses as $key => $val): ?>
                <option value="<?php echo $key; ?>" <?php echo $filterStatus === $key ? 'selected' : ''; ?>><?php echo $val[0]; ?></option>
                <?php endforeach; ?>
            </select>
            <select name="category" class="form-select" onchange="this.form.submit()">
                <option value="">Tüm Kategoriler</option>
                <?php foreach ($categories as $key => $val): ?>
                <option value="<?php echo $key; ?>" <?php echo $filterCategory === $key ? 'selected' : ''; ?>><?php echo $val; ?></option>
                <?php endforeach; ?>
            </select>
            <select name="priority" class="form-select" onchange="this.form.submit()">
                <option value="">Tüm Öncelikler</option>
                <?php foreach ($priorities as $key => $val): ?>
                <option value="<?php echo $key; ?>" <?php echo $filterPriority === $key ? 'selected' : ''; ?>><?php echo $val[0]; ?></option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="btn-primary-custom btn-sm"><i class="fas fa-search"></i> Ara</button>
            <?php if ($filterStatus || $filterCategory || $filterPriority || $searchQuery): ?>
            <a href="?" class="btn-secondary-custom btn-sm"><i class="fas fa-times"></i> Temizle</a>
            <?php endif; ?>
        </form>
        
        <?php if (empty($tickets)): ?>
        <div class="empty-state">
            <i class="fas fa-inbox"></i>
            <h4>Talep Bulunamadı</h4>
            <p>Arama kriterlerinize uygun destek talebi yok.</p>
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="ticket-table">
                <thead>
                    <tr>
                        <th>Talep</th>
                        <th>Gönderen</th>
                        <th>Kategori</th>
                        <th>Öncelik</th>
                        <th>Durum</th>
                        <th>Mesaj</th>
                        <th>Tarih</th>
                        <th>İşlem</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($tickets as $ticket): 
                        $isUser = !empty($ticket['user_id']);
                        $displayName = $isUser ? ($ticket['user_name'] ?? 'Üye') : ($ticket['guest_name'] ?? 'Misafir');
                        $displayEmail = $isUser ? ($ticket['user_email'] ?? '') : ($ticket['guest_email'] ?? '');
                    ?>
                    <tr>
                        <td>
                            <a href="?id=<?php echo $ticket['id']; ?>" class="ticket-number"><?php echo $ticket['ticket_number']; ?></a>
                            <div class="ticket-subject"><?php echo clean($ticket['subject']); ?></div>
                        </td>
                        <td>
                            <div class="ticket-user">
                                <div class="ticket-avatar <?php echo $isUser ? 'user' : 'guest'; ?>">
                                    <?php echo strtoupper(mb_substr($displayName, 0, 1, 'UTF-8')); ?>
                                </div>
                                <div class="ticket-user-info">
                                    <h6><?php echo clean($displayName); ?></h6>
                                    <span><?php echo clean($displayEmail); ?></span>
                                </div>
                            </div>
                        </td>
                        <td><span class="ticket-meta"><?php echo $categories[$ticket['category']] ?? 'Genel'; ?></span></td>
                        <td>
                            <span class="priority-badge" style="background: <?php echo $priorities[$ticket['priority']][1]; ?>22; color: <?php echo $priorities[$ticket['priority']][1]; ?>;">
                                <?php echo $priorities[$ticket['priority']][0]; ?>
                            </span>
                        </td>
                        <td>
                            <span class="status-badge" style="background: <?php echo $statuses[$ticket['status']][1]; ?>22; color: <?php echo $statuses[$ticket['status']][1]; ?>;">
                                <i class="<?php echo $statuses[$ticket['status']][2]; ?>"></i>
                                <?php echo $statuses[$ticket['status']][0]; ?>
                            </span>
                        </td>
                        <td><span class="message-count"><i class="fas fa-comments me-1"></i><?php echo $ticket['message_count']; ?></span></td>
                        <td><span class="ticket-meta"><?php echo date('d.m.Y H:i', strtotime($ticket['created_at'])); ?></span></td>
                        <td>
                            <div class="actions-cell">
                                <a href="?id=<?php echo $ticket['id']; ?>" class="action-btn view" title="Görüntüle"><i class="fas fa-eye"></i></a>
                                <a href="?delete=<?php echo $ticket['id']; ?>" class="action-btn delete" title="Sil" onclick="return confirm('Bu talebi silmek istediğinize emin misiniz?')"><i class="fas fa-trash"></i></a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php else: ?>

<a href="?" class="back-link"><i class="fas fa-arrow-left"></i> Tüm Taleplere Dön</a>

<?php if ($selectedTicket): 
    $isUser = !empty($selectedTicket['user_id']);
    $displayName = $isUser ? ($selectedTicket['user_name'] ?? 'Üye') : ($selectedTicket['guest_name'] ?? 'Misafir');
    $displayEmail = $isUser ? ($selectedTicket['user_email'] ?? '') : ($selectedTicket['guest_email'] ?? '');
?>

<div class="ticket-detail-header">
    <div class="ticket-detail-top">
        <div class="ticket-detail-title">
            <span class="ticket-number"><i class="fas fa-ticket-alt me-1"></i><?php echo $selectedTicket['ticket_number']; ?></span>
            <h2><?php echo clean($selectedTicket['subject']); ?></h2>
        </div>
        <div class="ticket-detail-actions">
            <form method="POST" style="display: inline-flex; gap: 10px;">
                <input type="hidden" name="update_status" value="1">
                <input type="hidden" name="ticket_id" value="<?php echo $selectedTicket['id']; ?>">
                <select name="status" class="form-select" style="width: auto;" onchange="this.form.submit()">
                    <?php foreach ($statuses as $key => $val): ?>
                    <option value="<?php echo $key; ?>" <?php echo $selectedTicket['status'] === $key ? 'selected' : ''; ?>><?php echo $val[0]; ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
            <a href="?delete=<?php echo $selectedTicket['id']; ?>" class="btn-danger-custom btn-sm" onclick="return confirm('Bu talebi silmek istediğinize emin misiniz?')">
                <i class="fas fa-trash"></i> Sil
            </a>
        </div>
    </div>
    
    <div class="ticket-info-grid">
        <div class="ticket-info-item">
            <div class="ticket-info-icon" style="background: <?php echo $isUser ? 'var(--gradient)' : 'var(--bg-hover)'; ?>; color: <?php echo $isUser ? '#fff' : 'var(--text-secondary)'; ?>;">
                <i class="fas fa-user"></i>
            </div>
            <div class="ticket-info-content">
                <h6>Gönderen</h6>
                <p><?php echo clean($displayName); ?> <?php echo $isUser ? '<span style="color: var(--primary); font-size: 10px;">(Üye)</span>' : '<span style="color: var(--text-muted); font-size: 10px;">(Ziyaretçi)</span>'; ?></p>
            </div>
        </div>
        <div class="ticket-info-item">
            <div class="ticket-info-icon" style="background: rgba(59, 130, 246, 0.15); color: #3b82f6;">
                <i class="fas fa-envelope"></i>
            </div>
            <div class="ticket-info-content">
                <h6>E-posta</h6>
                <p><?php echo clean($displayEmail); ?></p>
            </div>
        </div>
        <?php if (!$isUser && !empty($selectedTicket['guest_phone'])): ?>
        <div class="ticket-info-item">
            <div class="ticket-info-icon" style="background: rgba(16, 185, 129, 0.15); color: #10b981;">
                <i class="fas fa-phone"></i>
            </div>
            <div class="ticket-info-content">
                <h6>Telefon</h6>
                <p><?php echo clean($selectedTicket['guest_phone']); ?></p>
            </div>
        </div>
        <?php endif; ?>
        <div class="ticket-info-item">
            <div class="ticket-info-icon" style="background: rgba(139, 92, 246, 0.15); color: #8b5cf6;">
                <i class="fas fa-folder"></i>
            </div>
            <div class="ticket-info-content">
                <h6>Kategori</h6>
                <p><?php echo $categories[$selectedTicket['category']] ?? 'Genel'; ?></p>
            </div>
        </div>
        <div class="ticket-info-item">
            <div class="ticket-info-icon" style="background: <?php echo $priorities[$selectedTicket['priority']][1]; ?>22; color: <?php echo $priorities[$selectedTicket['priority']][1]; ?>;">
                <i class="fas fa-flag"></i>
            </div>
            <div class="ticket-info-content">
                <h6>Öncelik</h6>
                <p><?php echo $priorities[$selectedTicket['priority']][0]; ?></p>
            </div>
        </div>
        <div class="ticket-info-item">
            <div class="ticket-info-icon" style="background: rgba(245, 158, 11, 0.15); color: #f59e0b;">
                <i class="fas fa-calendar"></i>
            </div>
            <div class="ticket-info-content">
                <h6>Oluşturulma</h6>
                <p><?php echo date('d.m.Y H:i', strtotime($selectedTicket['created_at'])); ?></p>
            </div>
        </div>
        <?php if (!empty($selectedTicket['linked_order_number'])): ?>
        <div class="ticket-info-item">
            <div class="ticket-info-icon" style="background: rgba(139, 92, 246, 0.15); color: #8b5cf6;">
                <i class="fas fa-shopping-cart"></i>
            </div>
            <div class="ticket-info-content">
                <h6>Bağlı Sipariş</h6>
                <p>
                    <a href="<?php echo SITE_URL; ?>/admin/siparis-detay.php?id=<?php echo $selectedTicket['order_id']; ?>" class="order-link">
                        <i class="fas fa-external-link-alt"></i> <?php echo $selectedTicket['linked_order_number']; ?>
                    </a>
                </p>
            </div>
        </div>
        <?php endif; ?>
        <?php if (!$isUser && !empty($selectedTicket['ip_address'])): ?>
        <div class="ticket-info-item">
            <div class="ticket-info-icon" style="background: var(--bg-hover); color: var(--text-secondary);">
                <i class="fas fa-globe"></i>
            </div>
            <div class="ticket-info-content">
                <h6>IP Adresi</h6>
                <p><?php echo clean($selectedTicket['ip_address']); ?></p>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="messages-card">
    <div class="messages-header">
        <h3><i class="fas fa-comments"></i> Mesajlar (<?php echo count($ticketMessages); ?>)</h3>
    </div>
    <div class="messages-body">
        <?php foreach ($ticketMessages as $msg): 
            $isAdmin = $msg['is_admin'];
            $senderName = $isAdmin ? ($msg['sender_name'] ?? 'Admin') : $displayName;
            $msgAttachments = $msg['attachments'] ? json_decode($msg['attachments'], true) : [];
        ?>
        <div class="message-item <?php echo $isAdmin ? 'admin' : ''; ?>">
            <div class="message-avatar">
                <?php if ($isAdmin): ?>
                    <i class="fas fa-headset"></i>
                <?php else: ?>
                    <?php echo strtoupper(mb_substr($senderName, 0, 1, 'UTF-8')); ?>
                <?php endif; ?>
            </div>
            <div class="message-bubble">
                <div class="message-header">
                    <span class="message-sender"><?php echo $isAdmin ? 'Destek Ekibi' : clean($senderName); ?></span>
                    <span class="message-time"><?php echo date('d.m.Y H:i', strtotime($msg['created_at'])); ?></span>
                </div>
                <div class="message-text"><?php echo nl2br(clean($msg['message'])); ?></div>
                <?php if (!empty($msgAttachments)): ?>
                <div class="message-attachments">
                    <?php foreach ($msgAttachments as $att): ?>
                    <a href="<?php echo SITE_URL . '/' . $att['path']; ?>" target="_blank" class="message-attachment">
                        <img src="<?php echo SITE_URL . '/' . $att['path']; ?>" alt="">
                    </a>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php if ($selectedTicket['status'] !== 'closed'): ?>
<div class="reply-card">
    <div class="reply-header">
        <h3><i class="fas fa-reply"></i> Yanıt Gönder</h3>
    </div>
    <div class="reply-body">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="send_reply" value="1">
            
            <div class="mb-3">
                <textarea name="reply_message" class="form-control" rows="5" placeholder="Yanıtınızı yazın..." required></textarea>
            </div>
            
            <div class="reply-actions">
                <div class="left">
                    <label class="file-upload-btn">
                        <i class="fas fa-paperclip"></i> Dosya Ekle
                        <input type="file" name="attachments[]" multiple accept="image/*">
                    </label>
                    
                    <select name="new_status" class="form-select" style="width: auto;">
                        <option value="answered" selected>Yanıtlandı</option>
                        <option value="waiting">Bekliyor</option>
                        <option value="closed">Kapat</option>
                    </select>
                </div>
                
                <button type="submit" class="btn-primary-custom">
                    <i class="fas fa-paper-plane"></i> Yanıt Gönder
                </button>
            </div>
        </form>
    </div>
</div>
<?php else: ?>
<div class="alert alert-info">
    <i class="fas fa-info-circle"></i>
    Bu talep kapatılmış. Yanıt göndermek için durumu değiştirin.
</div>
<?php endif; ?>

<?php endif; ?>
<?php endif; ?>

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