<?php
/**
 * SMM Paket Satış Scripti - Destek Talebi
 * @version 1.1.0
 */

require_once __DIR__ . '/config.php';

$pageTitle = 'Destek Talebi';
$pageDescription = 'Sorularınız ve talepleriniz için destek ekibimizle iletişime geçin.';

$isLoggedIn = isLoggedIn();
$userEmail = $isLoggedIn ? ($_SESSION['user_email'] ?? '') : '';
$userName = $isLoggedIn ? ($_SESSION['user_name'] ?? '') : '';
$userId = $isLoggedIn ? ($_SESSION['user_id'] ?? null) : null;

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

$priorities = [
    'low' => 'Düşük',
    'normal' => 'Normal',
    'high' => 'Yüksek',
    'urgent' => 'Acil'
];

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

$errors = [];
$success = false;
$ticketNumber = '';
$currentView = 'form'; // form, list, detail, track
$selectedTicket = null;
$ticketMessages = [];

// Sayfa görünümünü belirle
if ($isLoggedIn) {
    $currentView = $_GET['view'] ?? 'list';
} else {
    $currentView = $_GET['view'] ?? 'form';
}

// Talep detayı görüntüleme
if (isset($_GET['ticket'])) {
    $ticketCode = trim($_GET['ticket']);
    
    if ($isLoggedIn) {
        // Giriş yapmış kullanıcı için
        $stmt = $db->prepare("SELECT * FROM support_tickets WHERE ticket_number = ? AND user_id = ?");
        $stmt->execute([$ticketCode, $userId]);
    } else {
        // Ziyaretçi için
        $stmt = $db->prepare("SELECT * FROM support_tickets WHERE ticket_number = ? AND user_id IS NULL");
        $stmt->execute([$ticketCode]);
    }
    
    $selectedTicket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($selectedTicket) {
        $currentView = 'detail';
        
        // Mesajları çek
        $msgStmt = $db->prepare("SELECT * FROM support_messages WHERE ticket_id = ? ORDER BY created_at ASC");
        $msgStmt->execute([$selectedTicket['id']]);
        $ticketMessages = $msgStmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $errors[] = 'Talep bulunamadı veya erişim yetkiniz yok.';
        $currentView = $isLoggedIn ? 'list' : 'track';
    }
}

// Takip formu gönderildi
if (isset($_POST['track_ticket'])) {
    $trackCode = trim($_POST['ticket_code'] ?? '');
    $trackEmail = trim($_POST['track_email'] ?? '');
    
    if (empty($trackCode)) {
        $errors[] = 'Talep numarası gereklidir.';
    } elseif (empty($trackEmail)) {
        $errors[] = 'E-posta adresi gereklidir.';
    } else {
        $stmt = $db->prepare("SELECT * FROM support_tickets WHERE ticket_number = ? AND guest_email = ? AND user_id IS NULL");
        $stmt->execute([$trackCode, $trackEmail]);
        $foundTicket = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($foundTicket) {
            header("Location: " . SITE_URL . "/destek.php?ticket=" . $trackCode);
            exit;
        } else {
            $errors[] = 'Talep bulunamadı. Talep numarası ve e-posta adresini kontrol edin.';
        }
    }
    $currentView = 'track';
}

// Yeni mesaj gönderme (talep detayında)
if (isset($_POST['send_reply']) && $selectedTicket) {
    $replyMessage = trim($_POST['reply_message'] ?? '');
    
    if (empty($replyMessage)) {
        $errors[] = 'Mesaj boş olamaz.';
    } elseif (strlen($replyMessage) < 10) {
        $errors[] = 'Mesaj en az 10 karakter olmalıdır.';
    } else {
        // Ek dosyalar
        $attachments = [];
        if (!empty($_FILES['reply_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['reply_attachments']['name']), 3); $i++) {
                if ($_FILES['reply_attachments']['error'][$i] === UPLOAD_ERR_OK) {
                    $tmpName = $_FILES['reply_attachments']['tmp_name'][$i];
                    $fileName = $_FILES['reply_attachments']['name'][$i];
                    $fileSize = $_FILES['reply_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 = 'reply_' . time() . '_' . $i . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                        if (move_uploaded_file($tmpName, $uploadDir . $newFileName)) {
                            $attachments[] = ['name' => $fileName, 'path' => 'uploads/support/' . $newFileName];
                        }
                    }
                }
            }
        }
        
        try {
            $stmt = $db->prepare("INSERT INTO support_messages (ticket_id, user_id, is_admin, message, attachments, created_at) VALUES (?, ?, 0, ?, ?, NOW())");
            $stmt->execute([$selectedTicket['id'], $userId, $replyMessage, !empty($attachments) ? json_encode($attachments) : null]);
            
            // Talebi "waiting" durumuna çek
            $db->prepare("UPDATE support_tickets SET status = 'waiting', updated_at = NOW() WHERE id = ?")->execute([$selectedTicket['id']]);
            
            header("Location: " . SITE_URL . "/destek.php?ticket=" . $selectedTicket['ticket_number'] . "&sent=1");
            exit;
        } catch (Exception $e) {
            $errors[] = 'Mesaj gönderilemedi.';
        }
    }
}

