<?php
include "../includes/header3.php";

$seller_name = $_SESSION['seller_name'] ?? 'default_user';
$json_path = "../a/rtx/Setting_{$seller_name}.json";
?>

<style>
:root {
    --primary: #FF6B9D;
    --primary-dark: #D94A7E;
    --secondary: #00D4FF;
    --accent: #FFD166;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --text-secondary: #B0B7C3;
    --text-muted: #6B7280;
    --border: rgba(255,255,255,0.1);
    --glow: 0 0 20px rgba(255, 107, 157, 0.3);
    --glow-secondary: 0 0 20px rgba(0, 212, 255, 0.3);
}

body {
    background: radial-gradient(1200px 600px at 30% -10%, rgba(255, 107, 157, 0.15), transparent),
                radial-gradient(1000px 500px at 80% 120%, rgba(0, 212, 255, 0.12), transparent),
                var(--surface);
    color: var(--text-primary);
    font-family: 'Inter', sans-serif;
}

.container-fluid {
    background: transparent !important;
    padding: 20px;
}

.h3 {
    color: var(--text-primary) !important;
    font-weight: 700;
    margin-bottom: 24px;
    text-align: center;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.card {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 20px !important;
    box-shadow: var(--glow) !important;
    backdrop-filter: blur(10px);
    margin-bottom: 24px;
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 40px rgba(255, 107, 157, 0.4);
}

.card-header {
    background: linear-gradient(135deg, var(--surface-lighter), var(--surface-light)) !important;
    border-bottom: 1px solid var(--border) !important;
    border-radius: 20px 20px 0 0 !important;
    padding: 20px 24px !important;
}

.text-primary2 {
    color: var(--text-primary) !important;
    font-weight: 600;
    font-size: 1.2rem;
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 0;
}

.card-body {
    padding: 40px !important;
}

/* === FORM STYLES === */
.theme-form {
    text-align: center;
    margin-bottom: 40px;
}

.custom-select {
    background: var(--surface-lighter) !important;
    border: 2px solid var(--border) !important;
    border-radius: 12px !important;
    color: var(--text-primary) !important;
    padding: 14px 20px !important;
    font-size: 1.1rem;
    font-weight: 600;
    transition: all 0.3s ease;
    min-width: 200px;
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23FF6B9D' viewBox='0 0 24 24'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 16px center;
    background-size: 16px;
}

.custom-select:focus {
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 0.3rem rgba(255, 107, 157, 0.2) !important;
    outline: none;
}

.custom-select option {
    background: var(--surface-lighter);
    color: var(--text-primary);
    padding: 12px;
}

.btn-success {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    border: none !important;
    border-radius: 12px !important;
    padding: 14px 32px !important;
    font-weight: 700;
    font-size: 1.1rem;
    transition: all 0.3s ease;
    box-shadow: var(--glow);
    margin-top: 20px;
}

.btn-success:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(255, 107, 157, 0.5);
}

/* === THEME GRID === */
.themes-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 30px;
    margin-top: 40px;
}

.theme-card {
    background: var(--surface-lighter);
    border: 2px solid var(--border);
    border-radius: 20px;
    padding: 25px;
    text-align: center;
    transition: all 0.4s ease;
    position: relative;
    overflow: hidden;
    cursor: pointer;
}

.theme-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.1), transparent);
    transition: left 0.6s ease;
}

.theme-card:hover::before {
    left: 100%;
}

.theme-card:hover {
    transform: translateY(-8px);
    border-color: var(--secondary);
    box-shadow: var(--glow-secondary);
}

.theme-card.selected-theme {
    border-color: var(--primary);
    box-shadow: var(--glow);
    background: linear-gradient(135deg, var(--surface-lighter), rgba(255, 107, 157, 0.1));
    transform: scale(1.02);
}

.theme-card.selected-theme::after {
    content: '✓ SELECIONADO';
    position: absolute;
    top: 15px;
    right: 15px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: var(--text-primary);
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 700;
    box-shadow: var(--glow);
}

