<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Fawaz</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            font-family: 'Arial', sans-serif;
            background: linear-gradient(to right, #d4e6f1, #d6eaf8);
            margin: 0;
            padding: 20px;
        }

        h1 {
            color: #fff;
            text-align: center;
            font-size: 26px;
            margin-bottom: 20px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }

        .tabs {
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
        }

        button {
            padding: 10px 20px;
            margin: 5px;
            font-size: 18px;
            color: white;
            background-color: #6a5acd;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.2s;
            width: auto;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        button:hover {
            background-color: red;
            transform: scale(1.05);
        }

        .tab {
            display: none;
            margin-top: 22px;
            background: white;
            border: 2px solid #6a5acd;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .tab.active {
            display: block;
        }

        table {
            width: 100%;
            border: 1px solid #6a5acd;
            font-size: 18px;
            border-collapse: collapse;
            margin-top: 20px;
            display: flex;
            flex-direction: column;
        }

        tr {
            display: flex;
            justify-content: space-between;
        }

        th, td {
            border: 1px solid #6a5acd;
            padding: 0px;
            text-align: center;
            flex: 1;
        }

        th {
            background-color: #6a5acd;
            color: white;
            font-size: 18px;
        }

        td {
            background: linear-gradient(to right, #d4e6f1, #d6eaf8);
            width: 50%;
        }

        input[type="number"], input[type="text"] {
            width: 70%;
            padding: 8px;
            font-size: 15px;
            text-align: center;
            border: 1px solid #6a5acd;
            border-radius: 5px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            background-color: #fff;
            color: #1b4f72;
            font-weight: bold;
            -moz-appearance: textfield;
        }

        input[type="number"]::-webkit-inner-spin-button,
        input[type="number"]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }

        .extra-inputs {
            margin-top: 22px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            align-items: center;
        }

        .extra-inputs label {
            font-size: 22px;
            font-weight: bold;
            color: #1b4f72;
            text-align: center;
        }

        .extra-inputs input {
            border: 1px solid #6a5acd;
            padding: 10px;
            font-size: 18px;
            border-radius: 5px;
            background-color: #fff;
            color: #1b4f72;
        }

        #result {
            font-size: 26px;
            font-weight: bold;
            margin-top: 20px;
            color: blue;
            background: #fff;
            padding: 10px 20px;
            border: 2px solid #6a5acd;
            border-radius: 10px;
            text-align: center;
            align-items: center;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        #currentDate {
            margin-top: 20px;
            font-size: 24px;
            color: black;
            text-align: center;
        }
    </style>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>
</head>

