<?php
ini_set('display_errors', 0);
include('includes/header.php');

$jsonFile = 'cores.json';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newStartColor = ($_POST['start_color_transparent'] === '1') ? '#00ffffff' : $_POST['start_color'];
    $newEndColor = ($_POST['end_color_transparent'] === '1') ? '#00ffffff' : $_POST['end_color'];
    $newBorderColor = ($_POST['border_color_transparent'] === '1') ? '#00ffffff' : $_POST['border_color'];
    $newBorderColorFocus = ($_POST['border_color_focus_transparent'] === '1') ? '#00ffffff' : $_POST['border_color_focus'];
    $newBorderWidth = (int)$_POST['border_width'];
    $newCornerRadius = (int)$_POST['corner_radius'];

    $newColors = [
        "START_COLOR_XML" => $newStartColor,
        "END_COLOR_XML" => $newEndColor,
        "BORDER_COLOR_NORMAL" => $newBorderColor,
        "BORDER_COLOR_FOCUS" => $newBorderColorFocus,
        "BORDER_WIDTH_DP" => $newBorderWidth,
        "CORNER_RADIUS_DP" => $newCornerRadius
    ];

    file_put_contents($jsonFile, json_encode($newColors, JSON_PRETTY_PRINT));
    $successMessage = "🎉 Configurações salvas com sucesso!";
}

$cores = json_decode(file_get_contents($jsonFile), true);
?>

