<?php
/**
 * SMM Paket Satış Scripti - Tema Ayarları
 * @version 1.0.2
 */

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'];

// Demo modu kontrolü
function isDemoMode() {
    global $db;
    try {
        $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = 'demo_mode'");
        $stmt->execute();
        $value = $stmt->fetchColumn();
        return $value === '1' || $value === 1;
    } catch (PDOException $e) {
        return false;
    }
}

$demoMode = isDemoMode();

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

// Aktif tema ID
$activeThemeId = (int)$settings->get('active_theme_id', 1);

// POST İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // Demo modunda işlem yapılamaz
    if ($demoMode) {
        setFlash('error', '🔒 Demo modunda tema ayarları değiştirilemez.');
        redirect(SITE_URL . '/admin/tema-ayarlari.php');
        exit;
    }
    
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Güvenlik hatası.');
        redirect(SITE_URL . '/admin/tema-ayarlari.php');
        exit;
    }
    
    $action = $_POST['action'];
    
    try {
        switch ($action) {
            case 'activate_theme':
                $themeId = (int)($_POST['theme_id'] ?? 0);
                
                if ($themeId <= 0) {
                    throw new Exception('Geçersiz tema.');
                }
                
                // Tema var mı kontrol et
                $checkTheme = $db->prepare("SELECT id FROM themes WHERE id = ?");
                $checkTheme->execute([$themeId]);
                if (!$checkTheme->fetch()) {
                    throw new Exception('Tema bulunamadı.');
                }
                
                // Aktif tema ayarını güncelle
                $check = $db->prepare("SELECT id FROM settings WHERE setting_key = 'active_theme_id'");
                $check->execute();
                if ($check->fetch()) {
                    $db->prepare("UPDATE settings SET setting_value = ?, updated_at = NOW() WHERE setting_key = 'active_theme_id'")->execute([$themeId]);
                } else {
                    $db->prepare("INSERT INTO settings (setting_key, setting_value, setting_group, created_at) VALUES ('active_theme_id', ?, 'appearance', NOW())")->execute([$themeId]);
                }
                
                setFlash('success', 'Tema başarıyla aktifleştirildi.');
                break;
                
            case 'update_theme':
                $themeId = (int)($_POST['theme_id'] ?? 0);
                $name = trim($_POST['name'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $primaryColor = trim($_POST['primary_color'] ?? '#6366f1');
                $secondaryColor = trim($_POST['secondary_color'] ?? '#8b5cf6');
                $accentColor = trim($_POST['accent_color'] ?? '#22d3ee');
                $backgroundColor = trim($_POST['background_color'] ?? '#0f172a');
                $textColor = trim($_POST['text_color'] ?? '#f8fafc');
                $headerBgColor = trim($_POST['header_bg_color'] ?? '#0f172a');
                $isDark = isset($_POST['is_dark']) ? 1 : 0;
                
                if ($themeId <= 0) {
                    throw new Exception('Geçersiz tema.');
                }
                
                if (empty($name)) {
                    throw new Exception('Tema adı zorunludur.');
                }
                
                // Renk validasyonu
                $colorPattern = '/^#[0-9A-Fa-f]{6}$/';
                if (!preg_match($colorPattern, $primaryColor)) $primaryColor = '#6366f1';
                if (!preg_match($colorPattern, $secondaryColor)) $secondaryColor = '#8b5cf6';
                if (!preg_match($colorPattern, $accentColor)) $accentColor = '#22d3ee';
                if (!preg_match($colorPattern, $backgroundColor)) $backgroundColor = '#0f172a';
                if (!preg_match($colorPattern, $textColor)) $textColor = '#f8fafc';
                if (!preg_match($colorPattern, $headerBgColor)) $headerBgColor = '#0f172a';
                
                $stmt = $db->prepare("
                    UPDATE themes 
                    SET name = ?, description = ?, primary_color = ?, secondary_color = ?, 
                        accent_color = ?, background_color = ?, text_color = ?, header_bg_color = ?, is_dark = ?
                    WHERE id = ?
                ");
                $stmt->execute([$name, $description, $primaryColor, $secondaryColor, $accentColor, $backgroundColor, $textColor, $headerBgColor, $isDark, $themeId]);
                
                setFlash('success', 'Tema güncellendi.');
                break;
                
            case 'add_theme':
                $name = trim($_POST['name'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $primaryColor = trim($_POST['primary_color'] ?? '#6366f1');
                $secondaryColor = trim($_POST['secondary_color'] ?? '#8b5cf6');
                $accentColor = trim($_POST['accent_color'] ?? '#22d3ee');
                $backgroundColor = trim($_POST['background_color'] ?? '#0f172a');
                $textColor = trim($_POST['text_color'] ?? '#f8fafc');
                $headerBgColor = trim($_POST['header_bg_color'] ?? '#0f172a');
                $isDark = isset($_POST['is_dark']) ? 1 : 0;
                
                if (empty($name)) {
                    throw new Exception('Tema adı zorunludur.');
                }
                
                // Folder oluştur
                $folder = preg_replace('/[^a-z0-9\-]/', '-', strtolower($name));
                $folder = preg_replace('/-+/', '-', $folder);
                $folder = trim($folder, '-');
                if (empty($folder)) $folder = 'custom-' . time();
                
                // Benzersiz folder
                $checkFolder = $db->prepare("SELECT id FROM themes WHERE folder = ?");
                $checkFolder->execute([$folder]);
                if ($checkFolder->fetch()) {
                    $folder = $folder . '-' . time();
                }
                
                // Sıralama
                $maxOrder = $db->query("SELECT MAX(sort_order) FROM themes")->fetchColumn();
                $sortOrder = ($maxOrder ?? 0) + 1;
                
                // Renk validasyonu
                $colorPattern = '/^#[0-9A-Fa-f]{6}$/';
                if (!preg_match($colorPattern, $headerBgColor)) $headerBgColor = '#0f172a';
                
                $stmt = $db->prepare("
                    INSERT INTO themes (name, folder, description, primary_color, secondary_color, accent_color, background_color, text_color, header_bg_color, is_dark, is_active, sort_order, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, NOW())
                ");
                $stmt->execute([$name, $folder, $description, $primaryColor, $secondaryColor, $accentColor, $backgroundColor, $textColor, $headerBgColor, $isDark, $sortOrder]);
                
                setFlash('success', 'Yeni tema oluşturuldu.');
                break;
                
            case 'delete_theme':
                $themeId = (int)($_POST['theme_id'] ?? 0);
                
                if ($themeId <= 0) {
                    throw new Exception('Geçersiz tema.');
                }
                
                // Aktif tema silinemez
                if ($themeId == $activeThemeId) {
                    throw new Exception('Aktif tema silinemez. Önce başka bir tema aktifleştirin.');
                }
                
                // Varsayılan temalar silinemez (ilk 8)
                if ($themeId <= 8) {
                    throw new Exception('Varsayılan temalar silinemez.');
                }
                
                $db->prepare("DELETE FROM themes WHERE id = ?")->execute([$themeId]);
                
                setFlash('success', 'Tema silindi.');
                break;
                
            case 'duplicate_theme':
                $themeId = (int)($_POST['theme_id'] ?? 0);
                
                if ($themeId <= 0) {
                    throw new Exception('Geçersiz tema.');
                }
                
                $stmt = $db->prepare("SELECT * FROM themes WHERE id = ?");
                $stmt->execute([$themeId]);
                $sourceTheme = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$sourceTheme) {
                    throw new Exception('Tema bulunamadı.');
                }
                
                $newName = $sourceTheme['name'] . ' (Kopya)';
                $newFolder = $sourceTheme['folder'] . '-copy-' . time();
                $maxOrder = $db->query("SELECT MAX(sort_order) FROM themes")->fetchColumn();
                
                $stmt = $db->prepare("
                    INSERT INTO themes (name, folder, description, primary_color, secondary_color, accent_color, background_color, text_color, header_bg_color, is_dark, is_active, sort_order, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, NOW())
                ");
                $stmt->execute([
                    $newName, $newFolder, $sourceTheme['description'],
                    $sourceTheme['primary_color'], $sourceTheme['secondary_color'], $sourceTheme['accent_color'],
                    $sourceTheme['background_color'], $sourceTheme['text_color'], $sourceTheme['header_bg_color'] ?? '#0f172a',
                    $sourceTheme['is_dark'],
                    ($maxOrder ?? 0) + 1
                ]);
                
                setFlash('success', 'Tema kopyalandı.');
                break;
        }
    } catch (Exception $e) {
        setFlash('error', $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/tema-ayarlari.php');
    exit;
}

// Temaları yeniden çek (güncellemeden sonra)
try {
    $themes = $db->query("SELECT * FROM themes ORDER BY sort_order ASC, id ASC")->fetchAll(PDO::FETCH_ASSOC);
    $activeThemeId = (int)$settings->get('active_theme_id', 1);
} catch (PDOException $e) {
    $themes = [];
}

$adminPageTitle = 'Tema Ayarları';
require_once __DIR__ . '/header.php';
?>

<style>
/* Demo Banner */
.demo-banner {
    background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(239, 68, 68, 0.15));
    border: 1px solid rgba(245, 158, 11, 0.3);
    border-radius: 12px;
    padding: 15px 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.demo-banner i { font-size: 24px; color: #f59e0b; }
.demo-banner-text h4 { margin: 0 0 4px; font-size: 14px; font-weight: 600; color: #f59e0b; }
.demo-banner-text p { margin: 0; font-size: 12px; color: var(--text-secondary); }

/* 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);
}

/* Theme Grid */
.themes-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
}

/* Theme Card */
.theme-card {
    background: var(--bg-card);
    border: 2px solid var(--border-color);
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s;
    position: relative;
}

.theme-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 40px rgba(0,0,0,0.2);
}

.theme-card.active {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.2);
}

.theme-card.active::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: var(--gradient);
}

/* Theme Preview */
.theme-preview {
    height: 160px;
    position: relative;
    overflow: hidden;
}

.theme-preview-bg {
    position: absolute;
    inset: 0;
    display: flex;
}

.theme-preview-sidebar {
    width: 60px;
    display: flex;
    flex-direction: column;
    padding: 10px 8px;
    gap: 6px;
    border-right: 1px solid rgba(255,255,255,0.1);
}

.theme-preview-sidebar .menu-item {
    height: 8px;
    border-radius: 4px;
    opacity: 0.3;
}

.theme-preview-sidebar .menu-item.active {
    opacity: 1;
}

.theme-preview-content {
    flex: 1;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.theme-preview-header {
    height: 20px;
    border-radius: 6px;
    opacity: 0.9;
}

.theme-preview-cards {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    flex: 1;
}

.theme-preview-card {
    border-radius: 8px;
    opacity: 0.15;
}

.theme-preview-card:first-child {
    opacity: 0.25;
}

/* Active Badge */
.active-badge {
    position: absolute;
    top: 12px;
    right: 12px;
    background: var(--success);
    color: #fff;
    font-size: 10px;
    font-weight: 700;
    padding: 5px 10px;
    border-radius: 20px;
    display: flex;
    align-items: center;
    gap: 5px;
    z-index: 10;
}

/* Theme Info */
.theme-info {
    padding: 20px;
    border-top: 1px solid var(--border-color);
}

.theme-name {
    font-size: 17px;
    font-weight: 700;
    margin: 0 0 5px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.theme-name .dark-badge {
    font-size: 9px;
    padding: 3px 8px;
    border-radius: 10px;
    background: rgba(255,255,255,0.1);
    color: var(--text-secondary);
    font-weight: 600;
}

.theme-description {
    font-size: 13px;
    color: var(--text-secondary);
    margin: 0 0 15px;
    line-height: 1.5;
}

/* Color Palette */
.color-palette {
    display: flex;
    gap: 8px;
    margin-bottom: 18px;
}

.color-dot {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    border: 2px solid rgba(255,255,255,0.1);
    cursor: pointer;
    transition: all 0.2s;
    position: relative;
}

.color-dot:hover {
    transform: scale(1.15);
}

.color-dot::after {
    content: attr(data-label);
    position: absolute;
    bottom: calc(100% + 8px);
    left: 50%;
    transform: translateX(-50%);
    background: var(--bg-dark);
    color: var(--text-primary);
    font-size: 10px;
    padding: 4px 8px;
    border-radius: 6px;
    white-space: nowrap;
    opacity: 0;
    visibility: hidden;
    transition: all 0.2s;
    pointer-events: none;
}

.color-dot:hover::after {
    opacity: 1;
    visibility: visible;
}

/* Theme Actions */
.theme-actions {
    display: flex;
    gap: 8px;
}

.theme-actions .btn {
    flex: 1;
    padding: 10px;
    border: none;
    border-radius: 10px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    transition: all 0.2s;
}

.btn-activate {
    background: var(--gradient);
    color: #fff;
}

.btn-activate:hover {
    box-shadow: 0 5px 20px rgba(var(--primary-rgb), 0.4);
}

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

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

.btn-duplicate {
    background: rgba(139, 92, 246, 0.15);
    color: #8b5cf6;
}

.btn-duplicate:hover {
    background: #8b5cf6;
    color: #fff;
}

.btn-delete {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
    flex: 0;
    width: 42px;
}

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

.btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

/* 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-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);
}

/* Color Picker */
.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;
}

.color-input-group .form-control {
    flex: 1;
    font-family: 'Courier New', monospace;
    text-transform: uppercase;
}

/* Color Grid */
.colors-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
}

/* Toggle */
.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);
}

/* Live Preview */
.live-preview {
    background: var(--bg-hover);
    border-radius: 12px;
    padding: 20px;
    margin-top: 20px;
}

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

.preview-box {
    height: 120px;
    border-radius: 12px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    border: 1px solid rgba(255,255,255,0.1);
}

.preview-header-bar {
    height: 24px;
    display: flex;
    align-items: center;
    padding: 0 10px;
    gap: 6px;
}

.preview-header-bar .dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    opacity: 0.5;
}

.preview-body {
    flex: 1;
    display: flex;
}

.preview-sidebar {
    width: 50px;
    padding: 10px 6px;
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.preview-sidebar .item {
    height: 6px;
    border-radius: 3px;
    opacity: 0.3;
}

.preview-sidebar .item.active {
    opacity: 1;
}

.preview-main {
    flex: 1;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.preview-content-header {
    height: 12px;
    border-radius: 4px;
    opacity: 0.1;
    width: 60%;
}

.preview-cards {
    display: flex;
    gap: 6px;
    flex: 1;
}

.preview-card {
    flex: 1;
    border-radius: 6px;
    opacity: 0.15;
}

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

.info-box i {
    margin-top: 2px;
}

/* Responsive */
@media (max-width: 768px) {
    .themes-grid {
        grid-template-columns: 1fr;
    }
    
    .colors-grid {
        grid-template-columns: 1fr;
    }
    
    .theme-actions {
        flex-wrap: wrap;
    }
    
    .theme-actions .btn {
        min-width: calc(50% - 4px);
    }
    
    .btn-delete {
        flex: 1;
        width: auto;
    }
}
</style>

<?php if ($demoMode): ?>
<div class="demo-banner">
    <i class="fas fa-shield-alt"></i>
    <div class="demo-banner-text">
        <h4>Demo Modu Aktif</h4>
        <p>Demo modunda tema ayarları görüntülenebilir ancak değiştirilemez.</p>
    </div>
</div>
<?php endif; ?>

<div class="page-header">
    <h2><i class="fas fa-palette"></i> Tema Ayarları</h2>
    <?php if ($demoMode): ?>
    <button class="btn-primary-custom" disabled style="opacity: 0.5; cursor: not-allowed;">
        <i class="fas fa-lock"></i> Demo Mod
    </button>
    <?php else: ?>
    <button class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addThemeModal">
        <i class="fas fa-plus"></i> Yeni Tema
    </button>
    <?php endif; ?>
</div>

<div class="info-box">
    <i class="fas fa-info-circle"></i>
    <div>
        Sitenizdeki renk şemasını buradan yönetebilirsiniz. Aktif temayı değiştirmek için "Aktifleştir" butonuna tıklayın. 
        Mevcut temaları düzenleyebilir veya kendi temanızı oluşturabilirsiniz.
    </div>
</div>

<!-- Themes Grid -->
<div class="themes-grid">
    <?php foreach ($themes as $t): 
        $isActive = ($t['id'] == $activeThemeId);
        $headerBg = $t['header_bg_color'] ?? '#0f172a';
    ?>
    <div class="theme-card <?php echo $isActive ? 'active' : ''; ?>">
        <?php if ($isActive): ?>
        <span class="active-badge"><i class="fas fa-check"></i> Aktif</span>
        <?php endif; ?>
        
        <!-- Theme Preview -->
        <div class="theme-preview">
            <div class="theme-preview-bg" style="background: <?php echo $t['background_color']; ?>">
                <!-- Header Preview -->
                <div style="position: absolute; top: 0; left: 0; right: 0; height: 25px; background: <?php echo $headerBg; ?>; display: flex; align-items: center; padding: 0 10px; gap: 8px;">
                    <div style="width: 8px; height: 8px; border-radius: 50%; background: <?php echo $t['primary_color']; ?>"></div>
                    <div style="flex: 1; height: 6px; border-radius: 3px; background: <?php echo $t['text_color']; ?>; opacity: 0.2;"></div>
                </div>
                <div class="theme-preview-sidebar" style="background: <?php echo $t['is_dark'] ? 'rgba(0,0,0,0.3)' : 'rgba(0,0,0,0.05)'; ?>; margin-top: 25px;">
                    <div class="menu-item" style="background: <?php echo $t['text_color']; ?>"></div>
                    <div class="menu-item active" style="background: <?php echo $t['primary_color']; ?>"></div>
                    <div class="menu-item" style="background: <?php echo $t['text_color']; ?>"></div>
                    <div class="menu-item" style="background: <?php echo $t['text_color']; ?>"></div>
                </div>
                <div class="theme-preview-content" style="margin-top: 25px;">
                    <div class="theme-preview-cards">
                        <div class="theme-preview-card" style="background: <?php echo $t['primary_color']; ?>"></div>
                        <div class="theme-preview-card" style="background: <?php echo $t['secondary_color']; ?>"></div>
                        <div class="theme-preview-card" style="background: <?php echo $t['accent_color']; ?>"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Theme Info -->
        <div class="theme-info">
            <h3 class="theme-name">
                <?php echo clean($t['name']); ?>
                <span class="dark-badge"><?php echo $t['is_dark'] ? 'Koyu' : 'Açık'; ?></span>
            </h3>
            <p class="theme-description"><?php echo clean($t['description'] ?: 'Açıklama yok'); ?></p>
            
            <!-- Color Palette -->
            <div class="color-palette">
                <div class="color-dot" style="background: <?php echo $t['primary_color']; ?>" data-label="Ana Renk"></div>
                <div class="color-dot" style="background: <?php echo $t['secondary_color']; ?>" data-label="İkincil"></div>
                <div class="color-dot" style="background: <?php echo $t['accent_color']; ?>" data-label="Vurgu"></div>
                <div class="color-dot" style="background: <?php echo $t['background_color']; ?>" data-label="Arkaplan"></div>
                <div class="color-dot" style="background: <?php echo $t['text_color']; ?>" data-label="Metin"></div>
                <div class="color-dot" style="background: <?php echo $headerBg; ?>" data-label="Header"></div>
            </div>
            
            <!-- Actions -->
            <div class="theme-actions">
                <?php if (!$isActive): ?>
                <?php if ($demoMode): ?>
                <button class="btn btn-activate" disabled>
                    <i class="fas fa-lock"></i> Demo
                </button>
                <?php else: ?>
                <form method="POST" style="flex: 1; display: contents;">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="activate_theme">
                    <input type="hidden" name="theme_id" value="<?php echo $t['id']; ?>">
                    <button type="submit" class="btn btn-activate">
                        <i class="fas fa-check"></i> Aktifleştir
                    </button>
                </form>
                <?php endif; ?>
                <?php endif; ?>
                
                <?php if ($demoMode): ?>
                <button class="btn btn-edit" disabled>
                    <i class="fas fa-lock"></i>
                </button>
                <button class="btn btn-duplicate" disabled>
                    <i class="fas fa-lock"></i>
                </button>
                <?php else: ?>
                <button class="btn btn-edit" onclick="editTheme(<?php echo htmlspecialchars(json_encode($t)); ?>)">
                    <i class="fas fa-edit"></i> Düzenle
                </button>
                
                <button class="btn btn-duplicate" onclick="duplicateTheme(<?php echo $t['id']; ?>, '<?php echo clean($t['name']); ?>')">
                    <i class="fas fa-copy"></i>
                </button>
                <?php endif; ?>
                
                <?php if ($t['id'] > 8 && !$isActive && !$demoMode): ?>
                <button class="btn btn-delete" onclick="deleteTheme(<?php echo $t['id']; ?>, '<?php echo clean($t['name']); ?>')">
                    <i class="fas fa-trash"></i>
                </button>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php if (!$demoMode): ?>
<!-- Add Theme Modal -->
<div class="modal fade" id="addThemeModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST" id="addThemeForm">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="add_theme">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus-circle"></i> Yeni Tema Oluştur</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">Tema Adı</label>
                        <input type="text" name="name" class="form-control" placeholder="Örn: Özel Temam" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Açıklama</label>
                        <input type="text" name="description" class="form-control" placeholder="Tema hakkında kısa açıklama">
                    </div>
                    
                    <div class="colors-grid">
                        <div class="form-group">
                            <label class="form-label">Ana Renk (Primary)</label>
                            <div class="color-input-group">
                                <input type="color" name="primary_color" class="color-picker" value="#6366f1" onchange="syncColorInput(this)">
                                <input type="text" class="form-control" value="#6366f1" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">İkincil Renk (Secondary)</label>
                            <div class="color-input-group">
                                <input type="color" name="secondary_color" class="color-picker" value="#8b5cf6" onchange="syncColorInput(this)">
                                <input type="text" class="form-control" value="#8b5cf6" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Vurgu Rengi (Accent)</label>
                            <div class="color-input-group">
                                <input type="color" name="accent_color" class="color-picker" value="#22d3ee" onchange="syncColorInput(this)">
                                <input type="text" class="form-control" value="#22d3ee" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Arkaplan Rengi</label>
                            <div class="color-input-group">
                                <input type="color" name="background_color" class="color-picker" value="#0f172a" onchange="syncColorInput(this)">
                                <input type="text" class="form-control" value="#0f172a" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Metin Rengi</label>
                            <div class="color-input-group">
                                <input type="color" name="text_color" class="color-picker" value="#f8fafc" onchange="syncColorInput(this)">
                                <input type="text" class="form-control" value="#f8fafc" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Header Arkaplan Rengi</label>
                            <div class="color-input-group">
                                <input type="color" name="header_bg_color" class="color-picker" value="#0f172a" onchange="syncColorInput(this)">
                                <input type="text" class="form-control" value="#0f172a" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group" style="margin-top: 15px;">
                        <div class="form-check-custom">
                            <input type="checkbox" name="is_dark" id="addIsDark" checked>
                            <label for="addIsDark">
                                <strong>Koyu Tema</strong>
                                <span>Karanlık arkaplan kullanır</span>
                            </label>
                        </div>
                    </div>
                    
                    <!-- Live Preview -->
                    <div class="live-preview">
                        <h5><i class="fas fa-eye"></i> Önizleme</h5>
                        <div class="preview-box" id="addPreviewBox">
                            <div class="preview-header-bar" id="addPreviewHeader">
                                <div class="dot"></div>
                                <div class="dot"></div>
                                <div class="dot"></div>
                            </div>
                            <div class="preview-body">
                                <div class="preview-sidebar">
                                    <div class="item"></div>
                                    <div class="item active"></div>
                                    <div class="item"></div>
                                </div>
                                <div class="preview-main">
                                    <div class="preview-content-header"></div>
                                    <div class="preview-cards">
                                        <div class="preview-card"></div>
                                        <div class="preview-card"></div>
                                        <div class="preview-card"></div>
                                    </div>
                                </div>
                            </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> Tema Oluştur
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Theme Modal -->
<div class="modal fade" id="editThemeModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST" id="editThemeForm">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="update_theme">
                <input type="hidden" name="theme_id" id="editThemeId">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> Tema 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">Tema Adı</label>
                        <input type="text" name="name" id="editName" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Açıklama</label>
                        <input type="text" name="description" id="editDescription" class="form-control">
                    </div>
                    
                    <div class="colors-grid">
                        <div class="form-group">
                            <label class="form-label">Ana Renk (Primary)</label>
                            <div class="color-input-group">
                                <input type="color" name="primary_color" id="editPrimary" class="color-picker" onchange="syncColorInput(this)">
                                <input type="text" id="editPrimaryText" class="form-control" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">İkincil Renk (Secondary)</label>
                            <div class="color-input-group">
                                <input type="color" name="secondary_color" id="editSecondary" class="color-picker" onchange="syncColorInput(this)">
                                <input type="text" id="editSecondaryText" class="form-control" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Vurgu Rengi (Accent)</label>
                            <div class="color-input-group">
                                <input type="color" name="accent_color" id="editAccent" class="color-picker" onchange="syncColorInput(this)">
                                <input type="text" id="editAccentText" class="form-control" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Arkaplan Rengi</label>
                            <div class="color-input-group">
                                <input type="color" name="background_color" id="editBackground" class="color-picker" onchange="syncColorInput(this)">
                                <input type="text" id="editBackgroundText" class="form-control" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Metin Rengi</label>
                            <div class="color-input-group">
                                <input type="color" name="text_color" id="editText" class="color-picker" onchange="syncColorInput(this)">
                                <input type="text" id="editTextText" class="form-control" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Header Arkaplan Rengi</label>
                            <div class="color-input-group">
                                <input type="color" name="header_bg_color" id="editHeaderBg" class="color-picker" onchange="syncColorInput(this)">
                                <input type="text" id="editHeaderBgText" class="form-control" maxlength="7" onchange="syncColorPicker(this)">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group" style="margin-top: 15px;">
                        <div class="form-check-custom">
                            <input type="checkbox" name="is_dark" id="editIsDark">
                            <label for="editIsDark">
                                <strong>Koyu Tema</strong>
                                <span>Karanlık arkaplan kullanır</span>
                            </label>
                        </div>
                    </div>
                    
                    <!-- Live Preview -->
                    <div class="live-preview">
                        <h5><i class="fas fa-eye"></i> Önizleme</h5>
                        <div class="preview-box" id="editPreviewBox">
                            <div class="preview-header-bar" id="editPreviewHeader">
                                <div class="dot"></div>
                                <div class="dot"></div>
                                <div class="dot"></div>
                            </div>
                            <div class="preview-body">
                                <div class="preview-sidebar">
                                    <div class="item"></div>
                                    <div class="item active"></div>
                                    <div class="item"></div>
                                </div>
                                <div class="preview-main">
                                    <div class="preview-content-header"></div>
                                    <div class="preview-cards">
                                        <div class="preview-card"></div>
                                        <div class="preview-card"></div>
                                        <div class="preview-card"></div>
                                    </div>
                                </div>
                            </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>
<?php endif; ?>

<script>
var csrfToken = '<?php echo $csrfToken; ?>';
var demoMode = <?php echo $demoMode ? 'true' : 'false'; ?>;

// Color input sync
function syncColorInput(picker) {
    var textInput = picker.parentElement.querySelector('input[type="text"]');
    if (textInput) {
        textInput.value = picker.value.toUpperCase();
    }
    updatePreview(picker.closest('form'));
}

function syncColorPicker(textInput) {
    var picker = textInput.parentElement.querySelector('input[type="color"]');
    var value = textInput.value;
    
    // # ekle
    if (value.charAt(0) !== '#') {
        value = '#' + value;
    }
    
    // Geçerli renk mi kontrol et
    if (/^#[0-9A-Fa-f]{6}$/.test(value)) {
        picker.value = value;
        textInput.value = value.toUpperCase();
        updatePreview(textInput.closest('form'));
    }
}

// Update preview
function updatePreview(form) {
    var previewBox = form.querySelector('.preview-box');
    if (!previewBox) return;
    
    var primary = form.querySelector('input[name="primary_color"]').value;
    var secondary = form.querySelector('input[name="secondary_color"]').value;
    var accent = form.querySelector('input[name="accent_color"]').value;
    var bg = form.querySelector('input[name="background_color"]').value;
    var text = form.querySelector('input[name="text_color"]').value;
    var headerBg = form.querySelector('input[name="header_bg_color"]').value;
    var isDark = form.querySelector('input[name="is_dark"]').checked;
    
    // Preview body background
    var previewBody = previewBox.querySelector('.preview-body');
    if (previewBody) {
        previewBody.style.background = bg;
    }
    
    // Header bar
    var headerBar = previewBox.querySelector('.preview-header-bar');
    if (headerBar) {
        headerBar.style.background = headerBg;
        headerBar.querySelectorAll('.dot').forEach(function(dot) {
            dot.style.background = text;
        });
    }
    
    var sidebar = previewBox.querySelector('.preview-sidebar');
    if (sidebar) {
        sidebar.style.background = isDark ? 'rgba(0,0,0,0.3)' : 'rgba(0,0,0,0.05)';
        sidebar.querySelectorAll('.item').forEach(function(item, index) {
            item.style.background = index === 1 ? primary : text;
        });
    }
    
    var contentHeader = previewBox.querySelector('.preview-content-header');
    if (contentHeader) {
        contentHeader.style.background = text;
    }
    
    var cards = previewBox.querySelectorAll('.preview-card');
    if (cards[0]) cards[0].style.background = primary;
    if (cards[1]) cards[1].style.background = secondary;
    if (cards[2]) cards[2].style.background = accent;
}

<?php if (!$demoMode): ?>
// Edit theme
function editTheme(theme) {
    document.getElementById('editThemeId').value = theme.id;
    document.getElementById('editName').value = theme.name;
    document.getElementById('editDescription').value = theme.description || '';
    
    document.getElementById('editPrimary').value = theme.primary_color;
    document.getElementById('editPrimaryText').value = theme.primary_color.toUpperCase();
    
    document.getElementById('editSecondary').value = theme.secondary_color;
    document.getElementById('editSecondaryText').value = theme.secondary_color.toUpperCase();
    
    document.getElementById('editAccent').value = theme.accent_color;
    document.getElementById('editAccentText').value = theme.accent_color.toUpperCase();
    
    document.getElementById('editBackground').value = theme.background_color;
    document.getElementById('editBackgroundText').value = theme.background_color.toUpperCase();
    
    document.getElementById('editText').value = theme.text_color;
    document.getElementById('editTextText').value = theme.text_color.toUpperCase();
    
    var headerBgColor = theme.header_bg_color || '#0f172a';
    document.getElementById('editHeaderBg').value = headerBgColor;
    document.getElementById('editHeaderBgText').value = headerBgColor.toUpperCase();
    
    document.getElementById('editIsDark').checked = theme.is_dark == 1;
    
    updatePreview(document.getElementById('editThemeForm'));
    
    new bootstrap.Modal(document.getElementById('editThemeModal')).show();
}

// Duplicate theme
function duplicateTheme(themeId, themeName) {
    Swal.fire({
        title: 'Temayı Kopyala',
        text: '"' + themeName + '" temasının bir kopyası oluşturulacak.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#8b5cf6',
        cancelButtonColor: '#64748b',
        confirmButtonText: '<i class="fas fa-copy me-1"></i> Kopyala',
        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="duplicate_theme">' +
                '<input type="hidden" name="theme_id" value="' + themeId + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

// Delete theme
function deleteTheme(themeId, themeName) {
    Swal.fire({
        title: 'Temayı Sil',
        html: '<strong>' + themeName + '</strong> teması silinecek.<br><small class="text-muted">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_theme">' +
                '<input type="hidden" name="theme_id" value="' + themeId + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

// Initialize previews on modal open
document.getElementById('addThemeModal').addEventListener('shown.bs.modal', function() {
    updatePreview(document.getElementById('addThemeForm'));
});

// Add event listeners for live preview update
document.querySelectorAll('#addThemeForm input').forEach(function(input) {
    input.addEventListener('input', function() {
        updatePreview(document.getElementById('addThemeForm'));
    });
    input.addEventListener('change', function() {
        updatePreview(document.getElementById('addThemeForm'));
    });
});

document.querySelectorAll('#editThemeForm input').forEach(function(input) {
    input.addEventListener('input', function() {
        updatePreview(document.getElementById('editThemeForm'));
    });
    input.addEventListener('change', function() {
        updatePreview(document.getElementById('editThemeForm'));
    });
});
<?php endif; ?>
</script>

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