<?php
if (!defined('ABSPATH'))
    exit;
$wpsslc_selected_form = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0; ?>
    <?php

$wpsslc_view_entry = isset($_GET['entryid']) ? absint($_GET['entryid']) : 0;

if ($wpsslc_view_entry > 0) {

    global $wpdb;

    $wpsslc_table_name = $wpdb->prefix . 'wpssc_form_entry';

    $wpsslc_safe_table_name = esc_sql($wpsslc_table_name);

    // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Single entry fetch for display; dynamic entry ID cannot be cached. {$wpsslc_safe_table_name} built from $wpdb->prefix and escaped with esc_sql().
    $wpsslc_rows = $wpdb->get_results(
        $wpdb->prepare(
        "SELECT name,value
                 FROM {$wpsslc_safe_table_name}
                 WHERE cf7_id=%d AND data_id=%d",
        $wpsslc_selected_form,
        $wpsslc_view_entry
    )
    );
    // phpcs:enable
    echo '<div class="card">';
    echo '<h2>Entry #' . esc_html($wpsslc_view_entry) . '</h2>';
    echo '<table class="widefat striped">';

    if (!empty($wpsslc_rows)) {
        foreach ($wpsslc_rows as $wpsslc_row) {
            echo '<tr>';
            echo '<th>' . esc_html(ucwords(str_replace(['-', '_'], ' ', $wpsslc_row->name))) . '</th>';
            echo '<td>' . esc_html($wpsslc_row->value) . '</td>';
            echo '</tr>';
        }
    }
    echo '</table>';
    echo '</div>';
}
if ($wpsslc_selected_form > 0) {
    require_once plugin_dir_path(__FILE__) . '/class-wpsslc-cf7-entries-table.php';
    if (class_exists('WPSSLC_CF7_Entries_Table')) {
        $wpsslc_table = new WPSSLC_CF7_Entries_Table($wpsslc_selected_form);
        $wpsslc_back_forms_url = add_query_arg([
            'page' => 'wpsyncsheets-for-contact-form-7',
            'view' => 'forms',
        ], admin_url('admin.php'));
?>
            <?php
        if (isset($_GET['wpssc_export_error']) && 'no_selection' === $_GET['wpssc_export_error'] ) {
?>
                <div class="entry-notes wpssc-entry-notes-postbox">                  
                    <div class="note" data-type="notification" data-sub-type="failed" style="padding: 0 !important;">
                        <?php
            $wpsslc_status_class = 'wpssc_note_error';
            $wpsslc_sheet_message = 'Please select at least one entry to export.';
?>
                        
                        <div class="note-content wpssc_note_notification alert <?php echo esc_attr($wpsslc_status_class); ?>" style="margin-top:0;">
                            <?php echo wp_kses_post($wpsslc_sheet_message); ?>
                        </div>

                    </div>
                </div>
            <?php
        }
        if (isset($_GET['wpssc_export_error'])): ?>
                <script>
                    if (window.history.replaceState) {
                        const url = new URL(window.location.href);
                        url.searchParams.delete('wpssc_export_error');
                        window.history.replaceState({}, document.title, url.toString());
                    }
                </script>
            <?php
        endif; ?>
            <a href="<?php echo esc_url($wpsslc_back_forms_url); ?>" class="backtoform-btn"><span>←</span> Back</a>
            <div class="top-section">
                <div class="commontopbar">
                    <form method="get" class="formlisting">
                        <input type="hidden" name="page" value="<?php echo esc_attr(isset($_REQUEST['page']) ? sanitize_key(wp_unslash($_REQUEST['page'])) : ''); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Read-only URL param for building admin link; no data mutated. ?>" />
                        <input type="hidden" name="view" value="entries" />
                        <select name="form_id" onchange="this.form.submit()">
                            <option value="">Select Contact Form</option>
                            <?php
        $wpsslc_forms = get_posts([
            'post_type' => 'wpcf7_contact_form',
            'numberposts' => -1,
        ]);

        if (!empty($wpsslc_forms)) {
            foreach ($wpsslc_forms as $wpsslc_form) {
                echo '<option value="' . esc_attr($wpsslc_form->ID) . '" ' .
                    selected($wpsslc_selected_form, $wpsslc_form->ID, false) . '>' .
                    esc_html($wpsslc_form->post_title) .
                    '</option>';
            }
        }
?>
                        </select>
                    </form>
                </div>
                <div class="commontopbar datefilter">
                    <form method="get">
                        <?php
        $wpsslc_date_filter = isset($_GET['date_filter']) ? sanitize_text_field(wp_unslash($_GET['date_filter'])) : '';
        $wpsslc_date_from = isset($_GET['date_from']) ? sanitize_text_field(wp_unslash($_GET['date_from'])) : '';
        $wpsslc_date_to = isset($_GET['date_to']) ? sanitize_text_field(wp_unslash($_GET['date_to'])) : '';
?>
                        <input type="hidden" name="page" value="wpsyncsheets-for-contact-form-7">
                        <input type="hidden" name="view" value="entries">
                        <input type="hidden" name="form_id" value="<?php echo esc_attr($wpsslc_selected_form); ?>">
                        <div class="date_filter">
                            <label>Filter By:</label>
                            <select name="date_filter" id="date_filter">
                                <option value="">All Dates</option>
                                <option value="today" <?php selected($wpsslc_date_filter, 'today'); ?>>Today</option>
                                <option value="7days" <?php selected($wpsslc_date_filter, '7days'); ?>>Last 7 Days</option>
                                <option value="month" <?php selected($wpsslc_date_filter, 'month'); ?>>This Month</option>
                                <option value="custom" <?php selected($wpsslc_date_filter, 'custom'); ?>>Custom Range</option>
                            </select>
                            <div class="custom-date-range" <?php echo('custom' !== $wpsslc_date_filter) ? 'style="display: none;"' : ''; ?>>
                                <input type="date" name="date_from" value="<?php echo esc_attr($wpsslc_date_from); ?>">
                                <input type="date" name="date_to" value="<?php echo esc_attr($wpsslc_date_to); ?>">
                            </div>
                            <input type="submit" class="button button-primary" value="Filter">
                        </div>
                    </form>
                </div>
                <div class="commontopbar">
                    <div class="managecolumn">
                        <?php
        // Save column settings
        if (isset($_POST['wpssc_save_columns'])) {
            check_admin_referer('wpssc_columns_nonce');
            $wpsslc_visible = isset($_POST['wpssc_visible']) ? array_map('sanitize_text_field', wp_unslash($_POST['wpssc_visible'])) : [];
            $wpsslc_labels = isset($_POST['wpssc_labels']) ? array_map('sanitize_text_field', wp_unslash($_POST['wpssc_labels'])) : [];
            $wpsslc_order = isset($_POST['column_order'])
                ? array_map('sanitize_text_field', wp_unslash($_POST['column_order']))
                : [];

            update_option("wpssc_form_columns_{$wpsslc_selected_form}", [
                'wpssc_visible' => $wpsslc_visible,
                'wpssc_labels' => $wpsslc_labels,
                'column_order' => $wpsslc_order
            ]);
        }

        global $wpdb;

        $wpsslc_table_name = $wpdb->prefix . 'wpssc_form_entry';
        $wpsslc_safe_table_name = esc_sql($wpsslc_table_name);

        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Dynamic field listing per form; result varies per form configuration and cannot be cached globally. {$wpsslc_safe_table_name} built from $wpdb->prefix and escaped with esc_sql().
        $wpsslc_fields = $wpdb->get_col(
            $wpdb->prepare(
            "SELECT DISTINCT name
                                 FROM {$wpsslc_safe_table_name}
                                 WHERE cf7_id = %d",
            $wpsslc_selected_form
        )
        );
        // phpcs:enable
        // Force add default system columns
        $wpsslc_default_columns = ['submit_time', 'submit_ip', 'page_url', 'user_agent'];
        $wpsslc_fields = array_unique(array_merge($wpsslc_fields, $wpsslc_default_columns));
        $wpsslc_settings = get_option("wpssc_form_columns_{$wpsslc_selected_form}", []);

        $wpsslc_visible = $wpsslc_settings['wpssc_visible'] ?? $wpsslc_fields;
        $wpsslc_labels = $wpsslc_settings['wpssc_labels'] ?? [];
        $wpsslc_order = $wpsslc_fields;

?>
                        <button type="button" class="wpssc-form-manage-col-btn" onclick="document.getElementById('wpssc-column-box').style.display='block';">
                            Manage Columns
                        </button>
                    </div>
                </div>
            </div>
            <div id="wpssc-column-box">
                <h3>Manage Columns</h3>

                <form method="post">
                    <input type="hidden" name="page" value="wpsyncsheets-for-contact-form-7">
                    <input type="hidden" name="view" value="entries">
                    <input type="hidden" name="form_id" value="<?php echo esc_attr($wpsslc_selected_form); ?>">
                    <?php wp_nonce_field('wpssc_columns_nonce'); ?>

                    <ul id="wpssc-column-sortable">
                        <?php
        foreach ($wpsslc_order as $wpsslc_field):

            if (in_array($wpsslc_field, ['submit_time', '_db_submission_speed_ms', '_google_submission_speed_ms', '_is_status'], true)) {
                continue;
            }

            $wpsslc_is_checked = in_array($wpsslc_field, $wpsslc_visible, true);
            $wpsslc_label = $wpsslc_labels[$wpsslc_field] ?? ucwords(str_replace(['-', '_'], ' ', $wpsslc_field));
?>
                            <li class="wpssc-column-row">
    
                                <span class="wpssc-drag-handle">☰</span>

                                <span class="wpssc-field-name">
                                    <?php echo esc_html($wpsslc_field); ?>
                                </span>

                                <label class="wpssc-toggle">
                                    <input type="checkbox"
                                           name="wpssc_visible[]"
                                           value="<?php echo esc_attr($wpsslc_field); ?>"
                                           <?php checked($wpsslc_is_checked); ?>>
                                    <span class="wpssc-toggle-slider"></span>
                                </label>

                                <input type="hidden" name="column_order[]" value="<?php echo esc_attr($wpsslc_field); ?>">

                                <input type="text"
                                       class="wpssc-label-input"
                                       name="wpssc_labels[<?php echo esc_attr($wpsslc_field); ?>]"
                                       value="<?php echo esc_attr($wpsslc_label); ?>"
                                       placeholder="Column Label">
                            </li>
                        <?php
        endforeach; ?>
                    </ul>

                    <br>
                    <input type="submit" name="wpssc_save_columns" class="button button-primary" value="Save Columns">
                    <button type="button" class="cancle-button" onclick="document.getElementById('wpssc-column-box').style.display='none';">
                        Cancel
                    </button>
                </form>
            </div>

            <script>
            jQuery(function($){
                $("#wpssc-column-sortable").sortable();

                function toggleDateRange() {
                    if ($('#date_filter').val() === 'custom') {
                        $('.custom-date-range').show();
                    } else {
                        $('.custom-date-range').hide();
                    }
                }

                // Run on page load
                toggleDateRange();

                // Run on change
                $('#date_filter').on('change', function () {
                    toggleDateRange();
                });
            });
            </script>
            <form method="post" id='entryfilter'>
                <input type="hidden" name="page" value="wpsyncsheets-for-contact-form-7">
                <input type="hidden" name="view" value="entries">
                <input type="hidden" name="form_id" value="<?php echo esc_attr($wpsslc_selected_form); ?>">
                <?php wp_nonce_field('bulk-' . $wpsslc_table->_args['plural']); ?>
            <?php
        $wpsslc_table->prepare_items();
        $wpsslc_table->search_box('Search Entries', 'cf7-search');
        $wpsslc_table->display();
        echo '</form>';
    }
    else {
?>
            <div class="entry-notes wpssc-entry-notes-postbox">                  
                <div class="note" data-type="notification" data-sub-type="failed" style="padding: 0 !important;">
                    <?php
        $wpsslc_status_class = 'wpssc_note_error';
        $wpsslc_sheet_message = 'Table class not found.';
?>
                    
                    <div class="note-content wpssc_note_notification alert <?php echo esc_attr($wpsslc_status_class); ?>">
                        <?php echo wp_kses_post($wpsslc_sheet_message); ?>
                    </div>

                </div>
            </div>
        <?php
    }
}
?>