const API_BASE_URL = './api';

document.addEventListener('DOMContentLoaded', function() {
    if (window.location.pathname.includes('product_entry.html')) {
        checkAuthenticationAndInitializeEntryPage();
    }
});

async function checkAuthenticationAndInitializeEntryPage() {
    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;
        }
        
        // Se autenticado, inicializa a página de entrada
        initializeProductEntryPage();
        
    } catch (error) {
        console.error('Erro ao verificar autenticação:', error);
        window.location.href = 'login.html';
    }
}

function initializeProductEntryPage() {
    const productEntryForm = document.getElementById('product-entry-form');
    const entryDateElement = document.getElementById('entry-date');
    const entryTimeElement = document.getElementById('entry-time');

    // Definir data e hora atuais
    const today = new Date().toISOString().split('T')[0];
    const now = new Date().toTimeString().split(' ')[0].substring(0, 5);

    if (entryDateElement) entryDateElement.value = today;
    if (entryTimeElement) entryTimeElement.value = now;

    if (productEntryForm) {
        productEntryForm.addEventListener('submit', handleProductEntrySubmit);
    }

    loadRecentEntries();
    loadSystemLogo(); // Carregar a logo na página de entrada
}

async function handleProductEntrySubmit(event) {
    event.preventDefault();

    const productName = document.getElementById('product-name').value;
    const quantity = document.getElementById('quantity').value;
    const entryDate = document.getElementById('entry-date').value;
    const entryTime = document.getElementById('entry-time').value;

    if (!productName || !quantity || !entryDate || !entryTime) {
        showMessage('Por favor, preencha todos os campos.', 'error');
        return;
    }

    const formData = new FormData();
    formData.append('product_name', productName);
    formData.append('quantity', quantity);
    formData.append('entry_date', entryDate);
    formData.append('entry_time', entryTime);

    try {
        const response = await fetch(`${API_BASE_URL}/product_entries.php`, {
            method: 'POST',
            body: formData,
            credentials: 'include'
        });

        const result = await response.json();

        if (response.ok && result.success) {
            showMessage(result.message, 'success');
            document.getElementById('product-entry-form').reset();
            loadRecentEntries();
        } else {
            showMessage(result.error || 'Erro ao registar entrada.', 'error');
        }
    } catch (error) {
        console.error('Erro ao registar entrada:', error);
        showMessage('Erro de conexão ao registar entrada.', 'error');
    }
}

async function loadRecentEntries() {
    try {
        const response = await fetch(`${API_BASE_URL}/product_entries.php`, {
            credentials: 'include'
        });
        const result = await response.json();

        const entriesList = document.getElementById('entries-list');
        entriesList.innerHTML = ''; // Limpar lista

        if (result.success && result.entries.length > 0) {
            result.entries.forEach(entry => {
                const entryItem = document.createElement('div');
                entryItem.className = 'exit-item'; // Reutilizar estilo
                entryItem.innerHTML = `
                    <div class="item-header">
                        <span>${entry.product_name}</span>
                        <span class="quantity">${entry.quantity}</span>
                    </div>
                    <div class="item-details">
                        <span>${formatDate(entry.entry_date + ' ' + entry.entry_time)}</span>
                    </div>
                `;
                entriesList.appendChild(entryItem);
            });
        } else {
            entriesList.innerHTML = '<p>Nenhuma entrada recente encontrada.</p>';
        }
    } catch (error) {
        console.error('Erro ao carregar entradas recentes:', error);
        showMessage('Erro ao carregar entradas recentes.', 'error');
    }
}

// Função utilitária para formatar data (reutilizada de script.js ou admin.js)
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'
    });
}

// Função para carregar logo do sistema (reutilizada de script.js)
async function loadSystemLogo() {
    try {
        const response = await fetch(`${API_BASE_URL}/logo.php`, {
            credentials: 'include'
        });
        
        const result = await response.json();
        const logoContainer = document.getElementById('logo-container');
        
        if (result.success && result.exists && result.logo_url) {
            logoContainer.innerHTML = `
                <img src="${result.logo_url}?t=${Date.now()}" alt="Logo do Sistema" style="max-height: 80px; max-width: 250px; margin-bottom: 10px;">
            `;
        } else {
            logoContainer.innerHTML = '';
        }
    } catch (error) {
        console.error('Erro ao carregar logo do sistema:', error);
        const logoContainer = document.getElementById('logo-container');
        if (logoContainer) {
            logoContainer.innerHTML = '';
        }
    }
}

// Função para exibir mensagens (reutilizada de script.js ou admin.js)
function showMessage(message, type = 'info') {
    const messageModal = document.getElementById('message-modal');
    const modalMessage = document.getElementById('modal-message');
    const closeModal = messageModal.querySelector('.close');

    modalMessage.textContent = message;
    messageModal.style.display = 'block';

    if (type === 'success') {
        modalMessage.style.color = '#27ae60';
    } else if (type === 'error') {
        modalMessage.style.color = '#e74c3c';
    } else {
        modalMessage.style.color = '#3498db';
    }

    closeModal.onclick = function() {
        messageModal.style.display = 'none';
    }

    window.onclick = function(event) {
        if (event.target == messageModal) {
            messageModal.style.display = 'none';
        }
    }
}


