// Content-Type: application/javascript
// Define variables
let eventType, buffet, bar, danceFloor, stage, cocktailTables, djTable, cakeTable, sweetheartTable, giftTable, weatherConsiderations;
let dimensions = {
    // Default dimensions (in square feet) (test dimensions) (include buffer for walkways)
    buffet: 100,
    bar: 50,
    danceFloor: 225, // 15x15
    stage: 150, //15x10
    cocktailTable: 16, // per table no chairs
    djTable: 40,
    cakeTable: 30,
    sweetheartTable: 25,
    giftTable: 20,
    seatingTable: 55, //seatingtable is an 8' rectangle with 10 chairs.
    chair: 5, // found a person in a chair is usually 2'3" x 2'3"
};
// Get form elements by id
const numberOfGuests = document.getElementById("guests");
const eventTypeInput = document.getElementById("eventType");
const TableSizeInput = document.getElementById("table_sizes");
const weatherConsiderationsInput = document.getElementById("weather-considerations");
const selectElement = document.getElementById("<?php echo $this->get_field_id('items'); ?>");


function extractAreaValues() {
    if (selectElement) {
        const options = selectElement.options;
        for (let i = 0; i < options.length; i++) {
            const optionsValue = options[i].value;
            const splitValue = optionsValue.split('-');
            if (splitValue.length > 1) {
                const areaValue = splitValue[1];
                console.log(areaValue);
            }
        }
    }
}


// Function to handle the navigation between steps
function nextStep(step){



    // Add conditional input field for tables or chairs

    if (step === 3) {
        var numberOfGuests = document.getElementById("numberOfGuests");
        if (numberOfGuests.value === '' || numberOfGuests.value < 1) {
            alert("Please enter the number of guests.");
            return;
        }
        addConditionalInput();
    }
    var conditionalInput;
    if (step === 4) {
        var eventType = document.getElementById("eventType");
        if (eventType.value === "Default") {
            alert("Please choose an event type.");
            return; // Stop here and don't proceed to next step
        }
        if (eventType.value === "cocktail") {
            conditionalInput = document.getElementById("numCocktailTables");
        }
        else if (eventType.value === "ceremony") {
            conditionalInput = document.getElementById("numberChairs");
        }
        else if (eventType.value === "Dinner") {
            conditionalInput = document.getElementById("numTables");
        }
        else if (eventType.value === "standing") {
            // Standing events don't require additional input, so skip validation
            conditionalInput = null;
        }
        if (conditionalInput && (conditionalInput.value === '' || conditionalInput.value < 1)) {
            alert("Please enter a valid number.");
            return; // Stop here and don't proceed to next step
        }
    }





    let steps= document.getElementsByClassName("steps");
    for (let i = 0; i < steps.length; i++) {
        steps[i].style.display="none";
    }
    let targetStepElement = document.getElementById("step_" + step);
    if (targetStepElement){
        targetStepElement.style.display = "block";
        if (step >=2) {
            document.getElementById('progressTracker').style.display = 'flex';
            updateProgressTracker(step - 1);
        } else {
            document.getElementById('progressTracker').style.display = 'none'; // Hide progress tracker
        }
    } else {
        nextStep(step + 1);
    }

}
function showSelectedOptions() {
    $('#checkboxDiv').html(''); // Clear the checkboxDiv area first
    $('#myDropdown :selected').each(function(i, selected) {
        // For each selected option, create a corresponding checkbox
        $('#checkboxDiv').append(
            '<label><input type="checkbox" value="' + $(selected).val() + '" checked>' + $(selected).text() + '</label><br>'
        );
    });
}
function updateProgressTracker(step) {
    // Reset all steps
    for (let i = 1; i <= 6; i++) { // Assuming 3 steps, adjust as needed
        document.getElementById(`stepProgress${i}`).classList.remove('active');
        document.getElementById(`stepProgress${i}`).classList.remove('completed');
    }

    // Set previous steps as completed
    for (let i = 1; i < step; i++) {
        document.getElementById(`stepProgress${i}`).classList.add('completed');
    }

    // Set current step as active
    document.getElementById(`stepProgress${step}`).classList.add('active');
}

