jQuery(document).ready(function($) {
    
    // Function to get current day name
    function getCurrentDayName() {
        return new Date().toLocaleString('en-US', { weekday: 'long' });
    }

    // Function to get current UTC datetime plus minutes
    function getCurrentUTCDateTimePlusMinutes(minutes) {
        let date = new Date();
        date.setMinutes(date.getMinutes() + minutes);
        return date.toISOString().slice(0, 16); // Get the format 'YYYY-MM-DDTHH:MM'
    }

    // Populate default values for day name, start event, and stop event
    $('#day_name').val(getCurrentDayName());
    //$('#start_event').val(getCurrentUTCDateTimePlusMinutes(0));
    //$('#stop_event').val(getCurrentUTCDateTimePlusMinutes(3));

    // Fetch columns based on the selected table
    $('#table_select').on('change', function() {
        let selectedTable = $(this).val();
        if (selectedTable) {
            $.ajax({
                url: ajax_object.ajax_url,
                method: 'POST',
                data: {
                    action: 'fetch_columns',
                    table: selectedTable
                },
                success: function(response) {
                    let columns = JSON.parse(response);
                    $('#column_select').empty();
                    columns.forEach(function(column) {
                        $('#column_select').append(`<option value="${column}">${column}</option>`);
                    });
                }
            });
        } else {
            $('#column_select').empty();
        }
    });

    // Fetch search results based on the selected columns
    $('#fetch_button').on('click', function() {
        let searchTerm = $('#search_term').val();
        let selectedTable = $('#table_select').val();
        let selectedColumns = $('#column_select').val();

        if (searchTerm.length >= 3 && selectedTable && selectedColumns.length > 0) {
            $.ajax({
                url: ajax_object.ajax_url,
                method: 'POST',
                data: {
                    action: 'perform_search',
                    search_term: searchTerm,
                    table: selectedTable,
                    columns: selectedColumns
                },
                success: function(response) {
                    let results = JSON.parse(response);
                    console.log(results);
                    $('#results_dropdown').empty();
                    results.forEach(function(result) {
                        $('#results_dropdown').append(`<option value="${result.channel_id}">${result.extinf} - ${result.event_description} - ${result.channel_id}</option>`);
                    });
                }
            });
        } else {
            alert('Please fill out the search term, select a table, and select at least one column.');
        }
    });

    // Submit form data
     $('#submit_button').on('click', function(event) {
        // Prevent the default form submission
        event.preventDefault();

        // Clear all previous error messages
        $('.error-message').remove();

        let selectedTable = $('#table_select').val();
        let channelId = $('#channel_id').val();
        let endpointUrl = $('#endpoint_select').val();
        let dayName = $('#day_name').val();
        let m3u8_hostname_link = $('#m3u8_hostname_link').val();
        let credentialsType = $('#credentials_select').val();
        let eventPeriodicTimes = {};
        let credentials = {};
        let eventDetails = {};
        let eventTimes = {};
        let isValid = true;

        // Function to display error messages
        function showError(element, message) {
            $('<span class="error-message" style="color: red;">' + message + '</span>').insertAfter(element);
        }

        // Validate selectedTable
        if (!selectedTable) {
            showError('#table_select', 'Please select a table.');
            isValid = false;
        }

        // Validate channelId
        if (!channelId) {
            showError('#channel_id', 'Please enter a channel ID.');
            isValid = false;
        }

        // Validate endpointUrl
        if (!endpointUrl) {
            showError('#endpoint_select', 'Please select an endpoint URL.');
            isValid = false;
        }

        // Validate dayName
        if (!dayName) {
            showError('#day_name', 'Please enter a day name.');
            isValid = false;
        }

        // Validate credentialsType
        if (!credentialsType) {
            showError('#credentials_select', 'Please select a credentials type.');
            isValid = false;
        }
    

        if (isValid) {
            let data = {
                action: 'submit_form',
                table: selectedTable,
                channel_id: channelId,
                endpoint_url: endpointUrl,
                day_name: dayName,
                m3u8_hostname_link: m3u8_hostname_link,
                event_times: eventTimes,
                event_periodic_times : eventPeriodicTimes,
                credentials_type: credentialsType,
                credentials: credentials,
                event_details: eventDetails
            };

            $('#results_dropdown option:selected').each(function() {
                let channel_id = $(this).val();
                eventDetails[channel_id] = {
                    title: $(`#event_title_${channel_id}`).val(),
                    description: $(`#event_description_${channel_id}`).val()
                };
            });
            
            $('#results_dropdown option:selected').each(function() {
                let channel_id = $(this).val();
                eventPeriodicTimes[channel_id] = {
                                daily_schedulation: false,
                                periodtype: 'weeks',
                                periodvalue: 1
                            };
                eventPeriodicTimes[channel_id] = {
                    daily_schedulation: $(`#daily_schedulation_${channel_id}`).is(':checked') ? 1 : 0,
                    periodtype: $(`#periodtype_${channel_id}`).val(),
                    periodvalue: $(`#periodvalue_${channel_id}`).val()
                };
            });
            
            $('#results_dropdown option:selected').each(function() {
                let channel_id = $(this).val();
                eventTimes[channel_id] = {
                    startdatetime: $(`#event_start_time_${channel_id}`).val(),
                    stopdatetime: $(`#event_stop_time_${channel_id}`).val()
                };
            });

            if (credentialsType === 'your_own') {
                $('#results_dropdown option:selected').each(function() {
                    let channel_id = $(this).val();
                    let username = $(`#username_${channel_id}`).val();
                    let password = $(`#password_${channel_id}`).val();
                    credentials[channel_id] = {
                        username: username,
                        password: password
                    };
                });
            }
            
            $.ajax({
                url: ajax_object.ajax_url,
                method: 'POST',
                data: data,
                success: function(response) {
                    $('#response_message').remove();
                    console.log(response);
                    response = JSON.parse(response);
                    console.log(response);
                    let alertType = 'success';
                    let messageContent = '';

                    if (response.status === 'error' || response.status === 'errors') {
                        alertType = 'danger';
                        messageContent = response.message || response.error || 'An error occurred check server side or logs';
                    } else {
                        messageContent = response.message || 'Operation successful';
                    }

                    let message = '<div id="response_message" class="alert alert-' + alertType + '" role="alert">' + messageContent + '</div>';
                    $('#submit_button').after(message);
                },
                error: function(response) {
                    $('#response_message').remove();
                    let message = '<div id="response_message" class="alert alert-danger" role="alert">Error: ' + response.responseText + '</div>';
                    $('#submit_button').after(message);
                }
            });
        } else {
            alert('Please complete the form before submitting.');
        }
    });


    // Update channel IDs field based on selected results
    $('#results_dropdown').on('change', function() {
        let selectedValues = $(this).val();
        //let selectedText = $('#results_dropdown option:selected').text();
        $('#channel_id').val(selectedValues.join(','));

        if (selectedValues.length > 0) {
            $('#event_title_description_fields').empty();
            selectedValues.forEach(function(channel_id) {
                let selectedOption = $(`#results_dropdown option[value="${channel_id}"]`);
                let selectedText = selectedOption.text();
                let eventTitle = $(`#results_dropdown option[value="${channel_id}"]`).data('event-title') || '';
                let eventDescription = $(`#results_dropdown option[value="${channel_id}"]`).data('event-description') || '';
                $('#event_title_description_fields').append(`
                    <div class="form-group">
                        <label for="event_title_${channel_id}"><strong>Event Title for : Channel ID ${channel_id} / ${selectedText}</strong></label>
                        <input type="text" id="event_title_${channel_id}" class="form-control" value="${eventTitle}">
                    </div>
                    <div class="form-group">
                        <label for="event_description_${channel_id}"><strong>Event Description : for Channel ID ${channel_id} / ${selectedText}</strong></label>
                        <textarea id="event_description_${channel_id}" class="form-control" rows="3">${eventDescription}</textarea>
                    </div>
                `);
            });
            $('#event_title_description_fields').show();
        } else {
            $('#event_title_description_fields').hide();
            alert('Please select at least one channel ID.');
        }
    });
    
    
     // Handle change event on start and stop date time fields
    $('#results_dropdown').on('change', function() {
        let selectedValues = $(this).val();
        //let selectedText = $('#results_dropdown option:selected').text();
        $('#channel_id').val(selectedValues.join(','));

        if (selectedValues.length > 0) {
            $('#event_start_stop_fields').empty();
            selectedValues.forEach(function(channel_id) {
                let selectedOption = $(`#results_dropdown option[value="${channel_id}"]`);
                let selectedText = selectedOption.text();
                let startDateTime = $(`#results_dropdown option[value="${channel_id}"]`).data('event-start-time') || '';
                let stopDateTime = $(`#results_dropdown option[value="${channel_id}"]`).data('event-stop-time') || '';
                $('#event_start_stop_fields').append(`
                    <div class="form-group">
                <label for="event_start_time_${channel_id}"><strong>Start time for :</strong> Channel ID ${channel_id} / ${selectedText}</label>
                 <input type="datetime-local" id="event_start_time_${channel_id}" class="form-control" value="${startDateTime}">
                    </div>
                    <div class="form-group">
                        <label for="event_stop_time_${channel_id}"><strong>Stop time for:</strong> Channel ID ${channel_id} / ${selectedText}</label>
                        <input type="datetime-local" id="event_stop_time_${channel_id}" class="form-control" value="${stopDateTime}">
                    </div>

                `);
            });
            $('#event_start_stop_fields').show();
        } else {
            $('#event_start_stop_fields').hide();
            alert('Please select at least one channel ID.');
        }
    });
    
    //handle change event on periodic time
    
    $('#results_dropdown').on('change', function() {
        let selectedValues = $(this).val();
        let selectedText = $('#results_dropdown option:selected').text();
        $('#channel_id').val(selectedValues.join(','));

         if (selectedValues.length > 0) {
                    $('#event_periodic_times_fields').empty();
                    selectedValues.forEach(function(channel_id) {
                        let selectedOption = $(`#results_dropdown option[value="${channel_id}"]`);
                        let selectedText = selectedOption.text()
                        let daily_schedulation = false
                        let periodtype = 'weeks'
                        let periodvalue = 1
                        
                        $('#event_periodic_times_fields').append(`
                            <div class="form-group">
                                <label for="daily_schedulation_${channel_id}">Daily Schedulation for: Channel ID ${channel_id} / ${selectedText}:</label>
                                <input type="checkbox" id="daily_schedulation_${channel_id}" ${daily_schedulation ? 'checked' : ''}>
                            </div>
                            <h2>Select Period</h2>
                            <div class="form-group">
                                <label for="periodtype_${channel_id}">Period Type for: Channel ID ${channel_id} / ${selectedText}:</label>
                                <select id="periodtype_${channel_id}" name="periodtype_${channel_id}" required>
                                    <option value="weeks" ${periodtype === 'weeks' ? 'selected' : ''}>Weeks</option>
                                    <option value="months" ${periodtype === 'months' ? 'selected' : ''}>Months</option>
                                </select>
                                <br><br>
                                <label for="periodvalue_${channel_id}">Period Value for: Channel ID ${channel_id} / ${selectedText}:</label>
                                <input type="number" id="periodvalue_${channel_id}" name="periodvalue_${channel_id}" min="1" value="${periodvalue}" required>
                            </div>
                        `);
                    });
                    
                    // Save the form data to eventPeriodicTimes on change
                    /*
                    $('#event_periodic_times_fields').find('input, select').on('change', function() {
                        let channel_id = $(this).attr('id').split('_').pop();
                        eventPeriodicTimes[channel_id] = {
                            daily_schedulation: $(`#daily_schedulation_${channel_id}`).is(':checked'),
                            periodtype: $(`#periodtype_${channel_id}`).val(),
                            periodvalue: $(`#periodvalue_${channel_id}`).val()
                        };
                    });*/
                    $('#event_periodic_times_fields').show();
                } else {
                    $('#event_periodic_times_fields').hide();
                    alert('Please select at least one channel ID.');
                }
    });

    // Handle change event on credentials select
    $('#credentials_select').on('change', function() {
        if ($(this).val() === 'your_own') {
            let selectedChannelIds = $('#results_dropdown').val();
            if (selectedChannelIds.length > 0) {
                $('#credentials_fields').empty();
                selectedChannelIds.forEach(function(channel_id) {
                    let selectedOption = $(`#results_dropdown option[value="${channel_id}"]`);
                    let selectedText = selectedOption.text();
                    $('#credentials_fields').append(`
                        <div class="form-group">
                            <label for="username_${channel_id}"><strong>Username for Channel ID ${channel_id} for / ${selectedText}:</strong></label>
                            <input type="text" name="username" id="username_${channel_id}">
                        </div>
                        <div class="form-group">
                            <label for="password_${channel_id}"><strong>Password for Channel ID ${channel_id} for / ${selectedText}:</strong></label>
                            <input type="text" name="password" id="password_${channel_id}">
                        </div>
                    `);
                });
                $('#credentials_fields').show();
            } else {
                $('#credentials_fields').hide();
                alert('Please select at least one channel ID before choosing "Your Own Credentials".');
            }
        } else {
            $('#credentials_fields').hide();
        }
    });
    
    // Toggle visibility of credentials fields based on selection
    $('#credentials_fields').hide();

    
});