<body>
    <div class="tabs" id="tabs"></div>
 
    <div class="container" style="background-color: #fff">
        <div id="tabContent" style="text-align: center; align-items: center; color: blue; font-weight: bold;font-size: 28px"></div>
        <div id="currentDate"></div>
    </div>
   
    <button id="saveButton" class="buttonBlue">Save as PNG</button>
    <button id="clearButton" style="background-color: red">Clear Data</button>

    <script>
        const tabCount = 20;
        const rows = 10;
        const cols = 10;

        const tabsContainer = document.getElementById("tabs");
        const tabContentContainer = document.getElementById("tabContent");

        for (let i = 1; i <= tabCount; i++) {
            const tabButton = document.createElement("button");
            tabButton.innerText = `Tab ${i}`;
            tabButton.onclick = () => showTab(`tab${i}`);
            tabsContainer.appendChild(tabButton);

            const tabDiv = document.createElement("div");
            tabDiv.id = `tab${i}`;
            tabDiv.classList.add("tab");
            if (i === 1) tabDiv.classList.add("active");

            // Add the heading to the tab
            const tabHeader1 = document.createElement("h1");
            tabHeader1.style.color = "#6a5acd";
            tabHeader1.innerText = "مزارع الحراحشة - الدجنية - المفرق";
            tabDiv.appendChild(tabHeader1);

            // Add the date to the tab
            const dateDiv = document.createElement("div");
            dateDiv.id = `date${i}`;
            dateDiv.style.textAlign = "center";
            tabDiv.appendChild(dateDiv);

            const tabHeader = document.createElement("h2");
            tabHeader.innerText = ` ${i} الفاتورة رقم`;
            tabHeader.style.fontSize = "28px";
            tabHeader.style.color = "#1e90ff";
            tabHeader.style.textAlign = "center";
            tabDiv.appendChild(tabHeader);

            // Add input field for marketer's name
const nameInputDiv = document.createElement("div");
nameInputDiv.style.textAlign = "center";
const nameInput = document.createElement("input");
nameInput.type = "text";
nameInput.id = `nameInput${i}`;
nameInput.placeholder = "اسم المسوق";
nameInput.style.width = "60%";
nameInput.style.padding = "10px 20px";
nameInput.style.fontSize = "28px";
nameInput.style.fontWeight = "bold";
nameInput.style.textAlign = "right";

// Load saved name on page load
const savedName = localStorage.getItem(`nameInput${i}`);
nameInput.value = savedName || '';

// Add event listener to save name to local storage
nameInput.addEventListener("input", function () {
    localStorage.setItem(`nameInput${i}`, this.value);
});

nameInputDiv.appendChild(nameInput);
tabDiv.appendChild(nameInputDiv);

            const table = document.createElement("table");
            for (let r = 1; r <= rows; r++) {
                const tr = document.createElement("tr");
                for (let c = 1; c <= cols; c++) {
                    const td = document.createElement("td");
                    const inputField = document.createElement("input");
                    inputField.type = "number";
                    inputField.style.fontSize = "18px";
                    inputField.id = `dataInput${i}_${r}_${c}`;
                    inputField.dataset.row = r;
                    inputField.dataset.col = c;
                    inputField.dataset.tab = i;

                    // Auto-save data on input
                    inputField.addEventListener("input", () => {
                        saveData(`tab${i}`);
                        calculateSumForCurrentTab();
                    });

                                      // Exit table on blur if input is empty
                    inputField.addEventListener("blur", () => {
                        if (inputField.value.trim() === "") {
                            inputField.value = ""; // Clear the input if it's empty
                            inputField.blur(); // Remove focus from the input
                        } else {
                            const currentRow = parseInt(inputField.dataset.row);
                            const currentCol = parseInt(inputField.dataset.col);
                            const currentTab = parseInt(inputField.dataset.tab);
                            if (currentRow === rows) {
                                const nextCol = currentCol + 1;
                                if (nextCol <= cols) {
                                    document.querySelector(`#dataInput${currentTab}_1_${nextCol}`).focus();
                                }
                            } else {
                                const nextRow = currentRow + 1;
                                document.querySelector(`#dataInput${currentTab}_${nextRow}_${currentCol}`).focus();
                            }
                        }
                    });

                    td.appendChild(inputField);
                    tr.appendChild(td);
                }
                table.appendChild(tr);
            }
            tabDiv.appendChild(table);

            const extraInputs = document.createElement("div");
            extraInputs.classList.add("extra-inputs");

            const labels = ["السعر", "وزن الفارغ", "عدد الفارغ", "المبلغ المدفوع"];

            // Generate input field configurations with consistent keys
            const inputFields = labels.map((label, index) => ({
                key: `field${index}`, // Unique key independent of label text
                label: label,
                type: "number",
                fontSize: "18px"
            }));

            inputFields.forEach(inputField => {
                const labelElement = document.createElement("label");
                labelElement.innerText = inputField.label;
				// Apply red color to "المبلغ المدفوع"
				if (inputField.label === "المبلغ المدفوع") {
					labelElement.style.color = "red";
				}
                const inputElement = document.createElement("input");
                inputElement.type = inputField.type;
                inputElement.style.fontSize = inputField.fontSize;
                inputElement.id = `extraInput${i}_${inputField.key}`; // Use key instead of label for id

                inputElement.addEventListener("input", () => {
                    saveData(`tab${i}`);
                    calculateSumForCurrentTab();
                });

                extraInputs.appendChild(labelElement);
                extraInputs.appendChild(inputElement);
            });

            tabDiv.appendChild(extraInputs);
            tabContentContainer.appendChild(tabDiv);
        }

        // Clear all data function
        function clearTabData() {
            const activeTab = document.querySelector(".tab.active");
            if (!activeTab) {
                alert("No active tab to clear!");
                return;
            }

            // Clear all input fields in the active tab
            const allInputs = activeTab.querySelectorAll("input");
            allInputs.forEach(input => {
                input.value = "";
            });

            // Save the cleared state to local storage
            saveData(activeTab.id);

            // Clear all calculated result fields
            const resultFields = activeTab.querySelectorAll(".result, .calculated-result");
            resultFields.forEach(result => {
                result.textContent = ""; // Clear the content of the result elements
            });

            calculateSumForCurrentTab();
        }

        // Attach clear function to the clear button
        document.getElementById("clearButton").addEventListener("click", clearTabData);

        document.getElementById('saveButton').addEventListener('click', function() {
            const activeTab = document.querySelector('.tab.active');
            if (!activeTab) {
                console.error("No active tab found.");
                return;
            }

            // Capture the active tab
            domtoimage.toPng(activeTab)
                .then(function (dataUrl) {
                    const link = document.createElement('a');
                    const tabNumber = activeTab.id.replace('tab', '');
                    const fileName = `tab${tabNumber}_Report.png`;

                    link.download = fileName;
                    link.href = dataUrl;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                })
                .catch(function (error) {
                    console.error('Oops, something went wrong!', error);
                });
        });

        // Modify the showTab function to save the active tab index
        function showTab(tabId) {
            const tabs = document.querySelectorAll('.tab');
            tabs.forEach(tab => tab.classList.remove('active'));
            const activeTab = document.getElementById(tabId);
            activeTab.classList.add('active');

            // Save the active tab index to local storage
            const tabIndex = tabId.replace('tab', '');
            localStorage.setItem('activeTabIndex', tabIndex);

            // Load data and calculate sums
            loadData(tabId);
            calculateSumForCurrentTab();
        }

        window.onload = function () {
            for (let i = 1; i <= tabCount; i++) {
                // Verify and retrieve data for each tab
                const tabId = `tab${i}`;
                if (document.getElementById(tabId)) {
                    loadData(tabId);
                } else {
                    console.warn(`Tab with ID '${tabId}' not found.`);
                }
            }

            // Show the last active tab or default to tab 1
            const activeTabIndex = localStorage.getItem('activeTabIndex') || 1;
            const activeTabId = `tab${activeTabIndex}`;
            if (document.getElementById(activeTabId)) {
                showTab(activeTabId);
            } else {
                console.warn(`Active tab with ID '${activeTabId}' not found. Defaulting to tab 1.`);
                showTab('tab1');
            }

            // Verify and set the global current date display
            const currentDateElement = document.getElementById("currentDate");
            if (currentDateElement) {
                const currentDate = new Date();
                const day = String(currentDate.getDate()).padStart(2, '0');
                const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                const year = currentDate.getFullYear();
                currentDateElement.innerText = `Today's Date: ${day}/${month}/${year}`;
            } else {
                console.warn("Element with ID 'currentDate' not found.");
            }

            // Set the date for each tab
            setDateInTabs();

            // Calculate and display results for the active tab immediately
            calculateSumForCurrentTab();
        };

        function saveData(tab) {
            const inputs = document.querySelectorAll(`#${tab} input`);
            const data = Array.from(inputs).map(input => input.value);
            localStorage.setItem(`savedData_${tab}`, JSON.stringify(data));
        }

