// Configuração da API
const API_BASE_URL = './api';

// Estado global
let currentUser = null;
let products = [];
let users = [];

// Inicialização
document.addEventListener('DOMContentLoaded', function() {
    // Verificar se estamos na página de administração
    if (window.location.pathname.includes('admin.html')) {
        checkAuthentication();
        setupEventListeners();
    } else {
        // Se estivermos na página principal, apenas configurar o logout
        setupMainPageEventListeners();
    }
});

// Event listeners para a página principal
function setupMainPageEventListeners() {
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', logout);
    }
}

// Event listeners para a página de administração
function setupEventListeners() {
    const userForm = document.getElementById('user-form');
    const productForm = document.getElementById('product-form');
    const stockReturnForm = document.getElementById('stock-return-form');
    const logoUploadForm = document.getElementById('logo-upload-form');
    
    if (userForm) userForm.addEventListener('submit', handleAddUser);
    if (productForm) productForm.addEventListener('submit', handleProductSubmit);
    if (stockReturnForm) stockReturnForm.addEventListener('submit', handleStockReturn);
    if (logoUploadForm) logoUploadForm.addEventListener('submit', handleLogoUpload);
}

// Verificar autenticação
async function checkAuthentication() {
    try {
        const response = await fetch(`${API_BASE_URL}/auth.php?action=check`, {
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (!result.authenticated) {
            window.location.href = 'login.html';
            return;
        }
        
        if (result.user.role !== 'admin') {
            alert('Acesso negado. Apenas administradores podem aceder a esta página.');
            window.location.href = 'index.html';
            return;
        }
        
        currentUser = result.user;
        const usernameElement = document.getElementById('username');
        if (usernameElement) {
            usernameElement.textContent = currentUser.username;
        }
        
        // Carregar dados iniciais
        loadUsers();
        loadProducts();
        
    } catch (error) {
        console.error('Erro ao verificar autenticação:', error);
        window.location.href = 'login.html';
    }
}

// Logout
async function logout() {
    try {
        await fetch(`${API_BASE_URL}/auth.php?action=logout`, {
            method: 'POST',
            credentials: 'include'
        });
        
        window.location.href = 'login.html';
    } catch (error) {
        console.error('Erro ao fazer logout:', error);
        window.location.href = 'login.html';
    }
}

// Navegação entre tabs
function showTab(tabName) {
    // Remover classe active de todas as tabs
    document.querySelectorAll('.nav-tab').forEach(tab => tab.classList.remove('active'));
    document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
    
    if (tabName === 'main') {
        window.location.href = 'index.html';
        return;
    }
    
    // Ativar tab selecionada
    if (event && event.target) {
        event.target.classList.add('active');
    }
    const tabContent = document.getElementById(`${tabName}-tab`);
    if (tabContent) {
        tabContent.classList.add('active');
    }
    
    // Recarregar dados se necessário
    if (tabName === 'users') {
        loadUsers();
    } else if (tabName === 'products') {
        loadProducts();
    } else if (tabName === 'stock') {
        loadProducts();
        loadStockData();
    }
}

// ========== GESTÃO DE UTILIZADORES ==========

async function loadUsers() {
    try {
        const response = await fetch(`${API_BASE_URL}/users.php`, {
            credentials: 'include'
        });
        
        if (!response.ok) {
            throw new Error('Erro ao carregar utilizadores');
        }
        
        users = await response.json();
        displayUsers();
        
    } catch (error) {
        console.error('Erro ao carregar utilizadores:', error);
        showMessage('Erro ao carregar utilizadores: ' + error.message, 'error');
    }
}

function displayUsers() {
    const tbody = document.getElementById('users-tbody');
    if (!tbody) return;
    
    if (users.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center;">Nenhum utilizador encontrado</td></tr>';
        return;
    }
    
    tbody.innerHTML = users.map(user => `
        <tr>
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td><span class="stock-badge ${getRoleBadgeClass(user.role)}">${getRoleDisplayName(user.role)}</span></td>
            <td>${formatDate(user.created_at)}</td>
            <td>
                ${user.id !== currentUser.id ? `<button class="btn btn-danger" onclick="deleteUser(${user.id})">Remover</button>` : '<span style="color: #7f8c8d;">Utilizador atual</span>'}
            </td>
        </tr>
    `).join('');
}

function getRoleBadgeClass(role) {
    switch (role) {
        case 'admin': return 'stock-high';
        case 'cozinha': return 'stock-medium';
        case 'lanchonete': return 'stock-low';
        default: return '';
    }
}

function getRoleDisplayName(role) {
    switch (role) {
        case 'admin': return 'Administrador';
        case 'cozinha': return 'Cozinha';
        case 'lanchonete': return 'Lanchonete';
        default: return role;
    }
}

async function handleAddUser(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const userData = {
        username: formData.get('username'),
        password: formData.get('password'),
        role: formData.get('role')
    };
    
    try {
        const response = await fetch(`${API_BASE_URL}/users.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify(userData)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showMessage('Utilizador adicionado com sucesso!', 'success');
            event.target.reset();
            loadUsers();
        } else {
            showMessage('Erro: ' + result.error, 'error');
        }
        
    } catch (error) {
        showMessage('Erro de conexão: ' + error.message, 'error');
    }
}

async function deleteUser(userId) {
    if (!confirm('Tem certeza que deseja remover este utilizador?')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/users.php?id=${userId}`, {
            method: 'DELETE',
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showMessage('Utilizador removido com sucesso!', 'success');
            loadUsers();
        } else {
            showMessage('Erro: ' + result.error, 'error');
        }
        
    } catch (error) {
        showMessage('Erro de conexão: ' + error.message, 'error');
    }
}

// ========== GESTÃO DE PRODUTOS ==========

async function loadProducts() {
    try {
        const response = await fetch(`${API_BASE_URL}/products.php`, {
            credentials: 'include'
        });
        
        if (!response.ok) {
            throw new Error('Erro ao carregar produtos');
        }
        
        products = await response.json();
        displayProducts();
        updateProductSelects();
        
    } catch (error) {
        console.error('Erro ao carregar produtos:', error);
        showMessage('Erro ao carregar produtos: ' + error.message, 'error');
    }
}

function displayProducts() {
    const tbody = document.getElementById('products-tbody');
    if (!tbody) return;
    
    if (products.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center;">Nenhum produto encontrado</td></tr>';
        return;
    }
    
    tbody.innerHTML = products.map(product => `
        <tr>
            <td>${product.id}</td>
            <td>${product.name}</td>
            <td>
                <div class="stock-info">
                    ${product.stock}
                    <span class="stock-badge ${getStockBadgeClass(product.stock)}">${getStockStatus(product.stock)}</span>
                </div>
            </td>
            <td>${formatDate(product.updated_at)}</td>
            <td>
                <button class="btn btn-primary" onclick="editProduct(${product.id})">Editar</button>
                <button class="btn btn-danger" onclick="deleteProduct(${product.id})">Remover</button>
            </td>
        </tr>
    `).join('');
}

function getStockBadgeClass(stock) {
    if (stock <= 5) return 'stock-low';
    if (stock <= 20) return 'stock-medium';
    return 'stock-high';
}

function getStockStatus(stock) {
    if (stock <= 5) return 'Baixo';
    if (stock <= 20) return 'Médio';
    return 'Alto';
}

function updateProductSelects() {
    const select = document.getElementById('return-product');
    if (!select) return;
    
    select.innerHTML = '<option value="">Selecione um produto...</option>' +
        products.map(product => `<option value="${product.id}">${product.name} (Stock: ${product.stock})</option>`).join('');
}

async function handleProductSubmit(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const productData = {
        name: formData.get('name'),
        stock: parseInt(formData.get('stock'))
    };
    
    const productId = formData.get('id');
    const isEdit = productId && productId !== '';
    
    try {
        const url = isEdit ? `${API_BASE_URL}/products.php?id=${productId}` : `${API_BASE_URL}/products.php`;
        const method = isEdit ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify(productData)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showMessage(`Produto ${isEdit ? 'atualizado' : 'adicionado'} com sucesso!`, 'success');
            event.target.reset();
            cancelProductEdit();
            loadProducts();
        } else {
            showMessage('Erro: ' + result.error, 'error');
        }
        
    } catch (error) {
        showMessage('Erro de conexão: ' + error.message, 'error');
    }
}

function editProduct(productId) {
    const product = products.find(p => p.id === productId);
    if (!product) return;
    
    const productIdField = document.getElementById('product-id');
    const productNameField = document.getElementById('product-name');
    const productStockField = document.getElementById('product-stock');
    const formTitle = document.getElementById('product-form-title');
    const submitBtn = document.getElementById('product-submit-btn');
    const cancelBtn = document.getElementById('product-cancel-btn');
    
    if (productIdField) productIdField.value = product.id;
    if (productNameField) productNameField.value = product.name;
    if (productStockField) productStockField.value = product.stock;
    if (formTitle) formTitle.textContent = 'Editar Produto';
    if (submitBtn) submitBtn.textContent = 'Atualizar Produto';
    if (cancelBtn) cancelBtn.style.display = 'inline-block';
}

function cancelProductEdit() {
    const form = document.getElementById('product-form');
    const productIdField = document.getElementById('product-id');
    const formTitle = document.getElementById('product-form-title');
    const submitBtn = document.getElementById('product-submit-btn');
    const cancelBtn = document.getElementById('product-cancel-btn');
    
    if (form) form.reset();
    if (productIdField) productIdField.value = '';
    if (formTitle) formTitle.textContent = 'Adicionar Novo Produto';
    if (submitBtn) submitBtn.textContent = 'Adicionar Produto';
    if (cancelBtn) cancelBtn.style.display = 'none';
}

async function deleteProduct(productId) {
    if (!confirm('Tem certeza que deseja remover este produto?')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/products.php?id=${productId}`, {
            method: 'DELETE',
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showMessage('Produto removido com sucesso!', 'success');
            loadProducts();
        } else {
            showMessage('Erro: ' + result.error, 'error');
        }
        
    } catch (error) {
        showMessage('Erro de conexão: ' + error.message, 'error');
    }
}

// ========== GESTÃO DE STOCK ==========

function loadStockData() {
    const tbody = document.getElementById('stock-tbody');
    if (!tbody) return;
    
    if (products.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center;">Nenhum produto encontrado</td></tr>';
        return;
    }
    
    tbody.innerHTML = products.map(product => `
        <tr>
            <td>${product.name}</td>
            <td>${product.stock}</td>
            <td><span class="stock-badge ${getStockBadgeClass(product.stock)}">${getStockStatus(product.stock)}</span></td>
            <td>
                <button class="btn btn-success" onclick="quickReturn(${product.id})">Retorno Rápido</button>
            </td>
        </tr>
    `).join('');
}

async function handleStockReturn(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const returnData = {
        product_id: parseInt(formData.get('product_id')),
        quantity: parseInt(formData.get('quantity')),
        reason: formData.get('reason') || 'Retorno manual'
    };
    
    try {
        const response = await fetch(`${API_BASE_URL}/stock.php?action=return`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify(returnData)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showMessage(result.message, 'success');
            event.target.reset();
            loadProducts();
            loadStockData();
        } else {
            showMessage('Erro: ' + result.error, 'error');
        }
        
    } catch (error) {
        showMessage('Erro de conexão: ' + error.message, 'error');
    }
}

function quickReturn(productId) {
    const quantity = prompt('Quantidade a retornar ao stock:');
    if (!quantity || isNaN(quantity) || parseInt(quantity) <= 0) {
        return;
    }
    
    const reason = prompt('Motivo (opcional):') || 'Retorno rápido';
    
    const returnData = {
        product_id: productId,
        quantity: parseInt(quantity),
        reason: reason
    };
    
    fetch(`${API_BASE_URL}/stock.php?action=return`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify(returnData)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showMessage(result.message, 'success');
            loadProducts();
            loadStockData();
        } else {
            showMessage('Erro: ' + result.error, 'error');
        }
    })
    .catch(error => {
        showMessage('Erro de conexão: ' + error.message, 'error');
    });
}

// ========== FUNÇÕES UTILITÁRIAS ==========

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('pt-PT', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function showMessage(message, type = 'info') {
    // Criar elemento de mensagem temporária
    const messageDiv = document.createElement('div');
    messageDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 1rem 1.5rem;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        z-index: 1000;
        max-width: 400px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    `;
    
    if (type === 'success') {
        messageDiv.style.background = '#27ae60';
    } else if (type === 'error') {
        messageDiv.style.background = '#e74c3c';
    } else {
        messageDiv.style.background = '#3498db';
    }
    
    messageDiv.textContent = message;
    document.body.appendChild(messageDiv);
    
    // Remover após 5 segundos
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.parentNode.removeChild(messageDiv);
        }
    }, 5000);
}