.theme-title {
    font-size: 1.4rem;
    font-weight: 700;
    margin-bottom: 20px;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.theme-image {
    width: 100%;
    height: 180px;
    border-radius: 12px;
    object-fit: cover;
    border: 2px solid var(--border);
    transition: all 0.3s ease;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.theme-card:hover .theme-image {
    border-color: var(--primary);
    transform: scale(1.05);
}

/* === CURRENT THEME DISPLAY === */
.current-theme-display {
    background: rgba(0, 212, 255, 0.1);
    border: 1px solid var(--secondary);
    border-radius: 16px;
    padding: 25px;
    margin: 30px 0;
    text-align: center;
    position: relative;
    overflow: hidden;
}

.current-theme-display::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: var(--secondary);
}

.current-theme-label {
    font-size: 1rem;
    color: var(--text-secondary);
    margin-bottom: 8px;
}

.current-theme-value {
    font-size: 1.4rem;
    font-weight: 700;
    color: var(--text-primary);
    background: linear-gradient(135deg, var(--secondary), var(--primary));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

/* === ALERTS === */
.alert {
    border: none !important;
    border-radius: 16px !important;
    padding: 20px 25px !important;
    margin-bottom: 25px !important;
    font-weight: 600;
}

.alert-success {
    background: rgba(0, 212, 255, 0.1) !important;
    color: var(--text-primary) !important;
    border-left: 4px solid var(--secondary) !important;
}

.alert-danger {
    background: rgba(255, 71, 87, 0.1) !important;
    color: var(--text-primary) !important;
    border-left: 4px solid #FF4757 !important;
}

/* === TOAST NOTIFICATION === */
.toast-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    background: var(--surface-lighter);
    color: var(--text-primary);
    padding: 16px 20px;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    border: 1px solid var(--border);
    z-index: 10000;
    transform: translateX(400px);
    opacity: 0;
    transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    max-width: 350px;
    backdrop-filter: blur(10px);
}

.toast-notification.show {
    transform: translateX(0);
    opacity: 1;
}

.toast-notification.success {
    border-left: 4px solid #00D4FF;
    background: rgba(0, 212, 255, 0.1);
}

.toast-progress {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary), var(--accent));
    border-radius: 0 0 12px 12px;
    animation: progress 3s linear forwards;
}

@keyframes progress {
    0% { width: 100%; }
    100% { width: 0%; }
}

/* === RESPONSIVIDADE === */
@media (max-width: 768px) {
    .container-fluid {
        padding: 16px;
    }
    
    .card-body {
        padding: 25px !important;
    }
    
    .themes-grid {
        grid-template-columns: 1fr;
        gap: 20px;
    }
    
    .theme-card {
        padding: 20px;
    }
    
    .custom-select {
        width: 100%;
        margin-bottom: 15px;
    }
    
    .toast-notification {
        top: 10px;
        right: 10px;
        left: 10px;
        max-width: none;
    }
}
</style>

<!-- Toast Notification Container -->
<div id="toastContainer"></div>

<script>
// Sistema de Toast Notification
function showToast(message, type = 'success') {
    const toastContainer = document.getElementById('toastContainer');
    const toastId = 'toast-' + Date.now();
    
    const toast = document.createElement('div');
    toast.className = `toast-notification ${type}`;
    toast.id = toastId;
    toast.innerHTML = `
        <div style="display: flex; align-items: center; gap: 12px;">
            <div style="font-size: 1.2rem;">${type === 'success' ? '✅' : '❌'}</div>
            <div style="font-weight: 500; line-height: 1.4;">${message}</div>
        </div>
        <div class="toast-progress"></div>
    `;
    
    toastContainer.appendChild(toast);
    
    // Mostrar toast
    setTimeout(() => {
        toast.classList.add('show');
    }, 100);
    
    // Remover toast após 3 segundos
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 400);
    }, 3000);
}

// Mostrar toast se houve sucesso no POST
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($selectedOption)): ?>
    document.addEventListener('DOMContentLoaded', function() {
        showToast('✅ Tema atualizado com sucesso!', 'success');
    });
<?php endif; ?>

// Seleção interativa de temas
document.addEventListener('DOMContentLoaded', function() {
    const themeCards = document.querySelectorAll('.theme-card');
    const themeSelect = document.getElementById('options');
    
    themeCards.forEach(card => {
        card.addEventListener('click', function() {
            const themeName = this.querySelector('.theme-title').textContent.replace('TEMA ', '').trim();
            const themeValue = this.querySelector('img').alt;
            
            // Atualizar select
            themeSelect.value = themeValue;
            
            // Remover seleção anterior
            themeCards.forEach(c => c.classList.remove('selected-theme'));
            
            // Adicionar seleção atual
            this.classList.add('selected-theme');
            
            showToast(`🎨 Tema ${themeName} selecionado! Clique em "Salvar" para aplicar.`, 'success');
        });
    });
    
    // Atualizar cards quando select mudar
    themeSelect.addEventListener('change', function() {
        const selectedValue = this.value;
        
        // Remover seleção anterior
        themeCards.forEach(c => c.classList.remove('selected-theme'));
        
        // Adicionar seleção atual
        const selectedCard = document.querySelector(`.theme-card img[alt="${selectedValue}"]`)?.closest('.theme-card');
        if (selectedCard) {
            selectedCard.classList.add('selected-theme');
        }
    });
});

