<?php
$title = 'Tema Özelleştirme';
$page_title = 'Tema Özelleştirme';

$theme_name = isset($segments[3]) ? $segments[3] : '';

if (empty($theme_name)) {
    m_redirect(ADMIN_URL . '/themes/lists');
}

// Tema klasörünün varlığını kontrol et
$theme_dir = ROOT_FOLDER . '/theme/' . $theme_name;
if (!is_dir($theme_dir)) {
    $_SESSION['error'] = 'Tema bulunamadı: ' . $theme_name;
    m_redirect(ADMIN_URL . '/themes/lists');
}

// Tema bilgilerini al
$theme_info_file = $theme_dir . '/theme.json';
$theme_info = [];
if (file_exists($theme_info_file)) {
    $theme_info = json_decode(file_get_contents($theme_info_file), true);
}

$theme_title = isset($theme_info['title']) ? $theme_info['title'] : ucfirst($theme_name);

// Tema dosyalarını listele
$theme_files = [];
$sections_dir = $theme_dir . '/sections';
if (is_dir($sections_dir)) {
    $theme_files = scandir($sections_dir);
    $theme_files = array_filter($theme_files, function($file) {
        return $file != '.' && $file != '..' && pathinfo($file, PATHINFO_EXTENSION) == 'php';
    });
}

// Tema ayarlarını JSON dosyasından al
$theme_title_db = isset($theme_info['title']) ? $theme_info['title'] : $theme_title;
$theme_description_db = isset($theme_info['description']) ? $theme_info['description'] : '';
$theme_version_db = isset($theme_info['version']) ? $theme_info['version'] : '1.0';
$theme_author_db = isset($theme_info['author']) ? $theme_info['author'] : '';
$theme_preview_image_db = isset($theme_info['preview_image']) ? $theme_info['preview_image'] : '';
?>

