function getUrlParameter( name ) {
	name = name.replace( /[\[]/, "\\[" ).replace( /[\]]/, "\\]" );
	var regex = new RegExp( "[\\?&]" + name + "=([^&#]*)" );
	var results = regex.exec(location.search);
	return results === null ? "" : decodeURIComponent( results[1].replace( /\+/g, " " ) );
}

function logoutSuperUser() {
    var currentPage = window.location.href.replace( /#Modal/g, "" );

    $.ajax( {
        type: "POST",
        url: "logout_superUser.php", 
        data: { currentPage: currentPage },
        dataType: "json",
        success: function( response ) {
            window.location.replace( response.redirect );
        },
        error: function( xhr, status, error ) {
            console.error( "AJAX Error: " + status + error );
        }
    } );
}

function calculateSum( inputs ) {
	const numericInputs = inputs.map( ( input ) => parseFloat( input ) || 0 );
	const sum = numericInputs.reduce( ( acc, val ) => acc + val, 0 );

	return sum;
}

function calculateDiff( inputs ) {
	const numericInputs = inputs.map( ( input ) => parseFloat( input ) || 0 );
	const diff = numericInputs.reduce( ( acc, val ) => acc - val, 0 );

	return diff;
}

document.addEventListener( "DOMContentLoaded", function() {
    var spinner = document.getElementById( "spinner" );
    if ( spinner ) {
        spinner.style.display = "block";
    }
    var tables = document.querySelectorAll( "table" );
    tables.forEach( function( table ) {
        table.style.display = "none";
    } );
} );

window.addEventListener( "load", function() {
    var spinner = document.getElementById( "spinner" );
    if ( spinner ) {
        spinner.style.display = "none";
    }
    var tables = document.querySelectorAll( "table" );
    tables.forEach( function( table ) {
        table.style.display = "table";
    } );
} );

function matchNavbarWidth() {
	var tableWidth = $( "table" ).outerWidth();
	var navbarWidth = $( ".navbar" ).outerWidth();
	
	if (tableWidth > navbarWidth) {
		$( ".navbar") .css( "width", tableWidth + "px" );
	} else {
		$( ".navbar" ).css( "width", "100%" );
	}
}

// START Controller BldgNo
function showInput( input ) {
	const amountInput = input.nextElementSibling;
	const textarea = document.getElementById( "hiddenTextarea" );

	if ( input.value ) {
		amountInput.classList.remove( "hidden" );
		textarea.classList.remove( "hidden" );
	} else {
		amountInput.classList.add( "hidden" );
		textarea.classList.add( "hidden" );
	}
}

function updateTextarea() {
    const itemInputs = document.querySelectorAll( ".itemInput" );
    const amountInputs = document.querySelectorAll( ".amountInput" );
    const switchInputs = document.querySelectorAll( ".BldgNoSwitch" );
    const textarea = document.getElementById( "hiddenTextarea" );

    let values = [];
    itemInputs.forEach( ( itemInput, index ) => {
        if ( itemInput.value && amountInputs[index].value ) {
            const switchValue = $( switchInputs[index] ).is( ":checked" ) ? "1" : "0";
            values.push( `${itemInput.value}[${amountInputs[index].value}]{${switchValue}}` );
        }
    } );

    textarea.value = values.join( "," );
}

function addInput() {
	const inputContainer = document.getElementById( "inputContainer" );
	const newInputGroup = document.createElement( "div" );
	newInputGroup.classList.add( "input-group", "input-group-sm", "mb-1" );

	newInputGroup.innerHTML = 
	'<div class="form-check form-switch"><input class="form-check-input BldgNoSwitch" type="checkbox" id="flexSwitchCheckDefault" checked onchange="updateTextarea()"></div><input class="form-control itemInput" list="items" name="item" id="item" placeholder="e.g LB-B10, LB-B11" oninput="updateTextarea()">' +
	'<input type="text" class="form-control amountInput" placeholder="Enter the balance..." oninput="updateTextarea()">' +
	'<button type="button" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" onclick="addInput()"><i class="lni lni-plus"></i></button>' +
	'<button type="button" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" onclick="removeInput()"><i class="lni lni-minus"></i></button>'

	inputContainer.appendChild( newInputGroup );
}

function removeInput() {
	const inputContainer = document.getElementById( "inputContainer" );
	const inputGroups = inputContainer.getElementsByClassName( "input-group" );

	if ( inputGroups.length > 1 ) {
		inputContainer.removeChild( inputGroups[inputGroups.length - 1] );
		updateTextarea();
	}
}

function populateInputsFromTextarea() {
    const textarea = document.getElementById( "hiddenTextarea" );
    const inputContainer = document.getElementById( "inputContainer" );
    const values = textarea.value.split( "," );

    if ( !textarea.value.trim() ) {
        return;
    }

    inputContainer.innerHTML = "";

    values.forEach(value => {
        const [itemPart, amountPart] = value.split( "[" );
        const [amount, switchPart] = amountPart.split( "]" );
        const switchValue = switchPart.replace( "{", "" ).replace( "}", "" ).trim();
        const checked = ( switchValue === "1" ) ? "checked" : "";

        const newInputGroup = document.createElement( "div" );
        newInputGroup.classList.add( "input-group", "input-group-sm", "mb-1" );

        newInputGroup.innerHTML = 
            `<div class="form-check form-switch"><input class="form-check-input BldgNoSwitch" type="checkbox" id="flexSwitchCheckDefault" ${checked} onchange="updateTextarea()"></div>` +
            `<input class="form-control itemInput" list="items" name="item" id="item" placeholder="e.g LB-B10, LB-B11" value="${itemPart}" oninput="updateTextarea()">` +
            `<input type="text" class="form-control amountInput" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off" placeholder="Enter the balance..." value="${amount}" oninput="updateTextarea()">` +
            `<button type="button" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" onclick="addInput()" title="Add"><i class="lni lni-plus"></i></button>` +
            `<button type="button" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" onclick="removeInput()" title="Delete"><i class="lni lni-minus"></i></button>`

        inputContainer.appendChild( newInputGroup );
    } );
}
// END Controller BldgNo

$( document ).ready( function () {
    const $inputElements = $( "input[type='text'], textarea, .itemInput" ).not( "#loginForm input, #regForm input, #cpForm input, #plForm input, textarea[name='pl_other_charges_remark'], #message" );

    $inputElements.on( "input", function () {
        const inputValue = $( this ).val();
        const uppercaseValue = inputValue.toUpperCase();
        $( this ).val( uppercaseValue );
    } );
	
	$( window ).resize( function() {
        matchNavbarWidth();
    } );	
} );

$( window ).on( "load", function() {
    matchNavbarWidth();
} );

// Form Validation
( function () {
'use strict';

var forms = document.querySelectorAll( ".needs-validation" );

Array.prototype.slice.call( forms )
	.forEach( function ( form ) {
		form.addEventListener( "submit", function ( event ) {
			if ( form.checkValidity() === false ) {
				event.preventDefault();
				event.stopPropagation();
			}

			form.classList.add( "was-validated" );
		}, false );
	} );
} )();

// Debounce function
function debounce( fn, delay ) {
    let timeoutID;
    return function() {
        if ( timeoutID ) {
            clearTimeout( timeoutID );
        }
        timeoutID = setTimeout( () => {
            fn.apply( this, arguments );
        }, delay );
    };
}