const products = [
            { description: "Cables de coche", rateFactor: 0.4 },
            { description: "Cables domésticos de Cu 36%", rateFactor: 0.75*0.36 },
            { description: "Cables domésticos de Cu 37%", rateFactor: 0.75*0.37 },
            { description: "Cables domésticos de Cu 38%", rateFactor: 0.75*0.38 },
            { description: "Cables domésticos de Cu 39%", rateFactor: 0.75*0.39 },
            { description: "Cables domésticos de Cu 40%", rateFactor: 0.75*0.40 },
            { description: "Cables domésticos de Cu 41%", rateFactor: 0.75*0.41 },
            { description: "Cables domésticos de Cu 42%", rateFactor: 0.75*0.42 },
            { description: "Cables individuales de Cu 56%", rateFactor: 0.80*0.56 },
            { description: "Cables individuales de Cu 57%", rateFactor: 0.80*0.57 },
            { description: "Cables individuales de Cu 58%", rateFactor: 0.80*0.58 },
            { description: "Cables individuales de Cu 59%", rateFactor: 0.80*0.59 },
            { description: "Cables individuales de Cu 60%", rateFactor: 0.80*0.60 },
            { description: "Cables individuales de Cu 61%", rateFactor: 0.80*0.61 },
            { description: "Cables individuales de Cu 62%", rateFactor: 0.80*0.62 },
            // Добавьте остальные продукты здесь
        ];

document.addEventListener('DOMContentLoaded', function() {
    initializeTable();
    updatePrices();
});

function initializeTable() {
    var tbody = document.querySelector('.table-container table tbody');
    products.forEach((product, index) => {
        var tr = document.createElement('tr');
        tr.innerHTML = `<td>${product.description}</td>
                        <td><input type="number" class="input-small" id="quantity-${index}" value="0" onchange="recalculate(${index})"></td>
                        <td id="price-${index}">-</td>
                        <td id="sum-${index}">-</td>`;
        tbody.appendChild(tr);
    });
}

function recalculate(productIndex) {
    var quantity = parseFloat(document.getElementById('quantity-' + productIndex).value);
    var price = calculatePrice(productIndex, quantity);
    document.getElementById('price-' + productIndex).textContent = price.toFixed(2);
    var sum = quantity * price;
    document.getElementById('sum-' + productIndex).textContent = sum.toFixed(2);
    updateTotalSum();
}

function calculatePrice(productIndex, quantity) {
   var rate = getCurrencyRate();
    return rate * products[productIndex].rateFactor;
}

function getCurrencyRate() {
   return parseFloat(document.getElementById('currency-rate').value);
}

function updateTotalSum() {
   var totalSum = 0;
    for (var i = 0; i < products.length; i++) {
        var sum = parseFloat(document.getElementById('sum-' + i).textContent);
        if (!isNaN(sum)) {
            totalSum += sum;
        }
    }
    document.getElementById('total-sum').textContent = totalSum.toFixed(2);
    document.getElementById('total-sum2').textContent = totalSum.toFixed(2);
}

function updatePrices() {
   for (var i = 0; i < products.length; i++) {
        recalculate(i);
    }
}

function printTable() {
    const selectedProducts = collectTableData();
    sendDataToServer(selectedProducts);
}

function collectTableData() {
    const productsData = [];
    document.querySelectorAll('.table-container table tbody tr').forEach(row => {
        const quantity = parseInt(row.querySelector('input[type="number"]').value);
        if (quantity > 0) {
            const description = row.cells[0].textContent.trim();
            const pricePerUnit = parseFloat(row.cells[2].textContent);
            const total = parseFloat(row.cells[3].textContent);
            productsData.push({ description, quantity, pricePerUnit, total });
        }
    });
    return productsData;
}

function sendDataToServer(data) {
    fetch('sendDataToServer.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ products: data })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Сетевая ошибка при отправке данных');
        }
        return response.json();
    })
    .then(result => {
        console.log('Данные успешно отправлены:', result);
        openPrintWindow(); // Открытие окна печати после успешной отправки данных
    })
    .catch(error => {
        console.error('Ошибка при отправке данных:', error);
    });
}

function openPrintWindow() {
    var printWindow = window.open('', '', 'height=600,width=800');
    printWindow.document.write('<html><head><title>Печать</title></head><body>');

    // Клонирование и обработка таблицы для печати
    var table = document.querySelector('.table-container table').cloneNode(true);
    Array.from(table.querySelectorAll('tbody tr')).forEach(row => {
        var quantity = parseInt(row.querySelector('input[type="number"]').value);
        if (quantity <= 0) {
            row.remove();
        }
    });

    printWindow.document.body.appendChild(table);

    // Добавление итоговой суммы
    var totalSum = document.querySelector('#total-sum').textContent;
    var totalSumPara = printWindow.document.createElement('p');
   
    printWindow.document.body.appendChild(totalSumPara);

    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.focus();

    // Печать и закрытие окна после небольшой задержки
    setTimeout(() => {
        printWindow.print();
        printWindow.close();
    }, 500);
}
