jQuery(document).ready( function($) {

	// Add placeholder on search
	const searchInput = $('#easyfua-search-input');
	const params      = new URLSearchParams( window.location.search );
	if ( searchInput.length ) {
		if ( params.get('sub') === 'view-files' ) {
			searchInput.attr('placeholder', 'Enter ID or filename');
		} else {
			searchInput.attr('placeholder', 'Enter Submission ID');
		}
	}

	// Folder Name
	$('#easyfua-folder-name').on('input', function() {
		const val = $(this).val().trim() === '' ? 'easy-file-upload-approval' : $(this).val();
        $('#easyfua-folder-name-text').text( val );
    });

	// Login Required + Roles
	$('#easyfua-login-req').on('change', function(){
		if ( $(this).is(':checked') ) {
            $('#easyfua-roles').prop('disabled', false );
        } else {
            $('#easyfua-roles').prop('disabled', true);
        }
	});

	

	// Dialog for rejection
	let fileData = [];

    // Open modal for single reject
    $(document).on('click', '.easyfua-reject-btn', function(e) {
        e.preventDefault();

		// Setup file id and filename.
        const files = {
			id      : $(this).data('id'),
			filename: $(this).data('name')
		}

		// Toggle modal.
        easyfuaModal( [files] );
    });

    // Open modal for bulk reject
    $(document).on('click', '#doaction', function(e) {

		// if it's not reject file then return.
		if ( $('#bulk-action-selector-top').val() !== 'reject' ) {
			return true;
		}

		e.preventDefault();

		// Get checked files (id, filename).
      	const files = $('input[name="id[]"]:checked').map(function() {
			const $row = $(this).closest('tr');
			return {
				id: $(this).val(),
				filename: $row.find('.column-file_name span').text().trim()
			}
		}).get();

		// Toggle modal.
        easyfuaModal( files );
    });

    // Open modal and generate input fields dynamically
    function easyfuaModal( files ) {

        fileData       = files;
        let fieldsHtml = '';

		// Append label and text field.
        if ( files.length === 1 ) {
            fieldsHtml = `<label>File #${files[0].id} - Note for "${files[0].filename}"</label><textarea name="easyfua-note_${files[0].id}" rows="3"></textarea>`;
        } else {
            files.forEach(file => {
                fieldsHtml += `<label>File #${file.id} - Note for "${file.filename}"</label><textarea name="easyfua-note_${file.id}" rows="3"></textarea>`;
            });
        }

        $('#easyfua-reject-fields').html( fieldsHtml );
        $('#easyfua-reject-modal').dialog({
            modal: true,
            width: 450
        });
    }

	// Submit modal form
	$('#easyfua-reject-form').on('submit', function(e) {
		e.preventDefault();
		const notes  = {};
		const button = $('button', $(this) );
		const form   = $('#easyfua-reject-form');

		fileData.forEach(file => {
			const note = $(`textarea[name="easyfua-note_${file.id}"]`);
			notes[file.id] = note.val().trim();
        });

		if ( !notes ) return;

		// Disabled button
		button.prop('disabled', true);

		// Make an ajax request.
		$.post( easyfua.ajax_url, {
            action: 'easyfua_reject_files',
            notes,
            _ajax_nonce: easyfua.nonce,
			_referer: $('input[name="_wp_http_referer"]').val().trim()
        }, function(response) {
			button.prop('disabled', false);
            if ( response.success ) {
				form[0].reset();
				location.href = response.data;
            } else {
                alert( response.data || 'Error occurred' );
            }
        });
	});

	// Delete modal confirmation
	$('.easyfua-action-delete').on('click', function(e){
		e.preventDefault();
		const url   = $(this).attr('href');
		const title = $(this).data('title');
		if ( confirm('Are you sure you want to delete this '+ title +'?') ) {
			window.location.href = url;
		}
	});
});