// Function to dynamically add an input for tables or chairs based on the event type
function addConditionalInput() {
    const eventType = document.getElementById("eventType").value;
    const step4 = document.getElementById("step_3");

    // Clear previous conditional input if any
    const oldConditionalInput = document.getElementById("conditionalInput");
    if (oldConditionalInput) {
        oldConditionalInput.remove();
    }

    // Create a new div to hold the conditional input
    const conditionalInput = document.createElement("div");
    conditionalInput.id = "conditionalInput";

    // Create label and input based on eventType
    let label = document.createElement("label");
    let input = document.createElement("input");
    input.type = "number";
    input.min = "1";

    if (eventType === "cocktail") {
        label.innerHTML = "Tall tables with no chairs<br>Enter the number of cocktail tables:";
        input.id = "numCocktailTables";
        input.name = "numCocktailTables";
    } else if (eventType === "ceremony") {
        label.innerHTML = "Chairs arranged in rows <br>Enter number of chairs for Ceremony seating:";
        input.id = "numberChairs";
        input.name = "numChairs";
    } else if (eventType === "Dinner") {
        // First ask for number of table size
        const tableSizeQuestion = document.createElement("div");
        tableSizeQuestion.id = "tableSizeQuestion";
        let tableSizeDropdownHTML = '<label for="tableSize">Select table size: </label><select id="tableSize"><option value="">Please Select</option>';
        // Dynamically add options based on tableOptions
        for (const [size, area] of Object.entries(table_Sizes)) {
            tableSizeDropdownHTML += `<option value="${size}">${size} (${area} sq ft)</option>`;
        }
        tableSizeDropdownHTML += '</select>';
        tableSizeQuestion.innerHTML = tableSizeDropdownHTML;
        conditionalInput.appendChild(tableSizeQuestion);
        step4.appendChild(conditionalInput);


        document.getElementById("tableSize").addEventListener("change", function() {
            addNumberOfTablesInput(this.value);
        })
    }else {
        return; // Do not add any conditional input for other event types
    }

    // Append elements to div for cocktail and ceremony types
    if (eventType === "cocktail" || eventType === "ceremony") {
        conditionalInput.appendChild(label);
        conditionalInput.appendChild(document.createElement("br"));
        conditionalInput.appendChild(input);
    }
    if (eventType !== "Dinner") {
        step4.appendChild(conditionalInput);
    }
}
function resetCalculator() {
    // Reset form values
    document.getElementById("guest-form").reset();

    // Hide all steps except the first one
    let steps = document.getElementsByClassName("steps");
    for (let i = 0; i < steps.length; i++) {
        steps[i].style.display = "none";
    }
    document.getElementById("step_1").style.display = "block";
    document.getElementById('progressTracker').style.display = 'none';
    // Hide the result display
    document.getElementById("resultDisplay").style.display = "none";
    updateProgressTracker(1);
}

function addNumberOfTablesInput(tableSize) {
    const conditionalInput = document.getElementById("conditionalInput");
    const oldNumberOfTablesInput = document.getElementById("numberOfTablesInput");
    if (oldNumberOfTablesInput) {
        oldNumberOfTablesInput.remove();
    }

    const numberOfTablesDiv = document.createElement("div");
    numberOfTablesDiv.id = "numberOfTablesInput";

    const label = document.createElement("label");
    label.innerHTML = `Enter the number of ${tableSize} tables:`;
    const input = document.createElement("input");
    input.type = "number";
    input.min = "1";
    input.id = "numTables";
    input.name = "numTables";
    console.log("Input for 'numTables' created with ID:", input.id);

    numberOfTablesDiv.appendChild(label);
    numberOfTablesDiv.appendChild(document.createElement("br"));
    numberOfTablesDiv.appendChild(input);

    conditionalInput.appendChild(numberOfTablesDiv);
}
function addCocktailTableInput() {
    const isChecked = document.getElementById("cocktailTables").checked;
    const step4 = document.getElementById("step_4");

    // Remove the existing cocktail tables input if present
    const oldInput = document.getElementById("cocktailTablesInput");
    if (oldInput) {
        oldInput.remove();
    }

    if (isChecked) {
        // Create a new div to hold the input for the number of cocktail tables
        const cocktailTablesInput = document.createElement("div");
        cocktailTablesInput.id = "cocktailTablesInput";

        // Create a label and input field
        let label = document.createElement("label");
        label.innerText = "Enter the number of cocktail tables:";

        let input = document.createElement("input");
        input.type = "number";
        input.min = "1";
        input.id = "numCocktailTablesInput";
        input.name = "numCocktailTablesInput";

        // Append elements to div
        cocktailTablesInput.appendChild(label);
        cocktailTablesInput.appendChild(document.createElement("br"));
        cocktailTablesInput.appendChild(input);

        // Append the new input div to step 4
        step4.appendChild(cocktailTablesInput);
    }
}



