<?php
/**
 * SMM Paket Satış Scripti - SSS Yönetimi
 * @version 1.0.0
 */

require_once __DIR__ . '/../config.php';

if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/admin/');
    exit;
}

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

// POST İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Güvenlik hatası.');
        redirect(SITE_URL . '/admin/sss.php');
        exit;
    }
    
    $action = $_POST['action'];
    
    try {
        switch ($action) {
            case 'add':
                $question = trim($_POST['question'] ?? '');
                $answer = trim($_POST['answer'] ?? '');
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                
                if (empty($question)) {
                    throw new Exception('Soru alanı zorunludur.');
                }
                
                if (empty($answer)) {
                    throw new Exception('Cevap alanı zorunludur.');
                }
                
                // Sıralama otomatik
                if ($sortOrder <= 0) {
                    $maxOrder = $db->query("SELECT MAX(sort_order) FROM faqs")->fetchColumn();
                    $sortOrder = ($maxOrder ?? 0) + 1;
                }
                
                $stmt = $db->prepare("
                    INSERT INTO faqs (question, answer, sort_order, is_active, created_at)
                    VALUES (?, ?, ?, ?, NOW())
                ");
                $stmt->execute([$question, $answer, $sortOrder, $isActive]);
                
                setFlash('success', 'SSS başarıyla eklendi.');
                break;
                
            case 'update':
                $faqId = (int)($_POST['faq_id'] ?? 0);
                $question = trim($_POST['question'] ?? '');
                $answer = trim($_POST['answer'] ?? '');
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                
                if ($faqId <= 0) {
                    throw new Exception('Geçersiz SSS.');
                }
                
                if (empty($question)) {
                    throw new Exception('Soru alanı zorunludur.');
                }
                
                if (empty($answer)) {
                    throw new Exception('Cevap alanı zorunludur.');
                }
                
                $stmt = $db->prepare("
                    UPDATE faqs 
                    SET question = ?, answer = ?, sort_order = ?, is_active = ?
                    WHERE id = ?
                ");
                $stmt->execute([$question, $answer, $sortOrder, $isActive, $faqId]);
                
                setFlash('success', 'SSS güncellendi.');
                break;
                
            case 'delete':
                $faqId = (int)($_POST['faq_id'] ?? 0);
                
                if ($faqId <= 0) {
                    throw new Exception('Geçersiz SSS.');
                }
                
                $db->prepare("DELETE FROM faqs WHERE id = ?")->execute([$faqId]);
                
                setFlash('success', 'SSS silindi.');
                break;
                
            case 'toggle_status':
                $faqId = (int)($_POST['faq_id'] ?? 0);
                $status = (int)($_POST['status'] ?? 0);
                
                if ($faqId <= 0) {
                    throw new Exception('Geçersiz SSS.');
                }
                
                $db->prepare("UPDATE faqs SET is_active = ? WHERE id = ?")->execute([$status, $faqId]);
                
                setFlash('success', $status ? 'SSS aktifleştirildi.' : 'SSS pasifleştirildi.');
                break;
                
            case 'reorder':
                $orders = $_POST['orders'] ?? [];
                
                if (!empty($orders) && is_array($orders)) {
                    $stmt = $db->prepare("UPDATE faqs SET sort_order = ? WHERE id = ?");
                    foreach ($orders as $id => $order) {
                        $stmt->execute([(int)$order, (int)$id]);
                    }
                    setFlash('success', 'Sıralama güncellendi.');
                }
                break;
        }
    } catch (Exception $e) {
        setFlash('error', $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/sss.php');
    exit;
}

// SSS'leri çek
try {
    $faqs = $db->query("SELECT * FROM faqs ORDER BY sort_order ASC, id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $faqs = [];
}

// İstatistikler
$stats = [
    'total' => count($faqs),
    'active' => count(array_filter($faqs, fn($f) => $f['is_active'] == 1)),
    'inactive' => count(array_filter($faqs, fn($f) => $f['is_active'] == 0))
];

$adminPageTitle = 'SSS Yönetimi';
require_once __DIR__ . '/header.php';
?>

<style>
/* Page Header */
.page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 25px;
    flex-wrap: wrap;
    gap: 15px;
}

.page-header h2 {
    font-size: 18px;
    font-weight: 700;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.page-header h2 i {
    color: var(--primary);
}

/* Stats */
.stats-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    padding: 20px;
    text-align: center;
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 30px rgba(0,0,0,0.15);
}

.stat-card .icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    margin: 0 auto 12px;
}

.stat-card .icon.primary {
    background: rgba(var(--primary-rgb), 0.15);
    color: var(--primary);
}

.stat-card .icon.success {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.stat-card .icon.warning {
    background: rgba(245, 158, 11, 0.15);
    color: #f59e0b;
}

.stat-card .value {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 5px;
}

.stat-card .label {
    font-size: 13px;
    color: var(--text-secondary);
}

/* FAQ List */
.faq-list {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    overflow: hidden;
}

.faq-list-header {
    padding: 18px 22px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
}

.faq-list-header h3 {
    font-size: 16px;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.faq-list-header h3 i {
    color: var(--primary);
}

/* FAQ Item */
.faq-item {
    border-bottom: 1px solid var(--border-color);
    transition: all 0.2s;
}

.faq-item:last-child {
    border-bottom: none;
}

.faq-item:hover {
    background: rgba(var(--primary-rgb), 0.02);
}

.faq-item.inactive {
    opacity: 0.6;
}

.faq-item-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 18px 22px;
    cursor: pointer;
}

.faq-drag-handle {
    color: var(--text-muted);
    cursor: grab;
    padding: 5px;
    font-size: 14px;
}

.faq-drag-handle:active {
    cursor: grabbing;
}

.faq-number {
    width: 32px;
    height: 32px;
    background: rgba(var(--primary-rgb), 0.1);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
    font-weight: 700;
    color: var(--primary);
    flex-shrink: 0;
}

.faq-question {
    flex: 1;
    font-size: 15px;
    font-weight: 600;
    color: var(--text-primary);
    min-width: 0;
}

.faq-status {
    flex-shrink: 0;
}

.faq-toggle {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    cursor: pointer;
    border: none;
    transition: all 0.2s;
}

.faq-toggle.active {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.faq-toggle.inactive {
    background: rgba(107, 114, 128, 0.15);
    color: #6b7280;
}

.faq-toggle:hover {
    transform: scale(1.05);
}

.faq-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
}

.faq-actions button {
    width: 34px;
    height: 34px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 13px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.faq-actions .btn-edit {
    background: rgba(59, 130, 246, 0.15);
    color: #3b82f6;
}

.faq-actions .btn-edit:hover {
    background: #3b82f6;
    color: #fff;
}

.faq-actions .btn-delete {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

.faq-actions .btn-delete:hover {
    background: #ef4444;
    color: #fff;
}

.faq-expand-icon {
    color: var(--text-muted);
    transition: transform 0.3s;
    flex-shrink: 0;
}

.faq-item.expanded .faq-expand-icon {
    transform: rotate(180deg);
}

/* FAQ Answer */
.faq-answer {
    display: none;
    padding: 0 22px 18px 85px;
}

.faq-item.expanded .faq-answer {
    display: block;
}

.faq-answer-content {
    background: var(--bg-hover);
    border-radius: 12px;
    padding: 18px;
    font-size: 14px;
    color: var(--text-secondary);
    line-height: 1.7;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 60px 20px;
}

.empty-state i {
    font-size: 60px;
    color: var(--text-muted);
    opacity: 0.3;
    margin-bottom: 20px;
}

.empty-state h4 {
    font-size: 18px;
    margin-bottom: 10px;
}

.empty-state p {
    color: var(--text-secondary);
    margin-bottom: 25px;
}

/* Modal */
.modal-content {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    color: var(--text-primary);
}

.modal-header {
    border-bottom: 1px solid var(--border-color);
    padding: 20px 24px;
}

.modal-title {
    font-size: 18px;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
}

.modal-title i { color: var(--primary); }

.modal-body { padding: 24px; }

.modal-footer {
    border-top: 1px solid var(--border-color);
    padding: 16px 24px;
    gap: 10px;
}

/* Form */
.form-group {
    margin-bottom: 20px;
}

.form-group:last-child {
    margin-bottom: 0;
}

.form-label {
    display: block;
    font-size: 13px;
    font-weight: 600;
    margin-bottom: 8px;
    color: var(--text-primary);
}

.form-label .required {
    color: #ef4444;
}

.form-control {
    width: 100%;
    padding: 12px 16px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    color: var(--text-primary);
    font-size: 14px;
    transition: all 0.2s;
}

.form-control:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.15);
    outline: none;
}

.form-control::placeholder {
    color: var(--text-muted);
}

textarea.form-control {
    min-height: 150px;
    resize: vertical;
    line-height: 1.6;
}

.form-hint {
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 6px;
}

/* Form Row */
.form-row {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 15px;
    align-items: end;
}

/* Toggle Switch in Modal */
.form-check-custom {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 15px;
    background: var(--bg-hover);
    border-radius: 12px;
    cursor: pointer;
}

.form-check-custom input[type="checkbox"] {
    width: 20px;
    height: 20px;
    accent-color: var(--primary);
    cursor: pointer;
}

.form-check-custom label {
    cursor: pointer;
    flex: 1;
}

.form-check-custom label strong {
    display: block;
    font-size: 14px;
    margin-bottom: 2px;
}

.form-check-custom label span {
    font-size: 12px;
    color: var(--text-secondary);
}

/* Quick Tips */
.tips-box {
    background: rgba(59, 130, 246, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.2);
    border-radius: 12px;
    padding: 18px;
    margin-bottom: 25px;
}

.tips-box h4 {
    font-size: 14px;
    font-weight: 600;
    color: #3b82f6;
    margin: 0 0 12px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.tips-box ul {
    margin: 0;
    padding-left: 20px;
    font-size: 13px;
    color: #3b82f6;
}

.tips-box ul li {
    margin-bottom: 6px;
}

.tips-box ul li:last-child {
    margin-bottom: 0;
}

/* Responsive */
@media (max-width: 768px) {
    .faq-item-header {
        flex-wrap: wrap;
        gap: 10px;
    }
    
    .faq-question {
        order: 1;
        width: 100%;
        padding-left: 47px;
        margin-top: -5px;
    }
    
    .faq-drag-handle {
        order: 0;
    }
    
    .faq-number {
        order: 0;
    }
    
    .faq-status {
        order: 0;
        margin-left: auto;
    }
    
    .faq-actions {
        order: 0;
    }
    
    .faq-expand-icon {
        order: 0;
    }
    
    .faq-answer {
        padding-left: 22px;
    }
    
    .form-row {
        grid-template-columns: 1fr;
    }
    
    .stats-row {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 480px) {
    .stats-row {
        grid-template-columns: 1fr;
    }
    
    .stat-card {
        display: flex;
        align-items: center;
        text-align: left;
        gap: 15px;
        padding: 15px;
    }
    
    .stat-card .icon {
        margin: 0;
        width: 45px;
        height: 45px;
    }
    
    .stat-card .value {
        font-size: 22px;
    }
}
</style>

<div class="page-header">
    <h2><i class="fas fa-question-circle"></i> SSS Yönetimi</h2>
    <button class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addFaqModal">
        <i class="fas fa-plus"></i> Yeni SSS Ekle
    </button>
</div>

<!-- Stats -->
<div class="stats-row">
    <div class="stat-card">
        <div class="icon primary">
            <i class="fas fa-question-circle"></i>
        </div>
        <div>
            <div class="value"><?php echo $stats['total']; ?></div>
            <div class="label">Toplam SSS</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="icon success">
            <i class="fas fa-check-circle"></i>
        </div>
        <div>
            <div class="value"><?php echo $stats['active']; ?></div>
            <div class="label">Aktif</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="icon warning">
            <i class="fas fa-eye-slash"></i>
        </div>
        <div>
            <div class="value"><?php echo $stats['inactive']; ?></div>
            <div class="label">Pasif</div>
        </div>
    </div>
</div>

<!-- Tips -->
<div class="tips-box">
    <h4><i class="fas fa-lightbulb"></i> İpuçları</h4>
    <ul>
        <li>Soruları sürükleyerek sıralayabilirsiniz</li>
        <li>Pasif sorular sitede görüntülenmez</li>
        <li>Soru ve cevapları mümkün olduğunca açık ve anlaşılır yazın</li>
    </ul>
</div>

<!-- FAQ List -->
<div class="faq-list">
    <div class="faq-list-header">
        <h3><i class="fas fa-list"></i> Soru-Cevap Listesi</h3>
        <span style="font-size: 13px; color: var(--text-secondary);"><?php echo count($faqs); ?> kayıt</span>
    </div>
    
    <?php if (empty($faqs)): ?>
    <div class="empty-state">
        <i class="fas fa-question-circle"></i>
        <h4>Henüz SSS eklenmemiş</h4>
        <p>Müşterilerinizin sık sorduğu soruları ekleyin</p>
        <button class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addFaqModal">
            <i class="fas fa-plus"></i> İlk SSS'yi Ekle
        </button>
    </div>
    <?php else: ?>
    <div id="faqSortable">
        <?php $counter = 1; foreach ($faqs as $faq): ?>
        <div class="faq-item <?php echo $faq['is_active'] ? '' : 'inactive'; ?>" data-id="<?php echo $faq['id']; ?>">
            <div class="faq-item-header" onclick="toggleFaq(this)">
                <div class="faq-drag-handle" onclick="event.stopPropagation()">
                    <i class="fas fa-grip-vertical"></i>
                </div>
                <div class="faq-number"><?php echo $counter++; ?></div>
                <div class="faq-question"><?php echo clean($faq['question']); ?></div>
                <div class="faq-status">
                    <button class="faq-toggle <?php echo $faq['is_active'] ? 'active' : 'inactive'; ?>" 
                            onclick="event.stopPropagation(); toggleStatus(<?php echo $faq['id']; ?>, <?php echo $faq['is_active'] ? 0 : 1; ?>)">
                        <i class="fas fa-<?php echo $faq['is_active'] ? 'check' : 'times'; ?>"></i>
                        <?php echo $faq['is_active'] ? 'Aktif' : 'Pasif'; ?>
                    </button>
                </div>
                <div class="faq-actions" onclick="event.stopPropagation()">
                    <button class="btn-edit" onclick="editFaq(<?php echo htmlspecialchars(json_encode($faq)); ?>)" title="Düzenle">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn-delete" onclick="deleteFaq(<?php echo $faq['id']; ?>, '<?php echo clean(addslashes($faq['question'])); ?>')" title="Sil">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
                <div class="faq-expand-icon">
                    <i class="fas fa-chevron-down"></i>
                </div>
            </div>
            <div class="faq-answer">
                <div class="faq-answer-content">
                    <?php echo nl2br(clean($faq['answer'])); ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- Add FAQ Modal -->
<div class="modal fade" id="addFaqModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="add">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus-circle"></i> Yeni SSS Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">Soru <span class="required">*</span></label>
                        <input type="text" name="question" class="form-control" placeholder="Örn: Siparişim ne zaman tamamlanır?" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Cevap <span class="required">*</span></label>
                        <textarea name="answer" class="form-control" placeholder="Sorunun detaylı cevabını yazın..." required></textarea>
                        <div class="form-hint">Cevabı açık ve anlaşılır şekilde yazın</div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Sıralama</label>
                            <input type="number" name="sort_order" class="form-control" value="0" min="0" style="width: 120px;">
                            <div class="form-hint">0 = otomatik</div>
                        </div>
                        
                        <div class="form-group">
                            <div class="form-check-custom">
                                <input type="checkbox" name="is_active" id="addIsActive" checked>
                                <label for="addIsActive">
                                    <strong>Aktif</strong>
                                    <span>Sitede gösterilsin</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn-primary-custom">
                        <i class="fas fa-plus"></i> SSS Ekle
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit FAQ Modal -->
<div class="modal fade" id="editFaqModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="faq_id" id="editFaqId">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> SSS Düzenle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">Soru <span class="required">*</span></label>
                        <input type="text" name="question" id="editQuestion" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Cevap <span class="required">*</span></label>
                        <textarea name="answer" id="editAnswer" class="form-control" required></textarea>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Sıralama</label>
                            <input type="number" name="sort_order" id="editSortOrder" class="form-control" min="0" style="width: 120px;">
                        </div>
                        
                        <div class="form-group">
                            <div class="form-check-custom">
                                <input type="checkbox" name="is_active" id="editIsActive">
                                <label for="editIsActive">
                                    <strong>Aktif</strong>
                                    <span>Sitede gösterilsin</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn-primary-custom">
                        <i class="fas fa-save"></i> Kaydet
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Sortable JS -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>

<script>
var csrfToken = '<?php echo $csrfToken; ?>';

// Toggle FAQ expand
function toggleFaq(header) {
    var item = header.closest('.faq-item');
    item.classList.toggle('expanded');
}

// Toggle status
function toggleStatus(faqId, newStatus) {
    var form = document.createElement('form');
    form.method = 'POST';
    form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
        '<input type="hidden" name="action" value="toggle_status">' +
        '<input type="hidden" name="faq_id" value="' + faqId + '">' +
        '<input type="hidden" name="status" value="' + newStatus + '">';
    document.body.appendChild(form);
    form.submit();
}

// Edit FAQ
function editFaq(faq) {
    document.getElementById('editFaqId').value = faq.id;
    document.getElementById('editQuestion').value = faq.question;
    document.getElementById('editAnswer').value = faq.answer;
    document.getElementById('editSortOrder').value = faq.sort_order;
    document.getElementById('editIsActive').checked = faq.is_active == 1;
    
    new bootstrap.Modal(document.getElementById('editFaqModal')).show();
}

// Delete FAQ
function deleteFaq(faqId, question) {
    var shortQuestion = question.length > 50 ? question.substring(0, 50) + '...' : question;
    
    Swal.fire({
        title: 'SSS\'yi Sil',
        html: '<strong>"' + shortQuestion + '"</strong><br><small style="color: #94a3b8;">Bu işlem geri alınamaz!</small>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        confirmButtonText: '<i class="fas fa-trash me-1"></i> Evet, Sil',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
                '<input type="hidden" name="action" value="delete">' +
                '<input type="hidden" name="faq_id" value="' + faqId + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

// Sortable
document.addEventListener('DOMContentLoaded', function() {
    var sortable = document.getElementById('faqSortable');
    if (sortable) {
        new Sortable(sortable, {
            handle: '.faq-drag-handle',
            animation: 200,
            ghostClass: 'sortable-ghost',
            onEnd: function(evt) {
                // Sıralama verilerini topla
                var items = sortable.querySelectorAll('.faq-item');
                var orders = {};
                items.forEach(function(item, index) {
                    orders[item.dataset.id] = index + 1;
                    // Numarayı güncelle
                    var numEl = item.querySelector('.faq-number');
                    if (numEl) numEl.textContent = index + 1;
                });
                
                // AJAX ile kaydet
                var formData = new FormData();
                formData.append('csrf_token', csrfToken);
                formData.append('action', 'reorder');
                for (var id in orders) {
                    formData.append('orders[' + id + ']', orders[id]);
                }
                
                fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                }).then(function(response) {
                    if (response.ok) {
                        // Başarılı toast
                        if (typeof Swal !== 'undefined') {
                            Swal.mixin({
                                toast: true,
                                position: 'top-end',
                                showConfirmButton: false,
                                timer: 2000,
                                background: '#1e293b',
                                color: '#f8fafc'
                            }).fire({
                                icon: 'success',
                                title: 'Sıralama güncellendi'
                            });
                        }
                    }
                });
            }
        });
    }
});
</script>

<style>
.sortable-ghost {
    opacity: 0.4;
    background: rgba(var(--primary-rgb), 0.1);
}
</style>

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