// ========== FUNÇÕES DE GESTÃO DE LOGO ==========

// Carregar configurações (incluindo logo)
async function loadSettings() {
    await loadCurrentLogo();
}

// Carregar logo atual
async function loadCurrentLogo() {
    try {
        const response = await fetch(`${API_BASE_URL}/logo.php`, {
            credentials: 'include'
        });
        
        const result = await response.json();
        const currentLogoDiv = document.getElementById('current-logo');
        
        if (result.success && result.exists && result.logo_url) {
            currentLogoDiv.innerHTML = `
                <div style="margin-bottom: 1rem;">
                    <img src="${result.logo_url}?t=${Date.now()}" alt="Logo Atual" style="max-height: 100px; max-width: 300px; border: 2px solid #ddd; border-radius: 8px;">
                </div>
                <p style="color: #666; margin: 0;">Logo atual do sistema</p>
            `;
        } else {
            currentLogoDiv.innerHTML = `
                <div style="padding: 2rem; color: #666; border: 2px dashed #ddd; border-radius: 8px;">
                    <p style="margin: 0; font-size: 1.1rem;">📷</p>
                    <p style="margin: 0.5rem 0 0 0;">Nenhuma logo configurada</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('Erro ao carregar logo atual:', error);
        showMessage('Erro ao carregar logo atual', 'error');
    }
}

// Fazer upload de nova logo
async function handleLogoUpload(event) {
    event.preventDefault();
    
    const fileInput = document.getElementById('logo-file');
    const file = fileInput.files[0];
    
    if (!file) {
        showMessage('Por favor, selecione um arquivo de imagem', 'error');
        return;
    }
    
    // Validar tipo de arquivo
    const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'];
    if (!allowedTypes.includes(file.type)) {
        showMessage('Tipo de arquivo não permitido. Use PNG, JPG, JPEG ou GIF.', 'error');
        return;
    }
    
    // Validar tamanho (2MB máximo)
    if (file.size > 2 * 1024 * 1024) {
        showMessage('Arquivo muito grande. Tamanho máximo: 2MB.', 'error');
        return;
    }
    
    const formData = new FormData();
    formData.append('logo', file);
    
    try {
        const submitButton = event.target.querySelector('button[type="submit"]');
        submitButton.disabled = true;
        submitButton.textContent = 'Enviando...';
        
        const response = await fetch(`${API_BASE_URL}/logo.php`, {
            method: 'POST',
            body: formData,
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (response.ok && result.success) {
            showMessage(result.message, 'success');
            fileInput.value = ''; // Limpar input
            await loadCurrentLogo(); // Recarregar preview
        } else {
            showMessage(result.error || 'Erro ao fazer upload da logo', 'error');
        }
    } catch (error) {
        console.error('Erro ao fazer upload da logo:', error);
        showMessage('Erro de conexão ao fazer upload da logo', 'error');
    } finally {
        const submitButton = event.target.querySelector('button[type="submit"]');
        submitButton.disabled = false;
        submitButton.textContent = 'Atualizar Logo';
    }
}

// Remover logo
async function removeLogo() {
    if (!confirm('Tem certeza de que deseja remover a logo atual?')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/logo.php`, {
            method: 'DELETE',
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (response.ok && result.success) {
            showMessage(result.message, 'success');
            await loadCurrentLogo(); // Recarregar preview
        } else {
            showMessage(result.error || 'Erro ao remover logo', 'error');
        }
    } catch (error) {
        console.error('Erro ao remover logo:', error);
        showMessage('Erro de conexão ao remover logo', 'error');
    }
}

// Atualizar função showTab para incluir settings
function showTab(tabName) {
    // Esconder todas as tabs
    const tabs = document.querySelectorAll('.tab-content');
    tabs.forEach(tab => tab.classList.remove('active'));
    
    // Remover classe active de todos os botões
    const tabButtons = document.querySelectorAll('.nav-tab');
    tabButtons.forEach(btn => btn.classList.remove('active'));
    
    // Mostrar tab selecionada
    const selectedTab = document.getElementById(`${tabName}-tab`);
    if (selectedTab) {
        selectedTab.classList.add('active');
    }
    
    // Ativar botão correspondente
    const selectedButton = document.querySelector(`[onclick="showTab('${tabName}')"]`);
    if (selectedButton) {
        selectedButton.classList.add('active');
    }
    
    // Carregar dados específicos da tab
    switch(tabName) {
        case 'users':
            loadUsers();
            break;
        case 'products':
            loadProducts();
            break;
        case 'entries':
            loadEntries();
            break;
        case 'stock':
            loadStock();
            break;
        case 'settings':
            loadSettings();
            break;
        case 'main':
            window.location.href = 'index.html';
            break;
    }
}


// ========== FUNÇÕES DE GESTÃO DE ENTRADAS ==========

// Carregar entradas de produtos
async function loadEntries() {
    try {
        const response = await fetch(`${API_BASE_URL}/product_entries.php`, {
            credentials: 'include'
        });
        
        const result = await response.json();
        const entriesTbody = document.getElementById('entries-tbody');
        
        if (result.success && result.entries.length > 0) {
            entriesTbody.innerHTML = result.entries.map(entry => `
                <tr>
                    <td>${entry.product_name}</td>
                    <td style="font-weight: bold; color: #27ae60;">${entry.quantity}</td>
                    <td>${formatDate(entry.entry_date)}</td>
                    <td>${entry.entry_time}</td>
                    <td>Utilizador ${entry.user_id}</td>
                </tr>
            `).join('');
            
            // Carregar estatísticas
            loadEntriesStats(result.entries);
        } else {
            entriesTbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #666;">Nenhuma entrada encontrada</td></tr>';
        }
    } catch (error) {
        console.error('Erro ao carregar entradas:', error);
        showMessage('Erro ao carregar entradas', 'error');
    }
}

// Carregar estatísticas de entradas
function loadEntriesStats(entries) {
    const statsContainer = document.getElementById('entries-stats');
    
    // Calcular estatísticas
    const totalEntries = entries.length;
    const totalQuantity = entries.reduce((sum, entry) => sum + parseInt(entry.quantity), 0);
    const uniqueProducts = new Set(entries.map(entry => entry.product_name)).size;
    
    // Produto mais recebido
    const productCounts = {};
    entries.forEach(entry => {
        productCounts[entry.product_name] = (productCounts[entry.product_name] || 0) + parseInt(entry.quantity);
    });
    
    const mostReceivedProduct = Object.keys(productCounts).reduce((a, b) => 
        productCounts[a] > productCounts[b] ? a : b, Object.keys(productCounts)[0] || 'N/A'
    );
    
    statsContainer.innerHTML = `
        <div style="background: #e8f5e8; padding: 1rem; border-radius: 8px; border-left: 4px solid #27ae60;">
            <h4 style="margin: 0 0 0.5rem 0; color: #27ae60;">Total de Entradas</h4>
            <p style="margin: 0; font-size: 1.5rem; font-weight: bold;">${totalEntries}</p>
        </div>
        
        <div style="background: #e3f2fd; padding: 1rem; border-radius: 8px; border-left: 4px solid #2196f3;">
            <h4 style="margin: 0 0 0.5rem 0; color: #2196f3;">Quantidade Total</h4>
            <p style="margin: 0; font-size: 1.5rem; font-weight: bold;">${totalQuantity}</p>
        </div>
        
        <div style="background: #fff3e0; padding: 1rem; border-radius: 8px; border-left: 4px solid #ff9800;">
            <h4 style="margin: 0 0 0.5rem 0; color: #ff9800;">Produtos Únicos</h4>
            <p style="margin: 0; font-size: 1.5rem; font-weight: bold;">${uniqueProducts}</p>
        </div>
        
        <div style="background: #f3e5f5; padding: 1rem; border-radius: 8px; border-left: 4px solid #9c27b0;">
            <h4 style="margin: 0 0 0.5rem 0; color: #9c27b0;">Mais Recebido</h4>
            <p style="margin: 0; font-size: 1rem; font-weight: bold;">${mostReceivedProduct}</p>
            <small style="color: #666;">${productCounts[mostReceivedProduct] || 0} unidades</small>
        </div>
    `;
}