<div class="container-fluid px-4">
    <div class="row justify-content-center">
        <div class="col-xl-8 col-lg-10">
            <div class="card shadow-lg border-0 rounded-lg mt-5 animate__animated animate__fadeIn">
                <div class="card-header bg-gradient-primary-to-secondary text-white py-4">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="mb-0"><i class="fas fa-palette me-2"></i>🎨 Personalização de Cores</h3>
                            <p class="mb-0 mt-1 small opacity-75">Personalize as cores e estilos do seu aplicativo</p>
                        </div>
                        <div class="spinner-grow spinner-grow-sm text-light" role="status">
                            <span class="sr-only">Carregando...</span>
                        </div>
                    </div>
                </div>
                
                <!-- Pré-visualização no topo -->
                <div class="card-body border-bottom">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="preview-box p-4 text-center">
                                <p class="mb-3 fw-bold text-primary">Botão Normal</p>
                                <button class="btn preview-btn">Botão</button>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="preview-box p-4 text-center">
                                <p class="mb-3 fw-bold text-primary">Botão em Foco</p>
                                <button class="btn preview-btn focus">Botão</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php if(isset($successMessage)): ?>
                <div class="alert alert-success alert-dismissible fade show m-4 d-flex align-items-center" role="alert">
                    <i class="fas fa-check-circle me-2"></i>
                    <?php echo $successMessage; ?>
                    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <div class="card-body py-4">
                    <form method="POST" id="colorForm">
                        <div class="row g-4">
                            <!-- Grupo de Cores do Gradiente -->
                            <div class="col-md-6">
                                <div class="card h-100 border-0 shadow-sm">
                                    <div class="card-header bg-light">
                                        <h5 class="mb-0"><i class="fas fa-gradient me-2 text-primary"></i>Configurações do Gradiente</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label class="form-label fw-bold text-primary mb-2">🌈 Cor de Início</label>
                                            <div class="input-group">
                                                <span class="input-group-text bg-light"><i class="fas fa-fill-drip text-muted"></i></span>
                                                <input type="color" class="form-control form-control-color" id="start_color" name="start_color" value="<?php echo htmlspecialchars($cores['START_COLOR_XML']); ?>">
                                                <input type="hidden" id="start_color_transparent" name="start_color_transparent" value="0">
                                                <button type="button" class="btn btn-outline-primary" onclick="setTransparent('start_color')">
                                                    <i class="fas fa-eye-slash me-1"></i> Transparente
                                                </button>
                                            </div>
                                            <small class="form-text text-muted">Cor superior do gradiente</small>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label fw-bold text-primary mb-2">🌈 Cor de Fim</label>
                                            <div class="input-group">
                                                <span class="input-group-text bg-light"><i class="fas fa-fill text-muted"></i></span>
                                                <input type="color" class="form-control form-control-color" id="end_color" name="end_color" value="<?php echo htmlspecialchars($cores['END_COLOR_XML']); ?>">
                                                <input type="hidden" id="end_color_transparent" name="end_color_transparent" value="0">
                                                <button type="button" class="btn btn-outline-primary" onclick="setTransparent('end_color')">
                                                    <i class="fas fa-eye-slash me-1"></i> Transparente
                                                </button>
                                            </div>
                                            <small class="form-text text-muted">Cor inferior do gradiente</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Grupo de Cores de Borda -->
                            <div class="col-md-6">
                                <div class="card h-100 border-0 shadow-sm">
                                    <div class="card-header bg-light">
                                        <h5 class="mb-0"><i class="fas fa-border-style me-2 text-primary"></i>Configurações de Borda</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label class="form-label fw-bold text-primary mb-2">🖍️ Cor Normal</label>
                                            <div class="input-group">
                                                <span class="input-group-text bg-light"><i class="fas fa-square text-muted"></i></span>
                                                <input type="color" class="form-control form-control-color" id="border_color" name="border_color" value="<?php echo htmlspecialchars($cores['BORDER_COLOR_NORMAL']); ?>">
                                                <input type="hidden" id="border_color_transparent" name="border_color_transparent" value="0">
                                                <button type="button" class="btn btn-outline-primary" onclick="setTransparent('border_color')">
                                                    <i class="fas fa-eye-slash me-1"></i> Transparente
                                                </button>
                                            </div>
                                            <small class="form-text text-muted">Cor da borda no estado normal</small>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label fw-bold text-primary mb-2">✨ Cor em Foco</label>
                                            <div class="input-group">
                                                <span class="input-group-text bg-light"><i class="fas fa-square-full text-muted"></i></span>
                                                <input type="color" class="form-control form-control-color" id="border_color_focus" name="border_color_focus" value="<?php echo htmlspecialchars($cores['BORDER_COLOR_FOCUS']); ?>">
                                                <input type="hidden" id="border_color_focus_transparent" name="border_color_focus_transparent" value="0">
                                                <button type="button" class="btn btn-outline-primary" onclick="setTransparent('border_color_focus')">
                                                    <i class="fas fa-eye-slash me-1"></i> Transparente
                                                </button>
                                            </div>
                                            <small class="form-text text-muted">Cor da borda quando em foco</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Grupo de Configurações -->
                            <div class="col-12">
                                <div class="card border-0 shadow-sm">
                                    <div class="card-header bg-light">
                                        <h5 class="mb-0"><i class="fas fa-sliders-h me-2 text-primary"></i>Outras Configurações</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row g-3">
                                            <div class="col-md-6">
                                                <label class="form-label fw-bold text-primary mb-2">📏 Largura da Borda</label>
                                                <div class="input-group">
                                                    <span class="input-group-text bg-light"><i class="fas fa-ruler-horizontal text-muted"></i></span>
                                                    <input type="range" class="form-range" name="border_width" value="<?php echo htmlspecialchars($cores['BORDER_WIDTH_DP']); ?>" min="0" max="10" step="1" id="borderWidthRange" oninput="document.getElementById('borderWidthValue').value = this.value">
                                                    <input type="number" class="form-control" id="borderWidthValue" value="<?php echo htmlspecialchars($cores['BORDER_WIDTH_DP']); ?>" min="0" max="10" step="1" oninput="document.getElementById('borderWidthRange').value = this.value">
                                                    <span class="input-group-text bg-light">px</span>
                                                </div>
                                                <small class="form-text text-muted">Espessura da borda em pixels</small>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label class="form-label fw-bold text-primary mb-2">🔵 Raio das Bordas</label>
                                                <div class="input-group">
                                                    <span class="input-group-text bg-light"><i class="fas fa-circle-notch text-muted"></i></span>
                                                    <input type="range" class="form-range" name="corner_radius" value="<?php echo htmlspecialchars($cores['CORNER_RADIUS_DP']); ?>" min="0" max="50" step="1" id="cornerRadiusRange" oninput="document.getElementById('cornerRadiusValue').value = this.value">
                                                    <input type="number" class="form-control" id="cornerRadiusValue" value="<?php echo htmlspecialchars($cores['CORNER_RADIUS_DP']); ?>" min="0" max="50" step="1" oninput="document.getElementById('cornerRadiusRange').value = this.value">
                                                    <span class="input-group-text bg-light">px</span>
                                                </div>
                                                <small class="form-text text-muted">Arredondamento dos cantos</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-between mt-4 pt-3 border-top">
                            <button type="reset" class="btn btn-outline-secondary px-4">
                                <i class="fas fa-undo me-2"></i> Redefinir
                            </button>
                            <button type="submit" class="btn btn-primary px-4">
                                <i class="fas fa-save me-2"></i> Salvar Alterações
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    /* Estilos para a pré-visualização */
    .preview-box {
        background-color: #f8f9fa;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }
    
    .preview-btn {
        transition: all 0.3s ease;
        background: linear-gradient(to bottom, <?php echo $cores['START_COLOR_XML']; ?>, <?php echo $cores['END_COLOR_XML']; ?>);
        border: <?php echo $cores['BORDER_WIDTH_DP']; ?>px solid <?php echo $cores['BORDER_COLOR_NORMAL']; ?>;
        border-radius: <?php echo $cores['CORNER_RADIUS_DP']; ?>px;
        padding: 8px 20px;
        color: #fff;
        text-shadow: 0 1px 1px rgba(0,0,0,0.2);
        min-width: 120px;
    }
    
    .preview-btn.focus {
        border-color: <?php echo $cores['BORDER_COLOR_FOCUS']; ?>;
        box-shadow: 0 0 0 3px rgba(<?php echo hexdec(substr($cores['BORDER_COLOR_FOCUS'], 1, 2)); ?>, 
                            <?php echo hexdec(substr($cores['BORDER_COLOR_FOCUS'], 3, 2)); ?>, 
                            <?php echo hexdec(substr($cores['BORDER_COLOR_FOCUS'], 5, 2)); ?>, 0.2);
    }
    
    /* Animações e efeitos */
    .animate__animated {
        animation-duration: 0.5s;
    }
    
    .card {
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    
    .card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.15);
    }
    
    .form-control:focus, .form-control-color:focus {
        border-color: #86b7fe;
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    }
    
    .bg-gradient-primary-to-secondary {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
    }
    
    /* Toast notification */
    .toast-notification {
        position: fixed;
        bottom: 20px;
        right: 20px;
        min-width: 250px;
        z-index: 1050;
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    
    .toast-notification.show {
        opacity: 1;
    }
</style>

<script>
function setTransparent(id) {
    const colorInput = document.getElementById(id);
    const transparentInput = document.getElementById(id + '_transparent');
    
    colorInput.value = "#000000"; // visual apenas
    transparentInput.value = "1";
    
    // Mostrar notificação
    showToast('Cor transparente aplicada com sucesso!', 'success');
    
    // Atualizar pré-visualização
    updatePreview();
}

function showToast(message, type) {
    const toast = document.createElement('div');
    toast.className = 'toast-notification';
    toast.innerHTML = `
        <div class="toast-body bg-${type} text-white rounded p-3 shadow">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
            ${message}
        </div>
    `;
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('show');
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 3000);
    }, 100);
}