// Yeni talep formu gönderildi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_ticket'])) {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'])) {
        $errors[] = 'Güvenlik hatası. Sayfayı yenileyip tekrar deneyin.';
    } else {
        $subject = trim($_POST['subject'] ?? '');
        $message = trim($_POST['message'] ?? '');
        $category = $_POST['category'] ?? 'general';
        $priority = $_POST['priority'] ?? 'normal';
        $orderNumber = trim($_POST['order_number'] ?? '');
        
        $guestName = '';
        $guestEmail = '';
        $guestPhone = '';
        
        if (!$isLoggedIn) {
            $guestEmail = trim($_POST['email'] ?? '');
            $guestPhone = trim($_POST['phone'] ?? '');
            $guestName = trim($_POST['name'] ?? '');
            
            if (empty($guestEmail) || !filter_var($guestEmail, FILTER_VALIDATE_EMAIL)) {
                $errors[] = 'Geçerli bir e-posta adresi girin.';
            }
            if (empty($guestName)) {
                $errors[] = 'Adınız gereklidir.';
            }
        }
        
        if (empty($subject) || strlen($subject) < 5) {
            $errors[] = 'Konu en az 5 karakter olmalıdır.';
        }
        if (empty($message) || strlen($message) < 20) {
            $errors[] = 'Mesaj en az 20 karakter olmalıdır.';
        }
        
        if (!array_key_exists($category, $categories)) $category = 'general';
        if (!array_key_exists($priority, $priorities)) $priority = 'normal';
        
        $orderId = null;
        if (!empty($orderNumber)) {
            $stmt = $db->prepare("SELECT id FROM orders WHERE order_number = ?");
            $stmt->execute([$orderNumber]);
            $order = $stmt->fetch();
            if ($order) $orderId = $order['id'];
        }
        
        // Fotoğraf yükleme
        $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 = 'ticket_' . time() . '_' . $i . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                        if (move_uploaded_file($tmpName, $uploadDir . $newFileName)) {
                            $attachments[] = ['name' => $fileName, 'path' => 'uploads/support/' . $newFileName];
                        }
                    }
                }
            }
        }
        
        if (empty($errors)) {
            try {
                $db->beginTransaction();
                
                $ticketNumber = 'TKT-' . strtoupper(bin2hex(random_bytes(4)));
                $ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
                
                $stmt = $db->prepare("
                    INSERT INTO support_tickets 
                    (ticket_number, user_id, order_id, subject, category, priority, status, guest_name, guest_email, guest_phone, ip_address, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?, NOW())
                ");
                $stmt->execute([
                    $ticketNumber, $userId, $orderId, $subject, $category, $priority,
                    $isLoggedIn ? null : $guestName,
                    $isLoggedIn ? null : $guestEmail,
                    $isLoggedIn ? null : $guestPhone,
                    $isLoggedIn ? null : $ipAddress
                ]);
                
                $ticketId = $db->lastInsertId();
                
                $stmt = $db->prepare("INSERT INTO support_messages (ticket_id, user_id, is_admin, message, attachments, created_at) VALUES (?, ?, 0, ?, ?, NOW())");
                $stmt->execute([$ticketId, $userId, $message, !empty($attachments) ? json_encode($attachments) : null]);
                
                $db->commit();
                $success = true;
                
                // Telegram bildirimi
                $telegramBotToken = $settings->get('telegram_bot_token');
                $telegramChatId = $settings->get('telegram_chat_id');
                
                if (!empty($telegramBotToken) && !empty($telegramChatId)) {
                    $senderName = $isLoggedIn ? $userName : $guestName;
                    $senderEmail = $isLoggedIn ? $userEmail : $guestEmail;
                    
                    $telegramMsg = "🎫 <b>Yeni Destek Talebi</b>\n\n";
                    $telegramMsg .= "📋 <b>Ticket:</b> <code>{$ticketNumber}</code>\n";
                    $telegramMsg .= "👤 <b>Gönderen:</b> {$senderName}\n";
                    $telegramMsg .= "📧 <b>E-posta:</b> {$senderEmail}\n";
                    $telegramMsg .= "📂 <b>Kategori:</b> {$categories[$category]}\n";
                    $telegramMsg .= "🔔 <b>Öncelik:</b> {$priorities[$priority]}\n";
                    $telegramMsg .= "📝 <b>Konu:</b> {$subject}\n\n";
                    $telegramMsg .= "💬 <b>Mesaj:</b>\n" . mb_substr($message, 0, 500) . (strlen($message) > 500 ? '...' : '');
                    
                    if (!$isLoggedIn && !empty($ipAddress)) {
                        $telegramMsg .= "\n\n🌐 <b>IP:</b> {$ipAddress}";
                    }
                    
                    $telegramUrl = "https://api.telegram.org/bot{$telegramBotToken}/sendMessage";
                    $telegramData = [
                        'chat_id' => $telegramChatId,
                        'text' => $telegramMsg,
                        'parse_mode' => 'HTML'
                    ];
                    
                    $ch = curl_init();
                    curl_setopt_array($ch, [
                        CURLOPT_URL => $telegramUrl,
                        CURLOPT_POST => true,
                        CURLOPT_POSTFIELDS => $telegramData,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_TIMEOUT => 10
                    ]);
                    curl_exec($ch);
                    curl_close($ch);
                }
                
            } catch (Exception $e) {
                $db->rollBack();
                $errors[] = 'Bir hata oluştu: ' . $e->getMessage();
            }
        }
    }
}