// Feedback visual no formulário
document.querySelector('form').addEventListener('submit', function(e) {
    const selectedOption = document.getElementById('options').value;
    if (!selectedOption) {
        e.preventDefault();
        showToast('❌ Selecione um tema antes de salvar!', 'error');
        return false;
    }
    showToast('⏳ Aplicando tema, aguarde...', 'success');
    return true;
});
</script>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">
        <i class="fas fa-palette"></i> Temas
    </h1>

    <div class="card border-left-primary shadow h-100 card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary2">
                <i class="fas fa-cogs"></i> Personalizar Aparência
            </h6>
        </div>
        <div class="card-body">

        <?php
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $selectedOption = $_POST['options'] ?? '';
                if ($selectedOption && file_exists($json_path)) {
                    $jsonData = file_get_contents($json_path);
                    $data = json_decode($jsonData, true);

                    $data[0]["RTXSetting"] = "mLayout";
                    $data[0]["PanalData"] = $selectedOption;

                    file_put_contents($json_path, json_encode($data, JSON_PRETTY_PRINT));

                    echo "<div class='alert alert-success'>Tema atualizado para: <strong>" . htmlspecialchars($selectedOption) . "</strong></div>";
                } else {
                    echo "<div class='alert alert-danger'>Arquivo JSON não encontrado ou opção inválida.</div>";
                }
            }

            // Ler o tema atual para destacar
            if (file_exists($json_path)) {
                $jsonData = file_get_contents($json_path);
                $data = json_decode($jsonData, true);
                $current_layout = $data[0]["PanalData"] ?? '';
            } else {
                $current_layout = '';
                echo "<div class='alert alert-danger'>Arquivo de configuração não encontrado.</div>";
            }
        ?>

        <!-- Display do Tema Atual -->
        <div class="current-theme-display">
            <div class="current-theme-label">
                <i class="fas fa-star"></i> TEMA ATUAL
            </div>
            <div class="current-theme-value">
                <?php echo htmlspecialchars($current_layout ?: 'Nenhum tema selecionado'); ?>
            </div>
        </div>

        <!-- Formulário de Seleção -->
        <form method="post" action="" class="theme-form">
            <select name="options" id="options" class="custom-select" required>
                <option value="theme_d" <?php if ($current_layout === "theme_d") echo "selected"; ?>>Tema 1 - Moderno</option>
                <option value="theme_2" <?php if ($current_layout === "theme_2") echo "selected"; ?>>Tema 2 - Clássico</option>
                <option value="theme_3" <?php if ($current_layout === "theme_3") echo "selected"; ?>>Tema 3 - Escuro</option>
                <option value="theme_4" <?php if ($current_layout === "theme_4") echo "selected"; ?>>Tema 4 - Colorido</option>
            </select>
            <br>
            <button type="submit" class="btn btn-success btn-icon-split">
                <span class="icon text-white-50">
                    <i class="fas fa-save"></i>
                </span>
                <span class="text">Aplicar Tema</span>
            </button>
        </form>

        <!-- Grid de Temas -->
        <div class="themes-grid">
            <div class="theme-card <?php if($current_layout === 'theme_d') echo 'selected-theme'; ?>" data-theme="theme_d">
                <div class="theme-title">TEMA 1</div>
                <img src="../rtx/layout/d.png" class="theme-image" alt="theme_d">
                <div style="margin-top: 15px; color: var(--text-secondary); font-size: 0.9rem;">
                    <i class="fas fa-bolt"></i> Layout Moderno
                </div>
            </div>

            <div class="theme-card <?php if($current_layout === 'theme_2') echo 'selected-theme'; ?>" data-theme="theme_2">
                <div class="theme-title">TEMA 2</div>
                <img src="../rtx/layout/2.png" class="theme-image" alt="theme_2">
                <div style="margin-top: 15px; color: var(--text-secondary); font-size: 0.9rem;">
                    <i class="fas fa-gem"></i> Design Clássico
                </div>
            </div>   

            <div class="theme-card <?php if($current_layout === 'theme_3') echo 'selected-theme'; ?>" data-theme="theme_3">
                <div class="theme-title">TEMA 3</div>
                <img src="../rtx/layout/3.png" class="theme-image" alt="theme_3">
                <div style="margin-top: 15px; color: var(--text-secondary); font-size: 0.9rem;">
                    <i class="fas fa-moon"></i> Modo Escuro
                </div>
            </div>

            <div class="theme-card <?php if($current_layout === 'theme_4') echo 'selected-theme'; ?>" data-theme="theme_4">
                <div class="theme-title">TEMA 4</div>
                <img src="../rtx/layout/4.png" class="theme-image" alt="theme_4">
                <div style="margin-top: 15px; color: var(--text-secondary); font-size: 0.9rem;">
                    <i class="fas fa-paint-brush"></i> Cores Vibrantes
                </div>
            </div>
        </div>

        </div>
    </div>
</div>

<?php
include "../includes/footer3.php";
?>