function updatePreview() {
    const startColor = document.getElementById('start_color').value;
    const endColor = document.getElementById('end_color').value;
    const borderColor = document.getElementById('border_color').value;
    const borderFocusColor = document.getElementById('border_color_focus').value;
    const borderWidth = document.querySelector('[name="border_width"]').value;
    const cornerRadius = document.querySelector('[name="corner_radius"]').value;
    
    // Atualizar botões
    const buttons = document.querySelectorAll('.preview-btn');
    buttons.forEach(btn => {
        btn.style.background = `linear-gradient(to bottom, ${startColor}, ${endColor})`;
        btn.style.border = `${borderWidth}px solid ${borderColor}`;
        btn.style.borderRadius = `${cornerRadius}px`;
    });
    
    // Atualizar botão em foco
    const focusButton = document.querySelector('.preview-btn.focus');
    focusButton.style.borderColor = borderFocusColor;
    
    // Calcular cor com opacidade para o box-shadow
    if (borderFocusColor && borderFocusColor !== '#000000') {
        const r = parseInt(borderFocusColor.slice(1, 3), 16);
        const g = parseInt(borderFocusColor.slice(3, 5), 16);
        const b = parseInt(borderFocusColor.slice(5, 7), 16);
        focusButton.style.boxShadow = `0 0 0 3px rgba(${r}, ${g}, ${b}, 0.2)`;
    } else {
        focusButton.style.boxShadow = 'none';
    }
}

// Inicializar a pré-visualização e eventos
document.addEventListener('DOMContentLoaded', function() {
    updatePreview();
    
    // Atualizar quando os valores mudam
    document.getElementById('colorForm').addEventListener('input', function() {
        updatePreview();
    });
    
    // Resetar formulário
    document.querySelector('[type="reset"]').addEventListener('click', function() {
        setTimeout(updatePreview, 100);
    });
});
</script>

<?php include('includes/footer.php'); ?>