function loadData(tab) {
    const savedData = JSON.parse(localStorage.getItem(`savedData_${tab}`)) || [];
    const inputs = document.querySelectorAll(`#${tab} input`);
    inputs.forEach((input, index) => {
        input.value = savedData[index] || '';
    });

    // Load the saved name from local storage
    const nameInput = document.querySelector(`#${tab} input[type="text"]`);
    if (nameInput) {
        const savedName = localStorage.getItem(`nameInput${tab.slice(3)}`);
        nameInput.value = savedName || '';
    }
}

        function calculateSumForCurrentTab() {
            const activeTab = document.querySelector('.tab.active');
            if (!activeTab) {
                document.getElementById("result").innerText = "No active tab selected.";
                return;
            }

            // Calculate the total sum of input values in the table
            const tableInputs = activeTab.querySelectorAll('table input[type="number"]');
            let totalSum = 0;

            tableInputs.forEach(input => {
                const value = parseFloat(input.value);
                if (!isNaN(value)) {
                    totalSum += value;
                }
            });

            // Dynamically retrieve extra input values based on keys
            const fieldKeys = ["field0", "field1", "field2", "field3"]; // Keys corresponding to Price, Box Weight, and Boxes Number, paid amount
            const fieldValues = {};

            fieldKeys.forEach(key => {
                const input = activeTab.querySelector(`#extraInput${activeTab.id.slice(3)}_${key}`);
                fieldValues[key] = parseFloat(input?.value || 0);
            });

            const { field0: price, field1: boxWeight, field2: boxesNumber, field3: paid } = fieldValues;

            // Perform calculations
            const totalBoxesWeight = boxWeight * boxesNumber;
            const netWeight = totalSum - totalBoxesWeight;
            const netPrice = price * netWeight / 100;
            const netRest = netPrice - paid;

            // Create a results div if it doesn't exist
            let resultsDiv = activeTab.querySelector('.results');
            if (!resultsDiv) {
                resultsDiv = document.createElement('div');
                resultsDiv.classList.add('results');
                activeTab.appendChild(resultsDiv);
            }

            // Update the results div with the calculated values
            resultsDiv.innerHTML = `
                <p>${totalSum.toFixed(1)}    :اجمالي القائم </p>
                <p>${totalBoxesWeight.toFixed(1)}     :اجمالي الفارغ </p>
                <p>${netWeight.toFixed(1)}     :الوزن الصافي</p>
                <p>${netPrice.toFixed(1)}     :المبلغ المطلوب</p>
                <p><span style="color: red;">${netRest.toFixed(1)} :المبلغ المتبقي</span></p>
            `;
        }
 
         // Set the current date in each tab
        function setDateInTabs() {
            const currentDate = new Date();
            const day = String(currentDate.getDate()).padStart(2, '0');
            const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
            const year = currentDate.getFullYear();
            const formattedDate = `${day}/${month}/${year}   :التاريخ`;

            for (let i = 1; i <= tabCount; i++) {
                const dateDiv = document.getElementById(`date${i}`);
                dateDiv.innerText = formattedDate;
            }
        }

        // Call the function to set the date after creating tabs
        setDateInTabs();
    </script>
</body>

</html>