<?php
/**
 * Admin - Kayan Yazı (Marquee) Yönetimi
 * @version 1.0.0
 */

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

// Admin kontrolü
if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/giris.php');
    exit;
}

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

// POST İşlemleri (header.php'den ÖNCE)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Güvenlik hatası.');
        redirect(SITE_URL . '/admin/kayan-yazi.php');
        exit;
    }
    
    $action = $_POST['action'] ?? '';
    
    try {
        switch ($action) {
            case 'update_settings':
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                $bgColor = trim($_POST['bg_color'] ?? '#ef4444');
                $textColor = trim($_POST['text_color'] ?? '#ffffff');
                $speed = max(5, min(120, (int)($_POST['speed'] ?? 30)));
                $showOnMobile = isset($_POST['show_on_mobile']) ? 1 : 0;
                $isClosable = isset($_POST['is_closable']) ? 1 : 0;
                
                $colorPattern = '/^#[0-9A-Fa-f]{6}$/';
                if (!preg_match($colorPattern, $bgColor)) $bgColor = '#ef4444';
                if (!preg_match($colorPattern, $textColor)) $textColor = '#ffffff';
                
                $stmt = $db->prepare("
                    UPDATE marquee_settings 
                    SET is_active = ?, bg_color = ?, text_color = ?, speed = ?, show_on_mobile = ?, is_closable = ?
                    WHERE id = 1
                ");
                $stmt->execute([$isActive, $bgColor, $textColor, $speed, $showOnMobile, $isClosable]);
                
                unset($_SESSION['marquee_closed']);
                
                setFlash('success', 'Ayarlar güncellendi.');
                break;
                
            case 'add_item':
                $text = trim($_POST['text'] ?? '');
                $icon = trim($_POST['icon'] ?? '');
                $link = trim($_POST['link'] ?? '');
                $linkText = trim($_POST['link_text'] ?? '');
                $isActive = isset($_POST['item_active']) ? 1 : 0;
                
                if (empty($text)) {
                    throw new Exception('Yazı metni zorunludur.');
                }
                
                $maxOrder = $db->query("SELECT MAX(sort_order) FROM marquee_items")->fetchColumn();
                $sortOrder = ($maxOrder ?? 0) + 1;
                
                $stmt = $db->prepare("
                    INSERT INTO marquee_items (text, icon, link, link_text, is_active, sort_order, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, NOW())
                ");
                $stmt->execute([$text, $icon, $link, $linkText, $isActive, $sortOrder]);
                
                setFlash('success', 'Yeni öğe eklendi.');
                break;
                
            case 'update_item':
                $itemId = (int)($_POST['item_id'] ?? 0);
                $text = trim($_POST['text'] ?? '');
                $icon = trim($_POST['icon'] ?? '');
                $link = trim($_POST['link'] ?? '');
                $linkText = trim($_POST['link_text'] ?? '');
                $isActive = isset($_POST['item_active']) ? 1 : 0;
                
                if ($itemId <= 0) {
                    throw new Exception('Geçersiz öğe.');
                }
                
                if (empty($text)) {
                    throw new Exception('Yazı metni zorunludur.');
                }
                
                $stmt = $db->prepare("
                    UPDATE marquee_items 
                    SET text = ?, icon = ?, link = ?, link_text = ?, is_active = ?
                    WHERE id = ?
                ");
                $stmt->execute([$text, $icon, $link, $linkText, $isActive, $itemId]);
                
                setFlash('success', 'Öğe güncellendi.');
                break;
                
            case 'delete_item':
                $itemId = (int)($_POST['item_id'] ?? 0);
                
                if ($itemId <= 0) {
                    throw new Exception('Geçersiz öğe.');
                }
                
                $db->prepare("DELETE FROM marquee_items WHERE id = ?")->execute([$itemId]);
                
                setFlash('success', 'Öğe silindi.');
                break;
                
            case 'toggle_item':
                $itemId = (int)($_POST['item_id'] ?? 0);
                
                if ($itemId <= 0) {
                    throw new Exception('Geçersiz öğe.');
                }
                
                $db->prepare("UPDATE marquee_items SET is_active = NOT is_active WHERE id = ?")->execute([$itemId]);
                
                setFlash('success', 'Durum güncellendi.');
                break;
                
            case 'reorder':
                $orders = $_POST['orders'] ?? [];
                
                foreach ($orders as $id => $order) {
                    $db->prepare("UPDATE marquee_items SET sort_order = ? WHERE id = ?")->execute([(int)$order, (int)$id]);
                }
                
                setFlash('success', 'Sıralama güncellendi.');
                break;
        }
    } catch (Exception $e) {
        setFlash('error', $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/kayan-yazi.php');
    exit;
}

// Ayarları çek
$marqueeSettings = [
    'is_active' => 0,
    'bg_color' => '#ef4444',
    'text_color' => '#ffffff',
    'speed' => 30,
    'show_on_mobile' => 1,
    'is_closable' => 1
];

try {
    $stmt = $db->query("SELECT * FROM marquee_settings WHERE id = 1");
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($data) {
        $marqueeSettings = $data;
    }
} catch (PDOException $e) {}

// Öğeleri çek
$marqueeItems = [];
try {
    $stmt = $db->query("SELECT * FROM marquee_items ORDER BY sort_order ASC, id ASC");
    $marqueeItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

// Şimdi header'ı dahil et
$adminPageTitle = 'Kayan Yazı Ayarları';
require_once __DIR__ . '/header.php';
?>

<style>
.settings-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    margin-bottom: 25px;
}

.settings-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 15px;
}

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

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

.settings-body {
    padding: 24px;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
}

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

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

.color-input-group {
    display: flex;
    gap: 10px;
    align-items: center;
}

.color-picker {
    width: 50px;
    height: 44px;
    padding: 0;
    border: 2px solid var(--border-color);
    border-radius: 10px;
    cursor: pointer;
    overflow: hidden;
    flex-shrink: 0;
}

.color-picker::-webkit-color-swatch-wrapper {
    padding: 0;
}

.color-picker::-webkit-color-swatch {
    border: none;
    border-radius: 8px;
}

.toggle-switch {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 18px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s;
}

.toggle-switch:hover {
    border-color: var(--primary);
}

.toggle-switch input {
    width: 44px;
    height: 24px;
    accent-color: var(--primary);
    cursor: pointer;
}

.toggle-switch .toggle-label {
    flex: 1;
}

.toggle-switch .toggle-label strong {
    display: block;
    font-size: 14px;
    margin-bottom: 2px;
}

.toggle-switch .toggle-label span {
    font-size: 12px;
    color: var(--text-secondary);
}

.preview-section {
    background: var(--bg-dark);
    border-radius: 12px;
    padding: 20px;
    margin-top: 20px;
}

.preview-section h5 {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-secondary);
    margin: 0 0 15px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.marquee-preview {
    height: 36px;
    border-radius: 8px;
    overflow: hidden;
    display: flex;
    align-items: center;
}

.marquee-preview-content {
    display: flex;
    animation: previewScroll 15s linear infinite;
    white-space: nowrap;
}

@keyframes previewScroll {
    0% { transform: translateX(0); }
    100% { transform: translateX(-50%); }
}

.marquee-preview-item {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 0 30px;
    font-size: 13px;
    font-weight: 600;
}

.items-table {
    width: 100%;
}

.items-table th {
    background: rgba(0,0,0,0.15);
    padding: 12px 16px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: var(--text-muted);
    text-align: left;
    border-bottom: 1px solid var(--border-color);
}

.items-table td {
    padding: 14px 16px;
    border-bottom: 1px solid var(--border-color);
    vertical-align: middle;
}

.items-table tr:last-child td {
    border-bottom: none;
}

.items-table tr:hover {
    background: rgba(var(--primary-rgb), 0.03);
}

.item-icon {
    width: 36px;
    height: 36px;
    background: rgba(var(--primary-rgb), 0.15);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--primary);
    font-size: 14px;
}

.item-text {
    font-weight: 500;
    max-width: 300px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.item-link {
    font-size: 12px;
    color: var(--text-muted);
}

.item-actions {
    display: flex;
    gap: 6px;
}

.item-actions .btn {
    width: 32px;
    height: 32px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    font-size: 12px;
}

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

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

.status-active {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
}

.status-inactive {
    background: rgba(107, 114, 128, 0.15);
    color: #6b7280;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
}

.empty-items {
    text-align: center;
    padding: 40px 20px;
    color: var(--text-secondary);
}

.empty-items i {
    font-size: 40px;
    opacity: 0.3;
    margin-bottom: 15px;
}

.info-box {
    background: rgba(59, 130, 246, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.2);
    border-radius: 12px;
    padding: 14px 18px;
    margin-bottom: 20px;
    display: flex;
    align-items: flex-start;
    gap: 12px;
    font-size: 13px;
    color: #3b82f6;
}

.icon-preview {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    background: var(--bg-hover);
    border-radius: 8px;
    margin-left: 10px;
}

@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
    }
    
    .settings-header {
        flex-direction: column;
        align-items: flex-start;
    }
}
</style>

<!-- Genel Ayarlar -->
<div class="settings-card">
    <div class="settings-header">
        <h3><i class="fas fa-cog"></i> Genel Ayarlar</h3>
        <span class="<?php echo $marqueeSettings['is_active'] ? 'status-active' : 'status-inactive'; ?>">
            <?php echo $marqueeSettings['is_active'] ? 'Aktif' : 'Pasif'; ?>
        </span>
    </div>
    <div class="settings-body">
        <form method="POST" id="settingsForm">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
            <input type="hidden" name="action" value="update_settings">
            
            <div class="form-row">
                <div class="form-group">
                    <label class="toggle-switch">
                        <input type="checkbox" name="is_active" <?php echo $marqueeSettings['is_active'] ? 'checked' : ''; ?>>
                        <div class="toggle-label">
                            <strong>Kayan Yazıyı Aktifleştir</strong>
                            <span>Sitede kayan yazı bandını göster</span>
                        </div>
                    </label>
                </div>
                
                <div class="form-group">
                    <label class="toggle-switch">
                        <input type="checkbox" name="is_closable" <?php echo $marqueeSettings['is_closable'] ? 'checked' : ''; ?>>
                        <div class="toggle-label">
                            <strong>Kapatılabilir</strong>
                            <span>Kullanıcı kapatabilsin</span>
                        </div>
                    </label>
                </div>
                
                <div class="form-group">
                    <label class="toggle-switch">
                        <input type="checkbox" name="show_on_mobile" <?php echo $marqueeSettings['show_on_mobile'] ? 'checked' : ''; ?>>
                        <div class="toggle-label">
                            <strong>Mobilde Göster</strong>
                            <span>Mobil cihazlarda görünsün</span>
                        </div>
                    </label>
                </div>
            </div>
            
            <div class="form-row" style="margin-top: 20px;">
                <div class="form-group">
                    <label class="form-label">Arkaplan Rengi</label>
                    <div class="color-input-group">
                        <input type="color" name="bg_color" class="color-picker" value="<?php echo clean($marqueeSettings['bg_color']); ?>" id="bgColor">
                        <input type="text" class="form-control" value="<?php echo clean($marqueeSettings['bg_color']); ?>" id="bgColorText" maxlength="7">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Yazı Rengi</label>
                    <div class="color-input-group">
                        <input type="color" name="text_color" class="color-picker" value="<?php echo clean($marqueeSettings['text_color']); ?>" id="textColor">
                        <input type="text" class="form-control" value="<?php echo clean($marqueeSettings['text_color']); ?>" id="textColorText" maxlength="7">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Hız (saniye)</label>
                    <input type="number" name="speed" class="form-control" value="<?php echo (int)$marqueeSettings['speed']; ?>" min="5" max="120">
                    <small class="form-text">Düşük = Hızlı, Yüksek = Yavaş (5-120)</small>
                </div>
            </div>
            
            <!-- Preview -->
            <div class="preview-section">
                <h5><i class="fas fa-eye"></i> Önizleme</h5>
                <div class="marquee-preview" id="marqueePreview" style="background: <?php echo clean($marqueeSettings['bg_color']); ?>;">
                    <div class="marquee-preview-content" style="color: <?php echo clean($marqueeSettings['text_color']); ?>;">
                        <?php if (!empty($marqueeItems)): ?>
                            <?php for ($i = 0; $i < 2; $i++): ?>
                                <?php foreach ($marqueeItems as $item): ?>
                                    <?php if ($item['is_active']): ?>
                                    <span class="marquee-preview-item">
                                        <?php if ($item['icon']): ?>
                                        <i class="<?php echo clean($item['icon']); ?>"></i>
                                        <?php endif; ?>
                                        <?php echo clean($item['text']); ?>
                                    </span>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            <?php endfor; ?>
                        <?php else: ?>
                            <span class="marquee-preview-item">
                                <i class="fas fa-bullhorn"></i>
                                Örnek kayan yazı metni buraya gelecek...
                            </span>
                            <span class="marquee-preview-item">
                                <i class="fas fa-bullhorn"></i>
                                Örnek kayan yazı metni buraya gelecek...
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <div style="margin-top: 20px; text-align: right;">
                <button type="submit" class="btn-primary-custom">
                    <i class="fas fa-save"></i> Ayarları Kaydet
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Kayan Yazı Öğeleri -->
<div class="settings-card">
    <div class="settings-header">
        <h3><i class="fas fa-list"></i> Kayan Yazı Öğeleri</h3>
        <button class="btn-primary-custom btn-sm" data-bs-toggle="modal" data-bs-target="#addItemModal">
            <i class="fas fa-plus"></i> Yeni Öğe Ekle
        </button>
    </div>
    <div class="settings-body" style="padding: 0;">
        <?php if (empty($marqueeItems)): ?>
        <div class="empty-items">
            <i class="fas fa-text-width"></i>
            <p>Henüz kayan yazı öğesi eklenmemiş.</p>
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="items-table">
                <thead>
                    <tr>
                        <th width="40"></th>
                        <th width="50">İkon</th>
                        <th>Metin</th>
                        <th>Link</th>
                        <th width="80">Durum</th>
                        <th width="120">İşlemler</th>
                    </tr>
                </thead>
                <tbody id="itemsBody">
                    <?php foreach ($marqueeItems as $item): ?>
                    <tr data-id="<?php echo $item['id']; ?>">
                        <td>
                            <span class="drag-handle"><i class="fas fa-grip-vertical"></i></span>
                        </td>
                        <td>
                            <?php if ($item['icon']): ?>
                            <div class="item-icon">
                                <i class="<?php echo clean($item['icon']); ?>"></i>
                            </div>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="item-text"><?php echo clean($item['text']); ?></div>
                            <?php if ($item['link']): ?>
                            <div class="item-link">
                                <i class="fas fa-link"></i> <?php echo clean($item['link_text'] ?: $item['link']); ?>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($item['link']): ?>
                            <a href="<?php echo clean($item['link']); ?>" target="_blank" class="text-info">
                                <i class="fas fa-external-link-alt"></i>
                            </a>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="<?php echo $item['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                                <?php echo $item['is_active'] ? 'Aktif' : 'Pasif'; ?>
                            </span>
                        </td>
                        <td>
                            <div class="item-actions">
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                                    <input type="hidden" name="action" value="toggle_item">
                                    <input type="hidden" name="item_id" value="<?php echo $item['id']; ?>">
                                    <button type="submit" class="btn btn-sm <?php echo $item['is_active'] ? 'btn-warning-custom' : 'btn-success-custom'; ?>" title="<?php echo $item['is_active'] ? 'Pasifleştir' : 'Aktifleştir'; ?>">
                                        <i class="fas fa-<?php echo $item['is_active'] ? 'pause' : 'play'; ?>"></i>
                                    </button>
                                </form>
                                <button class="btn btn-sm btn-info-custom" onclick="editItem(<?php echo htmlspecialchars(json_encode($item)); ?>)" title="Düzenle">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-danger-custom" onclick="deleteItem(<?php echo $item['id']; ?>)" title="Sil">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Yeni Öğe Modal -->
<div class="modal fade" id="addItemModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="add_item">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus-circle"></i> Yeni Öğe Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <div class="info-box">
                        <i class="fas fa-info-circle"></i>
                        <div>İkonlar için Font Awesome kullanabilirsiniz. Örn: <code>fas fa-fire</code>, <code>fas fa-gift</code></div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Metin *</label>
                        <input type="text" name="text" class="form-control" placeholder="🔥 Bugüne özel %20 indirim!" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">İkon (Font Awesome)</label>
                        <div style="display: flex; align-items: center;">
                            <input type="text" name="icon" class="form-control" placeholder="fas fa-fire" id="addIconInput" style="flex: 1;">
                            <div class="icon-preview" id="addIconPreview">
                                <i class="fas fa-icons"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Link (Opsiyonel)</label>
                        <input type="url" name="link" class="form-control" placeholder="https://...">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Link Metni (Opsiyonel)</label>
                        <input type="text" name="link_text" class="form-control" placeholder="Detaylar için tıkla">
                    </div>
                    
                    <div class="form-group">
                        <label class="toggle-switch">
                            <input type="checkbox" name="item_active" checked>
                            <div class="toggle-label">
                                <strong>Aktif</strong>
                                <span>Öğeyi hemen göster</span>
                            </div>
                        </label>
                    </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> Ekle
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Düzenle Modal -->
<div class="modal fade" id="editItemModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="update_item">
                <input type="hidden" name="item_id" id="editItemId">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> Öğeyi 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">Metin *</label>
                        <input type="text" name="text" class="form-control" id="editText" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">İkon (Font Awesome)</label>
                        <div style="display: flex; align-items: center;">
                            <input type="text" name="icon" class="form-control" id="editIcon" style="flex: 1;">
                            <div class="icon-preview" id="editIconPreview">
                                <i class="fas fa-icons"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Link (Opsiyonel)</label>
                        <input type="url" name="link" class="form-control" id="editLink">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Link Metni (Opsiyonel)</label>
                        <input type="text" name="link_text" class="form-control" id="editLinkText">
                    </div>
                    
                    <div class="form-group">
                        <label class="toggle-switch">
                            <input type="checkbox" name="item_active" id="editActive">
                            <div class="toggle-label">
                                <strong>Aktif</strong>
                                <span>Öğeyi göster</span>
                            </div>
                        </label>
                    </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>

<!-- Silme Formu -->
<form method="POST" id="deleteForm" style="display: none;">
    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
    <input type="hidden" name="action" value="delete_item">
    <input type="hidden" name="item_id" id="deleteItemId">
</form>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
// Renk senkronizasyonu
document.getElementById('bgColor').addEventListener('input', function() {
    document.getElementById('bgColorText').value = this.value.toUpperCase();
    updatePreview();
});

document.getElementById('bgColorText').addEventListener('input', function() {
    if (/^#[0-9A-Fa-f]{6}$/.test(this.value)) {
        document.getElementById('bgColor').value = this.value;
        updatePreview();
    }
});

document.getElementById('textColor').addEventListener('input', function() {
    document.getElementById('textColorText').value = this.value.toUpperCase();
    updatePreview();
});

document.getElementById('textColorText').addEventListener('input', function() {
    if (/^#[0-9A-Fa-f]{6}$/.test(this.value)) {
        document.getElementById('textColor').value = this.value;
        updatePreview();
    }
});

function updatePreview() {
    var preview = document.getElementById('marqueePreview');
    var content = preview.querySelector('.marquee-preview-content');
    preview.style.background = document.getElementById('bgColor').value;
    content.style.color = document.getElementById('textColor').value;
}

// İkon önizleme
document.getElementById('addIconInput').addEventListener('input', function() {
    var preview = document.getElementById('addIconPreview');
    if (this.value.trim()) {
        preview.innerHTML = '<i class="' + this.value.trim() + '"></i>';
    } else {
        preview.innerHTML = '<i class="fas fa-icons"></i>';
    }
});

document.getElementById('editIcon').addEventListener('input', function() {
    var preview = document.getElementById('editIconPreview');
    if (this.value.trim()) {
        preview.innerHTML = '<i class="' + this.value.trim() + '"></i>';
    } else {
        preview.innerHTML = '<i class="fas fa-icons"></i>';
    }
});

// Düzenle
function editItem(item) {
    document.getElementById('editItemId').value = item.id;
    document.getElementById('editText').value = item.text;
    document.getElementById('editIcon').value = item.icon || '';
    document.getElementById('editLink').value = item.link || '';
    document.getElementById('editLinkText').value = item.link_text || '';
    document.getElementById('editActive').checked = item.is_active == 1;
    
    var preview = document.getElementById('editIconPreview');
    if (item.icon) {
        preview.innerHTML = '<i class="' + item.icon + '"></i>';
    } else {
        preview.innerHTML = '<i class="fas fa-icons"></i>';
    }
    
    new bootstrap.Modal(document.getElementById('editItemModal')).show();
}

// Sil
function deleteItem(id) {
    Swal.fire({
        title: 'Emin misiniz?',
        text: 'Bu öğe silinecek!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Evet, Sil',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('deleteItemId').value = id;
            document.getElementById('deleteForm').submit();
        }
    });
}

// Sıralama (Drag & Drop)
var itemsBody = document.getElementById('itemsBody');
if (itemsBody) {
    new Sortable(itemsBody, {
        handle: '.drag-handle',
        animation: 150,
        onEnd: function() {
            var orders = {};
            itemsBody.querySelectorAll('tr').forEach(function(row, index) {
                orders[row.dataset.id] = index + 1;
            });
            
            var formData = new FormData();
            formData.append('csrf_token', '<?php echo $csrfToken; ?>');
            formData.append('action', 'reorder');
            
            for (var id in orders) {
                formData.append('orders[' + id + ']', orders[id]);
            }
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            });
        }
    });
}

// Sidebar toggle
document.getElementById('menuToggle')?.addEventListener('click', function() {
    document.getElementById('sidebar').classList.toggle('show');
    document.getElementById('sidebarOverlay').classList.toggle('show');
});

document.getElementById('sidebarClose')?.addEventListener('click', function() {
    document.getElementById('sidebar').classList.remove('show');
    document.getElementById('sidebarOverlay').classList.remove('show');
});

document.getElementById('sidebarOverlay')?.addEventListener('click', function() {
    document.getElementById('sidebar').classList.remove('show');
    this.classList.remove('show');
});
</script>

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