// Function to calculate tent size
function CalculateButton() {
    // You can call as many functions as you want here
    var emailValid = verifyEmail();  // assuming verifyEmail returns true if the email is valid

    if(emailValid){
        calculateTentSize();
        if (TentSubmitURL) {
            jQuery.ajax({
                url : TentSubmitURL,
                data : {email : document.getElementById("userEmail").value}
            })
        };
    }
}
function verifyEmail() {
    var email = document.getElementById("userEmail").value;
    var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Simple regex to validate email
    if (email.length < 1 || !regex.test(email)) {
        alert("Please enter a valid email address.");
        return false; // Invalid email
    } else {
        return true; // Valid email
    }
}


function calculateTentSize() {
    // Get input values
    let totalArea = 0;
    let totalTableArea = 0;
    let numGuestsElement = document.getElementById("numberOfGuests");
    let numGuests = numGuestsElement ? parseInt(numGuestsElement.value) : 0;
    const checkboxes = document.querySelectorAll('input[type="checkbox"][id^="item_"]');

    if (isNaN(numGuests)) {
        alert("Please enter a valid number for the number of guests.");
        return; // Stop execution if input is not a number
    }
    eventType = document.getElementById("eventType").value;
    weatherConsiderationsElement = document.getElementById("weatherConsiderations");
    weatherConsiderations = weatherConsiderationsElement ? weatherConsiderationsElement.checked : false;
    AdditionalItems = document.querySelectorAll('.item-checkbox');
    let cocktailTables = parseInt(document.getElementById("eventType").value) || 0;
    checkboxes.forEach(function(AdditionalItems) {
        console.log(AdditionalItems.id + ' is ' + (AdditionalItems.checked ? 'checked' : 'not checked'));
        if(AdditionalItems.checked) {
            let area = AdditionalItems.id.split('-')[1];  // Split the id string by '-' and take the second part
            if(area) {  // Check if area exists to avoid adding undefined or NaN
                totalArea += parseInt(area);  // Parse area to integer and add to totalArea
            }
        }
    });
    let tentPrices = {
        "10x10": 50, // $50 per hour
        "10x20": 70, // $70 per hour
        "20x20": 100, // $100 per hour
        "20x30": 130, // $130 per hour
        "30x30": 160, // $160 per hour
    };

    let sidewallPrice = 10; // $10 per hour/day

    // Adding the area occupied by guests (assuming, 10 square feet per guest)
    totalArea += numGuests * 8;

    let includedItems = [];
    let numChairs = 0;  // Initialize to zero

    // Adding area based on different elements

    
    //console.log(totalArea)
    if (buffet) {
        totalArea += dimensions.buffet;
        includedItems.push("Buffet");
    }
    if (bar) {
        totalArea += dimensions.bar;
        includedItems.push("Bar");
    }
    if (danceFloor) {
        totalArea += dimensions.danceFloor;
        includedItems.push("Dance Floor");
    }
    if (stage) {
        totalArea += dimensions.stage;
        includedItems.push("Stage");
    }
    if (djTable) {
        totalArea += dimensions.djTable;
        includedItems.push("DJ Table");
    }
    if (cakeTable) {
        totalArea += dimensions.cakeTable;
        includedItems.push("Cake Table");
    }
    if (sweetheartTable) {
        totalArea += dimensions.sweetheartTable;
        includedItems.push("Sweetheart Table");
    }
    if (giftTable) {
        totalArea += dimensions.giftTable;
        includedItems.push("Gift Table");
    }

    // Adding area for cocktail tables, ceremony chairs or dinner tables
    // depending on the eventType
    if (eventType === 'cocktail') {
        totalArea += cocktailTables * dimensions.cocktailTable;
        includedItems.push("Cocktail Tables");
    } else if (eventType === 'ceremony') {
        // Assuming 'numChairs' exists or defaulting to 0
        numChairs = parseInt(document.getElementById("numberChairs").value || "0");
        totalArea += numChairs * dimensions.chair;
        includedItems.push("Ceremony Chairs");
    } else if (eventType === 'Dinner') {
        //Does not properly get the total table size correct
        const tableSizeDropdown = document.getElementById("tableSize");
        const numSeatingTablesElement = document.getElementById("numTables");


        if (tableSizeDropdown && numSeatingTablesElement) {
            const selectedTableSize = tableSizeDropdown.value; // Get selected table size (e.g., "6x2.5")
            console.log("Selected Table Size:", selectedTableSize);
            const numSeatingTables = parseInt(numSeatingTablesElement.value || "0"); // Get the number of seating tables
            console.log("Number of Seating Tables:", numSeatingTables);


            // Get the area for the selected table size from `table_Sizes` object
            const tableArea = table_Sizes[selectedTableSize]; // Ensure `table_Sizes` is correctly populated and available
            console.log("Area per Table:", tableArea);

            if (tableArea && !isNaN(numSeatingTables)) {
                // Calculate total area needed for the seating tables
                totalArea += numSeatingTables * tableArea;
                includedItems.push("Seating Tables (" + selectedTableSize + ")");
                totalTableArea = numSeatingTables * tableArea;

                // Debugging output to console
                console.log("Selected Table Size:", selectedTableSize);
                console.log("Number of Seating Tables:", numSeatingTables);
                console.log("Area per Table:", tableArea);
                console.log("Total Table Area for 'Dinner':", totalTableArea);
            }
        }

        // Assuming 'numSeatingTables' exists or defaulting to 0
        //let numSeatingTables = parseInt(document.getElementById("numSeatingTables").value || "0");
        //totalArea += numSeatingTables * dimensions.seatingTable;
        //includedItems.push("Seating Tables");
    }

    // Determine the tent size based on the total required area
    if (typeof tent_sizes === 'undefined') {
        console.error("tent_sizes is not defined!");
        return;
    }
    const sortedTents = Object.entries(tent_sizes).sort((a, b) => parseInt(a[1]) - parseInt(b[1]));
    console.log("Sorted tents from smallest to largest:", sortedTents);  // Debugging line

    let tentSize = "Not available";
    let largestTentSize = sortedTents[0][0];
    let largestTentArea = sortedTents[0][1];
    let requiredArea = totalArea;
    let extraSpaceNeeded = requiredArea - largestTentArea;

    for (let [size, area] of sortedTents) {
        console.log(`Checking tent size: ${size} with area: ${area} against required area: ${requiredArea}`);  // Debugging line

        if (area >= requiredArea) {
            tentSize = size;
            extraSpace = area - requiredArea;
            break;
        }
    }
    console.log(`Selected tent size: ${tentSize}`);  // Debugging line








    //debugger;






    let durationType = document.getElementById("duration-type").value;


    let dayMultiplier = 1; // This can be adjusted based on business logic. E.g., if 1 day's rent is not equal to 24 hours' rent.

    if (durationType === "days") {
        dayMultiplier = 24; // Assuming 24 hours in a day. This can be adjusted based on discounts or business rules.
    }



    if (weatherConsiderations) {
        includedItems.push("Sidewalls");
    }

    // Display result

    let resultText = `Event Type: ${eventType}\n`;

    if (tentSize === "Not available") {
        let largestTentSize = sortedTents[sortedTents.length - 1][0];
        let largestTentArea = sortedTents[sortedTents.length - 1][1];
        let extraSpaceNeeded = requiredArea - largestTentArea;
        resultText += `The largest available tent size is ${largestTentSize} with an area of ${largestTentArea} sq ft. You will need an extra space of ${extraSpaceNeeded} sq ft.`;
    } else {
        resultText += `Recommended tent size: ${tentSize}`;
        if (extraSpace > 0) {
            resultText += `\nExtra space in the tent: ${extraSpace} sq ft`;
        }
    }

    if (numChairs > 0) {
        resultText += `\nNumber of chairs: ${numChairs}`;
    }

    /*if (includedItems.length > 0) {
        resultText += `\nIncluded items: ${includedItems.join(", ")}`;
    }*/

    document.getElementById("resultDisplay").innerText = resultText;
    document.getElementById("resultDisplay").style.display = "block";
}