document.addEventListener('DOMContentLoaded', function() {
    fetchData();

    const form = document.getElementById('updateForm');
    form.addEventListener('submit', function(event) {
        event.preventDefault();
        updateMisses();
    });
});


function updateMissedTable(){
    let container = document.getElementById('button-bar-div-9');
    console.log("Container CHECK");
    if(container)
        {
            console.log("Container EXISTS");
            container.innerHTML = '';
            misses();
            checkAndUpdateMisses();
            let contents = createMissesTable();
            container.appendChild(contents);
            addOrUpdateColumn();
        }

}
function createMissesTable() {
    // Create the container div
    const container = document.createElement('div');

    // Create and append the style element
    const style = document.createElement('style');
    style.textContent = `
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
        }
        th, td {
            padding: 10px;
        }
    `;
    container.appendChild(style);
    container.id = 'misses-database-tool';


    let savedColor = localStorage.getItem(container.id+'-containerIdbackgroundColor');
    if (savedColor) {
        container.style.backgroundColor = savedColor;
    }

    let colorChangerQuickSpin = quickSpin_colorChanger(container.id);
    container.append(colorChangerQuickSpin);

    let toggleButton = document.createElement('button');
    toggleButton.style.paddingTop = '10px'; // Adjust padding if needed
    toggleButton.style.backgroundColor = '#d3ffba';
    toggleButton.style.color = 'black';
    toggleButton.style.marginTop = '10px'; // Add margin-top to move the button down
    toggleButton.textContent = 'Show Description';


    container.appendChild(toggleButton);

    // Create and append the h2 element
    const header = document.createElement('h2');
    header.textContent = 'Misses in a Row';
    container.appendChild(header);

    // -----------------------------------------------------------------
    // Start: Description
    // -----------------------------------------------------------------
    // Create the description box
    let itemDiv = document.createElement('div');
    itemDiv.classList.add('wrapped-div');
    let paragraph = document.createElement('p');
    paragraph.textContent = record_miss_description;
    itemDiv.appendChild(paragraph);

    container.appendChild(itemDiv);

    // Add event listener to the button
    toggleButton.addEventListener('click', () => {
        if (itemDiv.style.display === 'none') {
            itemDiv.style.display = 'block';
            toggleButton.textContent = 'Hide Description';
        } else {
            itemDiv.style.display = 'none';
            toggleButton.textContent = 'Show Description';
        }
    });
    // -----------------------------------------------------------------
    // END: Description
    // -----------------------------------------------------------------

    // Create and append the table element
    const table = document.createElement('table');
    table.id = 'missesTable';

    // Create and append the thead element
    const thead = document.createElement('thead');
    const trHead = document.createElement('tr');

    // Create and append th elements to the thead
   // const headers = ['Location', 'Record', 'Session'];
   const headers = ['Location',  'Session'];
    headers.forEach(text => {
        const th = document.createElement('th');
        th.textContent = text;
        trHead.appendChild(th);
    });
    
    thead.appendChild(trHead);
    table.appendChild(thead);

    // Create and append the tbody element
    const tbody = document.createElement('tbody');

    // Assuming variable data is available and formatted as mentioned
/*    const rowsData = [
        ["Evens", db_miss_even, miss_even], 
        ["Dozens", db_miss_dozen, miss_dozen],
        ["Lines", db_miss_line, miss_line],
        ["Quads", db_miss_quad, miss_quad],
        ["Streets", db_miss_street, miss_street],
        ["Splits", db_miss_split, miss_split],
        ["Straights", db_miss_straight, miss_straight]
   ];
 */
const rowsData = [
        ["Evens", miss_even], 
        ["Dozens",  miss_dozen],
        ["Lines",  miss_line],
        ["Quads",  miss_quad],
        ["Streets",  miss_street],
        ["Splits",  miss_split],
        ["Straights",  miss_straight]
   ];

    // Function to populate rows from variable data
    rowsData.forEach(rowData => {
        const row = tbody.insertRow(); // Insert a new row in tbody
        rowData.forEach(data => {
            const cell = row.insertCell(); // Insert a new cell in the row
            cell.textContent = data; // Set text content to data
        });
    });

    table.appendChild(tbody);

    // Append the table to the container
    container.appendChild(table);

    // Return the fully constructed container
    return container;
}


function fetchData() {
    fetch('fetch-miss.php')
    .then(response => response.json())
    .then(data => {
        const table = document.getElementById('missesTable').getElementsByTagName('tbody')[0];
        table.innerHTML = '';
        data.data.forEach(item => {
            let row = table.insertRow();
            let cell1 = row.insertCell(0);
            let cell2 = row.insertCell(1);
            let cell3 = row.insertCell(2);

            cell1.textContent = item.id;
            cell2.textContent = item.location;
            cell3.textContent = item.misses;
        });
    })
    .catch(error => console.error('Error:', error));

}