// Kullanıcının taleplerini çek
$userTickets = [];
if ($isLoggedIn && $currentView === 'list') {
    $stmt = $db->prepare("SELECT * FROM support_tickets WHERE user_id = ? ORDER BY created_at DESC");
    $stmt->execute([$userId]);
    $userTickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

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

<style>
.support-page { padding: 40px 0 80px; }
.support-header { text-align: center; margin-bottom: 40px; }
.support-header h1 { font-size: 32px; font-weight: 800; margin-bottom: 10px; }
.support-header p { color: rgba(255,255,255,0.6); font-size: 16px; }

.support-tabs { display: flex; justify-content: center; gap: 10px; margin-bottom: 30px; flex-wrap: wrap; }
.support-tab {
    padding: 12px 24px; border-radius: 10px;
    background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
    color: rgba(255,255,255,0.7); font-size: 14px; font-weight: 600;
    text-decoration: none; transition: all 0.3s;
    display: flex; align-items: center; gap: 8px;
}
.support-tab:hover { background: rgba(255,255,255,0.1); color: #fff; }
.support-tab.active { background: var(--gradient); color: #fff; border-color: transparent; }
.support-tab .badge { background: #ef4444; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 10px; }

.support-container { max-width: 900px; margin: 0 auto; }

.support-card {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 20px;
    padding: 30px;
}
.support-card h3 { font-size: 18px; font-weight: 700; margin-bottom: 25px; display: flex; align-items: center; gap: 10px; }
.support-card h3 i { color: var(--primary); }

.form-group { margin-bottom: 20px; }
.form-group label { display: block; font-size: 13px; font-weight: 600; margin-bottom: 8px; color: rgba(255,255,255,0.8); }
.form-group label .required { color: #ef4444; }
.form-group label .optional { color: rgba(255,255,255,0.4); font-weight: 400; font-size: 11px; }

.form-control {
    width: 100%; padding: 12px 16px;
    background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
    border-radius: 10px; color: #fff; font-size: 14px; transition: all 0.3s;
}
.form-control:focus { outline: none; border-color: var(--primary); background: rgba(255,255,255,0.08); }
.form-control::placeholder { color: rgba(255,255,255,0.3); }
textarea.form-control { min-height: 120px; resize: vertical; }

.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }

.user-info-box {
    background: rgba(var(--primary-rgb), 0.1); border: 1px solid rgba(var(--primary-rgb), 0.2);
    border-radius: 12px; padding: 15px; margin-bottom: 20px;
    display: flex; align-items: center; gap: 12px;
}
.user-info-box .avatar {
    width: 45px; height: 45px; background: var(--gradient); border-radius: 10px;
    display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 18px;
}
.user-info-box .info h4 { font-size: 14px; font-weight: 600; margin: 0 0 2px; }
.user-info-box .info p { font-size: 12px; color: rgba(255,255,255,0.6); margin: 0; }

.file-upload-area {
    border: 2px dashed rgba(255,255,255,0.15); border-radius: 12px;
    padding: 20px; text-align: center; cursor: pointer; transition: all 0.3s;
}
.file-upload-area:hover { border-color: var(--primary); background: rgba(var(--primary-rgb), 0.05); }
.file-upload-area i { font-size: 28px; color: var(--primary); margin-bottom: 8px; }
.file-upload-area p { font-size: 12px; color: rgba(255,255,255,0.6); margin: 0; }
.file-upload-area input[type="file"] { display: none; }

.file-preview { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px; }
.file-preview-item { width: 60px; height: 60px; border-radius: 8px; overflow: hidden; border: 1px solid rgba(255,255,255,0.1); }
.file-preview-item img { width: 100%; height: 100%; object-fit: cover; }

.btn-submit {
    width: 100%; padding: 14px 24px;
    background: var(--gradient); border: none; border-radius: 12px;
    color: #fff; font-size: 15px; font-weight: 600; cursor: pointer;
    display: flex; align-items: center; justify-content: center; gap: 10px; transition: all 0.3s;
}
.btn-submit:hover { transform: translateY(-2px); box-shadow: 0 10px 30px rgba(var(--primary-rgb), 0.4); }

.alert-box { padding: 15px 20px; border-radius: 12px; margin-bottom: 20px; display: flex; align-items: flex-start; gap: 12px; }
.alert-box i { font-size: 20px; margin-top: 2px; }
.alert-box.success { background: rgba(16, 185, 129, 0.15); border: 1px solid rgba(16, 185, 129, 0.3); color: #10b981; }
.alert-box.error { background: rgba(239, 68, 68, 0.15); border: 1px solid rgba(239, 68, 68, 0.3); color: #ef4444; }
.alert-box.info { background: rgba(59, 130, 246, 0.15); border: 1px solid rgba(59, 130, 246, 0.3); color: #3b82f6; }
.alert-box .content h4 { font-size: 15px; font-weight: 600; margin-bottom: 5px; }
.alert-box .content p { font-size: 13px; margin: 0; opacity: 0.9; }
.alert-box .content ul { margin: 10px 0 0; padding-left: 20px; }

.ticket-number-display {
    font-family: monospace; font-size: 20px; font-weight: 700;
    background: rgba(255,255,255,0.1); padding: 10px 20px; border-radius: 8px;
    display: inline-block; margin: 15px 0;
}

.success-actions { display: flex; gap: 10px; margin-top: 20px; flex-wrap: wrap; }
.success-actions .btn {
    padding: 10px 20px; border-radius: 8px; font-size: 13px; font-weight: 600;
    text-decoration: none; display: inline-flex; align-items: center; gap: 8px;
}
.success-actions .btn-primary { background: var(--gradient); color: #fff; }
.success-actions .btn-secondary { background: rgba(255,255,255,0.1); color: #fff; }

/* Ticket List */
.ticket-list { display: flex; flex-direction: column; gap: 15px; }
.ticket-item {
    background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08);
    border-radius: 14px; padding: 20px; transition: all 0.3s; cursor: pointer;
    text-decoration: none; color: inherit;
}
.ticket-item:hover { border-color: rgba(var(--primary-rgb), 0.3); transform: translateX(5px); }
.ticket-item-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; }
.ticket-item-code { font-family: monospace; font-size: 13px; color: var(--primary); font-weight: 600; }
.ticket-item-status {
    padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 600;
    display: flex; align-items: center; gap: 5px;
}
.ticket-item-subject { font-size: 15px; font-weight: 600; color: #fff; margin-bottom: 8px; }
.ticket-item-meta { display: flex; gap: 15px; font-size: 12px; color: rgba(255,255,255,0.5); }
.ticket-item-meta span { display: flex; align-items: center; gap: 5px; }

.empty-state { text-align: center; padding: 60px 20px; }
.empty-state i { font-size: 50px; color: rgba(255,255,255,0.2); margin-bottom: 15px; }
.empty-state h4 { font-size: 18px; margin-bottom: 10px; }
.empty-state p { color: rgba(255,255,255,0.5); margin-bottom: 20px; }

/* Ticket Detail */
.ticket-detail-header {
    background: rgba(var(--primary-rgb), 0.1); border: 1px solid rgba(var(--primary-rgb), 0.2);
    border-radius: 14px; padding: 20px; margin-bottom: 25px;
}
.ticket-detail-top { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 15px; }
.ticket-detail-code { font-family: monospace; font-size: 18px; font-weight: 700; color: var(--primary); }
.ticket-detail-subject { font-size: 18px; font-weight: 700; margin: 10px 0 15px; }
.ticket-detail-meta { display: flex; flex-wrap: wrap; gap: 20px; font-size: 13px; color: rgba(255,255,255,0.7); }
.ticket-detail-meta span { display: flex; align-items: center; gap: 6px; }
.ticket-detail-meta i { color: var(--primary); }

.message-list { display: flex; flex-direction: column; gap: 20px; margin-bottom: 30px; }
.message-item { display: flex; gap: 15px; }
.message-item.admin { flex-direction: row-reverse; }
.message-avatar {
    width: 40px; height: 40px; border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-weight: 700; font-size: 14px; flex-shrink: 0;
}
.message-item:not(.admin) .message-avatar { background: var(--gradient); }
.message-item.admin .message-avatar { background: linear-gradient(135deg, #10b981, #059669); }
.message-bubble {
    flex: 1; max-width: 80%; padding: 15px 20px;
    border-radius: 14px; background: rgba(255,255,255,0.05);
}
.message-item.admin .message-bubble { background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.2); }
.message-header { display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 12px; }
.message-sender { font-weight: 600; color: #fff; }
.message-item.admin .message-sender { color: #10b981; }
.message-time { color: rgba(255,255,255,0.4); }
.message-text { font-size: 14px; line-height: 1.6; color: rgba(255,255,255,0.85); white-space: pre-wrap; }
.message-attachments { display: flex; gap: 10px; margin-top: 12px; flex-wrap: wrap; }
.message-attachment {
    width: 80px; height: 80px; border-radius: 8px; overflow: hidden;
    border: 1px solid rgba(255,255,255,0.1); cursor: pointer;
}
.message-attachment img { width: 100%; height: 100%; object-fit: cover; }

.reply-form { border-top: 1px solid rgba(255,255,255,0.1); padding-top: 25px; }
.reply-form h4 { font-size: 15px; font-weight: 600; margin-bottom: 15px; display: flex; align-items: center; gap: 8px; }
.reply-form h4 i { color: var(--primary); }

/* Track Form */
.track-form { max-width: 500px; margin: 0 auto; }

@media (max-width: 768px) {
    .support-page { padding: 20px 0 60px; }
    .support-card { padding: 20px; }
    .form-row { grid-template-columns: 1fr; }
    .support-header h1 { font-size: 24px; }
    .ticket-detail-top { flex-direction: column; }
    .message-bubble { max-width: 90%; }
}
</style>

<div class="support-page">
    <div class="container">
        <div class="support-header">
            <h1><i class="fas fa-headset me-2" style="color: var(--primary);"></i>Destek Merkezi</h1>
            <p>Sorularınız ve sorunlarınız için bize ulaşın</p>
        </div>
        
        <!-- Tabs -->
        <div class="support-tabs">
            <?php if ($isLoggedIn): ?>
                <?php 
                $openCount = 0;
                foreach ($userTickets as $t) {
                    if (in_array($t['status'], ['open', 'answered'])) $openCount++;
                }
                ?>
                <a href="?view=list" class="support-tab <?php echo $currentView === 'list' ? 'active' : ''; ?>">
                    <i class="fas fa-list"></i> Taleplerim
                    <?php if ($openCount > 0): ?><span class="badge"><?php echo $openCount; ?></span><?php endif; ?>
                </a>
                <a href="?view=form" class="support-tab <?php echo $currentView === 'form' ? 'active' : ''; ?>">
                    <i class="fas fa-plus"></i> Yeni Talep
                </a>
            <?php else: ?>
                <a href="?view=form" class="support-tab <?php echo $currentView === 'form' ? 'active' : ''; ?>">
                    <i class="fas fa-plus"></i> Yeni Talep
                </a>
                <a href="?view=track" class="support-tab <?php echo $currentView === 'track' ? 'active' : ''; ?>">
                    <i class="fas fa-search"></i> Talep Takip
                </a>
            <?php endif; ?>
        </div>
        
        <div class="support-container">
            <?php if (!empty($errors)): ?>
            <div class="alert-box error">
                <i class="fas fa-exclamation-circle"></i>
                <div class="content">
                    <h4>Hata</h4>
                    <ul><?php foreach ($errors as $e): ?><li><?php echo clean($e); ?></li><?php endforeach; ?></ul>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['sent'])): ?>
            <div class="alert-box success">
                <i class="fas fa-check-circle"></i>
                <div class="content"><h4>Mesajınız gönderildi!</h4><p>Yanıt geldiğinde bilgilendirileceksiniz.</p></div>
            </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
            <!-- Başarılı -->
            <div class="support-card">
                <div class="alert-box success">
                    <i class="fas fa-check-circle"></i>
                    <div class="content">
                        <h4>Talebiniz Başarıyla Oluşturuldu!</h4>
                        <p>Destek ekibimiz en kısa sürede size dönüş yapacaktır.</p>
                        <div class="ticket-number-display"><?php echo $ticketNumber; ?></div>
                        <?php if (!$isLoggedIn): ?>
                        <p style="margin-top: 10px; font-size: 12px; color: rgba(255,255,255,0.6);">
                            <i class="fas fa-info-circle me-1"></i> Bu numarayı ve e-posta adresinizi kullanarak talebinizi takip edebilirsiniz.
                        </p>
                        <?php endif; ?>
                        <div class="success-actions">
                            <?php if ($isLoggedIn): ?>
                            <a href="?view=list" class="btn btn-primary"><i class="fas fa-list"></i> Taleplerime Git</a>
                            <?php else: ?>
                            <a href="?view=track" class="btn btn-primary"><i class="fas fa-search"></i> Talebi Takip Et</a>
                            <?php endif; ?>
                            <a href="<?php echo SITE_URL; ?>" class="btn btn-secondary"><i class="fas fa-home"></i> Ana Sayfa</a>
                        </div>
                    </div>
                </div>
            </div>
            
            <?php elseif ($currentView === 'detail' && $selectedTicket): ?>
            <!-- Talep Detay -->
            <div class="support-card">
                <a href="?view=<?php echo $isLoggedIn ? 'list' : 'track'; ?>" style="color: var(--primary); font-size: 13px; display: inline-flex; align-items: center; gap: 5px; margin-bottom: 20px;">
                    <i class="fas fa-arrow-left"></i> Geri
                </a>
                
                <div class="ticket-detail-header">
                    <div class="ticket-detail-top">
                        <span class="ticket-detail-code"><?php echo $selectedTicket['ticket_number']; ?></span>
                        <span class="ticket-item-status" style="background: <?php echo $statusLabels[$selectedTicket['status']][1]; ?>22; color: <?php echo $statusLabels[$selectedTicket['status']][1]; ?>;">
                            <i class="<?php echo $statusLabels[$selectedTicket['status']][2]; ?>"></i>
                            <?php echo $statusLabels[$selectedTicket['status']][0]; ?>
                        </span>
                    </div>
                    <h3 class="ticket-detail-subject"><?php echo clean($selectedTicket['subject']); ?></h3>
                    <div class="ticket-detail-meta">
                        <span><i class="fas fa-folder"></i> <?php echo $categories[$selectedTicket['category']] ?? 'Genel'; ?></span>
                        <span><i class="fas fa-calendar"></i> <?php echo date('d.m.Y H:i', strtotime($selectedTicket['created_at'])); ?></span>
                        <?php if ($selectedTicket['order_id']): ?>
                        <span><i class="fas fa-shopping-cart"></i> Sipariş bağlantılı</span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="message-list">
                    <?php foreach ($ticketMessages as $msg): 
                        $isAdmin = $msg['is_admin'];
                        $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(substr($isLoggedIn ? $userName : ($selectedTicket['guest_name'] ?? 'M'), 0, 1)); ?>
                            <?php endif; ?>
                        </div>
                        <div class="message-bubble">
                            <div class="message-header">
                                <span class="message-sender"><?php echo $isAdmin ? 'Destek Ekibi' : ($isLoggedIn ? $userName : ($selectedTicket['guest_name'] ?? 'Misafir')); ?></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>
                
                <?php if ($selectedTicket['status'] !== 'closed'): ?>
                <div class="reply-form">
                    <h4><i class="fas fa-reply"></i> Yanıt Yaz</h4>
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="send_reply" value="1">
                        <div class="form-group">
                            <textarea name="reply_message" class="form-control" placeholder="Mesajınızı yazın..." required></textarea>
                        </div>
                        <div class="form-group">
                            <div class="file-upload-area" onclick="document.getElementById('replyFileInput').click()">
                                <i class="fas fa-image"></i>
                                <p>Fotoğraf ekle (opsiyonel)</p>
                                <input type="file" name="reply_attachments[]" id="replyFileInput" multiple accept="image/*">
                            </div>
                        </div>
                        <button type="submit" class="btn-submit"><i class="fas fa-paper-plane"></i> Gönder</button>
                    </form>
                </div>
                <?php else: ?>
                <div class="alert-box info">
                    <i class="fas fa-info-circle"></i>
                    <div class="content"><p>Bu talep kapatılmış. Yeni bir sorunuz varsa yeni talep oluşturabilirsiniz.</p></div>
                </div>
                <?php endif; ?>
            </div>
            
            <?php elseif ($currentView === 'list' && $isLoggedIn): ?>
            <!-- Talep Listesi -->
            <div class="support-card">
                <h3><i class="fas fa-list"></i> Destek Taleplerim</h3>
                
                <?php if (empty($userTickets)): ?>
                <div class="empty-state">
                    <i class="fas fa-ticket-alt"></i>
                    <h4>Henüz talebiniz yok</h4>
                    <p>Bir sorunuz veya sorununuz mu var? Hemen yeni talep oluşturun.</p>
                    <a href="?view=form" class="btn-submit" style="width: auto; display: inline-flex;"><i class="fas fa-plus"></i> Yeni Talep Oluştur</a>
                </div>
                <?php else: ?>
                <div class="ticket-list">
                    <?php foreach ($userTickets as $ticket): ?>
                    <a href="?ticket=<?php echo $ticket['ticket_number']; ?>" class="ticket-item">
                        <div class="ticket-item-header">
                            <span class="ticket-item-code"><?php echo $ticket['ticket_number']; ?></span>
                            <span class="ticket-item-status" style="background: <?php echo $statusLabels[$ticket['status']][1]; ?>22; color: <?php echo $statusLabels[$ticket['status']][1]; ?>;">
                                <i class="<?php echo $statusLabels[$ticket['status']][2]; ?>"></i>
                                <?php echo $statusLabels[$ticket['status']][0]; ?>
                            </span>
                        </div>
                        <div class="ticket-item-subject"><?php echo clean($ticket['subject']); ?></div>
                        <div class="ticket-item-meta">
                            <span><i class="fas fa-folder"></i> <?php echo $categories[$ticket['category']] ?? 'Genel'; ?></span>
                            <span><i class="fas fa-calendar"></i> <?php echo date('d.m.Y H:i', strtotime($ticket['created_at'])); ?></span>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
            
            <?php elseif ($currentView === 'track' && !$isLoggedIn): ?>
            <!-- Talep Takip (Ziyaretçi) -->
            <div class="support-card track-form">
                <h3><i class="fas fa-search"></i> Talep Takip</h3>
                <p style="color: rgba(255,255,255,0.6); font-size: 14px; margin-bottom: 25px;">
                    Daha önce oluşturduğunuz talebi takip etmek için talep numaranızı ve e-posta adresinizi girin.
                </p>
                
                <form method="POST">
                    <input type="hidden" name="track_ticket" value="1">
                    <div class="form-group">
                        <label>Talep Numarası <span class="required">*</span></label>
                        <input type="text" name="ticket_code" class="form-control" placeholder="TKT-XXXXXXXX" required>
                    </div>
                    <div class="form-group">
                        <label>E-posta Adresi <span class="required">*</span></label>
                        <input type="email" name="track_email" class="form-control" placeholder="ornek@email.com" required>
                    </div>
                    <button type="submit" class="btn-submit"><i class="fas fa-search"></i> Talebi Bul</button>
                </form>
            </div>
            
            <?php else: ?>
            <!-- Yeni Talep Formu -->
            <div class="support-card">
                <h3><i class="fas fa-plus-circle"></i> Yeni Destek Talebi</h3>
                
                <?php if ($isLoggedIn): ?>
                <div class="user-info-box">
                    <div class="avatar"><?php echo strtoupper(substr($userName, 0, 1)); ?></div>
                    <div class="info">
                        <h4><?php echo clean($userName); ?></h4>
                        <p><?php echo clean($userEmail); ?></p>
                    </div>
                </div>
                <?php endif; ?>
                
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    <input type="hidden" name="submit_ticket" value="1">
                    
                    <?php if (!$isLoggedIn): ?>
                    <div class="form-group">
                        <label>Adınız Soyadınız <span class="required">*</span></label>
                        <input type="text" name="name" class="form-control" placeholder="Adınız Soyadınız" value="<?php echo clean($_POST['name'] ?? ''); ?>" required>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>E-posta Adresi <span class="required">*</span></label>
                            <input type="email" name="email" class="form-control" placeholder="ornek@email.com" value="<?php echo clean($_POST['email'] ?? ''); ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Telefon <span class="optional">(Opsiyonel)</span></label>
                            <input type="tel" name="phone" class="form-control" placeholder="05XX XXX XX XX" value="<?php echo clean($_POST['phone'] ?? ''); ?>">
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Kategori <span class="required">*</span></label>
                            <select name="category" class="form-control">
                                <?php foreach ($categories as $k => $v): ?>
                                <option value="<?php echo $k; ?>"><?php echo $v; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Öncelik</label>
                            <select name="priority" class="form-control">
                                <?php foreach ($priorities as $k => $v): ?>
                                <option value="<?php echo $k; ?>" <?php echo $k === 'normal' ? 'selected' : ''; ?>><?php echo $v; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Sipariş Numarası <span class="optional">(Opsiyonel)</span></label>
                        <input type="text" name="order_number" class="form-control" placeholder="ORD-XXXXXXXX" value="<?php echo clean($_POST['order_number'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label>Konu <span class="required">*</span></label>
                        <input type="text" name="subject" class="form-control" placeholder="Talebinizin konusu" value="<?php echo clean($_POST['subject'] ?? ''); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Mesajınız <span class="required">*</span></label>
                        <textarea name="message" class="form-control" placeholder="Sorununuzu detaylı açıklayın..." required><?php echo clean($_POST['message'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Ekler <span class="optional">(Maks. 3 fotoğraf, 5MB)</span></label>
                        <div class="file-upload-area" onclick="document.getElementById('fileInput').click()">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <p>Fotoğraf yüklemek için tıklayın</p>
                            <input type="file" name="attachments[]" id="fileInput" multiple accept="image/*">
                        </div>
                        <div class="file-preview" id="filePreview"></div>
                    </div>
                    
                    <button type="submit" class="btn-submit"><i class="fas fa-paper-plane"></i> Talebi Gönder</button>
                </form>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.getElementById('fileInput')?.addEventListener('change', function() {
    var preview = document.getElementById('filePreview');
    preview.innerHTML = '';
    for (var i = 0; i < Math.min(this.files.length, 3); i++) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var div = document.createElement('div');
            div.className = 'file-preview-item';
            div.innerHTML = '<img src="' + e.target.result + '">';
            preview.appendChild(div);
        };
        reader.readAsDataURL(this.files[i]);
    }
});
</script>

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