<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4 class="card-title mb-0"><?= $page_title ?> - <?= $theme_title ?></h4>
                <div>
                    <a href="<?= ADMIN_URL ?>/themes/lists" class="btn btn-secondary">
                        <i class="bx bx-arrow-back"></i> Geri Dön
                    </a>
                    <a href="<?= ADMIN_URL ?>/themes/preview/<?= $theme_name ?>" class="btn btn-info">
                        <i class="bx bx-show"></i> Önizle
                    </a>
                </div>
            </div>
            <div class="card-body">
                <div class="row">
                    <!-- Tema Bölümleri -->
                    <div class="col-lg-6">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Tema Bölümleri</h5>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($theme_files)): ?>
                                    <div class="list-group">
                                        <?php foreach ($theme_files as $file): ?>
                                            <?php $section_name = pathinfo($file, PATHINFO_FILENAME); ?>
                                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                                <div>
                                                    <h6 class="mb-1"><?= ucfirst(str_replace('_', ' ', $section_name)) ?></h6>
                                                    <small class="text-muted"><?= $file ?></small>
                                                </div>
                                                <div class="btn-group">
                                                    <a href="<?= DOMAIN ?>/theme/<?= $theme_name ?>/sections/<?= $file ?>" 
                                                       class="btn btn-sm btn-outline-primary" target="_blank">
                                                        <i class="bx bx-show"></i> Görüntüle
                                                    </a>
                                                    <a href="<?= ADMIN_URL ?>/editor?theme=<?= $theme_name ?>&section=<?= $section_name ?>" 
                                                       class="btn btn-sm btn-primary">
                                                        <i class="bx bx-edit"></i> Düzenle
                                                    </a>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="text-center py-4">
                                        <i class="bx bx-file fs-1 text-muted mb-3"></i>
                                        <h6 class="text-muted">Bölüm dosyası bulunamadı</h6>
                                        <p class="text-muted">Bu temada düzenlenebilir bölüm bulunmuyor.</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Tema Ayarları -->
                    <div class="col-lg-6">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Tema Ayarları</h5>
                            </div>
                            <div class="card-body">
                                <form id="themeSettingsForm">
                                    <input type="hidden" name="theme_name" value="<?= $theme_name ?>">
                                    
                                    <div class="mb-3">
                                        <label for="theme_title" class="form-label">Tema Başlığı</label>
                                        <input type="text" class="form-control" id="theme_title" name="title" 
                                               value="<?= htmlspecialchars($theme_title_db) ?>">
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="theme_description" class="form-label">Tema Açıklaması</label>
                                        <textarea class="form-control" id="theme_description" name="description" rows="3"><?= htmlspecialchars($theme_description_db) ?></textarea>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="theme_version" class="form-label">Versiyon</label>
                                                <input type="text" class="form-control" id="theme_version" name="version" 
                                                       value="<?= htmlspecialchars($theme_version_db) ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="theme_author" class="form-label">Geliştirici</label>
                                                <input type="text" class="form-control" id="theme_author" name="author" 
                                                       value="<?= htmlspecialchars($theme_author_db) ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="theme_preview_image" class="form-label">Önizleme Resmi</label>
                                        <input type="text" class="form-control" id="theme_preview_image" name="preview_image" 
                                               value="<?= htmlspecialchars($theme_preview_image_db) ?>">
                                        <small class="form-text text-muted">Tema klasörü içindeki resim dosyasının yolu (örn: assets/preview.jpg)</small>
                                    </div>
                                    
                                    <div class="d-grid">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="bx bx-save"></i> Ayarları Kaydet
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Hızlı İşlemler -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Hızlı İşlemler</h5>
                            </div>
                            <div class="card-body">
                                <div class="d-grid gap-2">
                                    <a href="<?= ADMIN_URL ?>/editor?theme=<?= $theme_name ?>" 
                                       class="btn btn-outline-primary">
                                        <i class="bx bx-edit"></i> Tema Editörü
                                    </a>
                                    <a href="<?= DOMAIN ?>/theme/<?= $theme_name ?>/editor.php?id=1" 
                                       class="btn btn-outline-info" target="_blank">
                                        <i class="bx bx-show"></i> Canlı Önizleme
                                    </a>
                                    <?php if (get_active_theme() != $theme_name): ?>
                                    <a href="#" 
                                       class="btn btn-success"
                                       onclick="activateTheme('<?= $theme_name ?>', '<?= $theme_title ?>')">
                                        <i class="bx bx-check"></i> Temayı Aktifleştir
                                    </a>
                                    <?php else: ?>
                                    <button class="btn btn-success" disabled>
                                        <i class="bx bx-check"></i> Aktif Tema
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#themeSettingsForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.html();
        
        // Loading durumu
        submitBtn.html('<i class="bx bx-loader-alt bx-spin"></i> Kaydediliyor...').prop('disabled', true);
        
        $.ajax({
            url: '<?= ADMIN_URL ?>/controller/theme_settings.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                try {
                    const result = JSON.parse(response);
                    if (result.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Başarılı!',
                            text: 'Tema ayarları başarıyla kaydedildi.',
                            confirmButtonText: 'Tamam'
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Hata!',
                            text: result.message || 'Ayarlar kaydedilirken bir hata oluştu.',
                            confirmButtonText: 'Tamam'
                        });
                    }
                } catch (e) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Hata!',
                        text: 'Sunucudan beklenmeyen bir yanıt alındı.',
                        confirmButtonText: 'Tamam'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Hata!',
                    text: 'Sunucu ile bağlantı kurulamadı.',
                    confirmButtonText: 'Tamam'
                });
            },
            complete: function() {
                submitBtn.html(originalText).prop('disabled', false);
            }
        });
    });
});

function activateTheme(themeName, themeTitle) {
    Swal.fire({
        title: 'Tema Aktifleştirme',
        text: `"${themeTitle}" temasını aktif hale getirmek istediğinizden emin misiniz?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Evet, Aktifleştir',
        cancelButtonText: 'İptal'
    }).then((result) => {
        if (result.isConfirmed) {
            // Loading göster
            Swal.fire({
                title: 'Aktifleştiriliyor...',
                text: 'Tema aktifleştiriliyor, lütfen bekleyin.',
                allowOutsideClick: false,
                allowEscapeKey: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Tema aktivasyon sayfasına yönlendir
            window.location.href = '<?= ADMIN_URL ?>/themes/activate/' + themeName;
        }
    });
}
</script> 