function updateMisses() {
    // For the html update file.
    const id = document.getElementById('id').value;
    const misses = document.getElementById('misses').value;


    // Assuming a POST method for updating
    fetch('update-misses.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: id, misses: misses })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Refresh the table
            const table = document.getElementById('missesTable').getElementsByTagName('tbody')[0];
            table.innerHTML = ''; // Clear the table
            getMissesHighScores(); // Refetch data
        } else {
            alert('Failed to update: ' + data.error);
        }
    })
    .catch(error => console.error('Error:', error));
}

function updateMissesTableItem(id, misses) {


    fetch('update-misses.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: parseInt(id), misses: parseInt(misses) }) // Ensure integers are sent
    })
    .then(response => response.json())
    .then(data => {

        if (data.success) {
            // Update was successful, do something like refreshing data
         
            getMissesHighScores(); // update db variables
            updateMissedTable();

        } else {
            console.error('Failed to update:', data.error);
        }
    })
    .catch(error => console.error('Error during update:', error));
}

async function getMissesHighScores() {
  try {
    const res = await fetch('fetch-miss.php'); // use the same endpoint as fetchData()
    const payload = await res.json();

    // Support both { data: [...] } and a raw array
    const rows = Array.isArray(payload?.data)
      ? payload.data
      : (Array.isArray(payload) ? payload : []);

    // Make sure global vars exist so comparisons won’t crash
    window.db_miss_even     ??= 0;
    window.db_miss_dozen    ??= 0;
    window.db_miss_line     ??= 0;
    window.db_miss_quad     ??= 0;
    window.db_miss_street   ??= 0;
    window.db_miss_split    ??= 0;
    window.db_miss_straight ??= 0;

    rows.forEach(({ id, misses }) => {
      const n = parseInt(id, 10);
      const v = parseInt(misses, 10);
      switch (n) {
        case 1: db_miss_even     = v; break;
        case 2: db_miss_dozen    = v; break;
        case 3: db_miss_line     = v; break;
        case 4: db_miss_quad     = v; break;
        case 5: db_miss_street   = v; break;
        case 6: db_miss_split    = v; break;
        case 7: db_miss_straight = v; break;
      }
    });
  } catch (err) {
    console.error('Error fetching current misses:', err);
  }
}


function checkAndUpdateMisses() {


    if (miss_even >db_miss_even) {
        db_miss_even = miss_even;
        updateMissesTableItem('1', miss_even.toString());
    }
    if (miss_dozen >db_miss_dozen) {
        db_miss_dozen = miss_dozen;
        updateMissesTableItem('2', miss_dozen.toString());
    }
    if (miss_line >db_miss_line) {
        db_miss_line = miss_line;
        updateMissesTableItem('3', miss_line.toString());
    }
    if (miss_quad >db_miss_quad) {
        db_miss_quad = miss_quad;
        updateMissesTableItem('4', miss_quad.toString());

    }
    if (miss_street >db_miss_street) {
        db_miss_street = miss_street;
        updateMissesTableItem('5', miss_street.toString());

    }
    if (miss_split >db_miss_split) {
        db_miss_split = miss_split;
        updateMissesTableItem('6', miss_split.toString());

    }
    if (miss_straight >db_miss_straight) {
        db_miss_straight = miss_straight;
        updateMissesTableItem('7', miss_straight.toString());
    }

}

function addCurrentSessionColumn()
{
        // Grab the table element
        const table = document.getElementById('missesTable');

        // 1. Add new column header
        const headerRow = table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[0];
        const newHeader = document.createElement('th');
        newHeader.textContent = 'Session'; 
        headerRow.appendChild(newHeader);
}

function addOrUpdateColumn() {
    const table = document.getElementById('missesTable');

    // Check if the additional column already exists
    const headerRow = table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[0];
    const headers = headerRow.getElementsByTagName('th');
    let columnIndex = -1; // Default value if column does not exist

    // Determine if the column already exists and find its index
    for (let i = 0; i < headers.length; i++) {
        if (headers[i].textContent === 'Session') {
            columnIndex = i;
            break;
        }
    }

    // If the column doesn't exist, add it
    if (columnIndex === -1) {
        const newHeader = document.createElement('th');
        newHeader.textContent = 'Session';
        headerRow.appendChild(newHeader);
        columnIndex = headers.length; // New column index will be the last one
    }

    // Update or add data cells in each row of the tbody
    const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    const newData = [miss_even, miss_dozen, miss_line, miss_quad, miss_street, miss_split, miss_straight]; 

    for (let i = 0; i < rows.length; i++) {
        // If the cell doesn't exist (first-time creation), add it
        if (rows[i].cells.length <= columnIndex) {
            const newCell = rows[i].insertCell(-1);
            newCell.textContent = newData[i];
        } else { // Otherwise, update the existing cell
            rows[i].cells[columnIndex].textContent = newData[i];
        }
    }
}
