<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

global $wpdb;

$wpsslc_form_id  = isset( $_GET['form_id'] ) ? intval( $_GET['form_id'] ) : 0;
$wpsslc_entry_id = isset( $_GET['entryid'] ) ? intval( $_GET['entryid'] ) : 0;

if ( ! $wpsslc_form_id || ! $wpsslc_entry_id ) { ?>
    <div class="entry-notes wpssc-entry-notes-postbox">
        <div class="note" data-id="<?php echo esc_attr( $wpsslc_entry_id ); ?>" data-type="notification" data-sub-type="failed" style="padding: 0 !important;">
            <?php
            $wpsslc_status_class  = 'wpssc_note_error';
            $wpsslc_sheet_message = 'Invalid entry request.';
            ?>
            <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
    return;
}

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

/*--------------------------------------------------------------
# Handle Delete
--------------------------------------------------------------*/
$wpsslc_nonce     = isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
$wpsslc_delete_id = isset( $_POST['delete_entry_id'] ) ? absint( wp_unslash( $_POST['delete_entry_id'] ) ) : 0;

if (
    $wpsslc_delete_id > 0 &&
    $wpsslc_nonce &&
    wp_verify_nonce( $wpsslc_nonce, 'delete_single_entry' )
) {

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpsslc_deleted = $wpdb->delete(
        $wpsslc_table_name,
        [
            'cf7_id'  => $wpsslc_form_id,
            'data_id' => $wpsslc_delete_id,
        ],
        [ '%d', '%d' ]
    );

    if ( false !== $wpsslc_deleted && $wpsslc_deleted > 0 ) {

        $wpsslc_service = WPSSLC_Service::get_instance();

        // CONDITION NOT MODIFIED (as requested)
        if ( $wpsslc_service->wpssc_is_sheet_sync_active( $wpsslc_form_id ) ) {

            $wpsslc_service->wpssc_delete_entries_from_sheet(
                $wpsslc_form_id,
                [ $wpsslc_delete_id ]
            );
        }
    }

    wp_safe_redirect(
        add_query_arg(
            [
                'page'    => 'wpsyncsheets-for-contact-form-7',
                'form_id' => $wpsslc_form_id,
                'view'    => 'entries',
                'deleted' => 1,
            ],
            admin_url( 'admin.php' )
        )
    );
    exit;
}

/*--------------------------------------------------------------
# Fetch Entry
--------------------------------------------------------------*/

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpsslc_rows = $wpdb->get_results(
    $wpdb->prepare(
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        "SELECT name, value FROM {$wpsslc_table_name} WHERE cf7_id = %d AND data_id = %d",
        $wpsslc_form_id,
        $wpsslc_entry_id
    ),
    ARRAY_A
);

$wpsslc_back_url = admin_url(
    'admin.php?page=wpsyncsheets-for-contact-form-7&form_id=' .
    $wpsslc_form_id .
    '&view=entries'
);

if ( empty( $wpsslc_rows ) ) { ?>
    <div class="entry-notes wpssc-entry-notes-postbox">
        <div class="note" data-id="<?php echo esc_attr( $wpsslc_entry_id ); ?>" data-type="notification" data-sub-type="failed" style="padding: 0 !important;">
            <?php
            $wpsslc_status_class  = 'wpssc_note_error';
            $wpsslc_sheet_message = '<strong>Entry not found.</strong> The requested submission may have been deleted or does not exist.';
            ?>
            <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
    return;
}

/*--------------------------------------------------------------
# Organize Data
--------------------------------------------------------------*/

$wpsslc_entry_data                 = [];
$wpsslc_submit_time                = '';
$wpsslc_submit_ip                  = '';
$wpsslc_page_url                   = '';
$wpsslc_user_agent                 = '';
$wpsslc_google_submission_speed_ms = '';
$wpsslc_db_submission_speed_ms     = '';
$wpsslc_is_status                  = '';

foreach ( $wpsslc_rows as $wpsslc_row ) {

    $wpsslc_value = maybe_unserialize( $wpsslc_row['value'] );

    if ( is_array( $wpsslc_value ) ) {
        $wpsslc_value = implode( ', ', $wpsslc_value );
    }

    if ( 'submit_time' === $wpsslc_row['name'] ) {
        $wpsslc_submit_time = $wpsslc_value;
        continue;
    }

    if ( 'submit_ip' === $wpsslc_row['name'] ) {
        $wpsslc_submit_ip = $wpsslc_value;
        continue;
    }

    if ( 'page_url' === $wpsslc_row['name'] ) {
        $wpsslc_page_url = $wpsslc_value;
        continue;
    }

    if ( 'user_agent' === $wpsslc_row['name'] ) {
        $wpsslc_user_agent = $wpsslc_value;
        continue;
    }

    if ( '_db_submission_speed_ms' === $wpsslc_row['name'] ) {
        $wpsslc_db_submission_speed_ms = $wpsslc_value;
        continue;
    }

    if ( '_google_submission_speed_ms' === $wpsslc_row['name'] ) {
        $wpsslc_google_submission_speed_ms = $wpsslc_value;
        continue;
    }

    if ( '_is_status' === $wpsslc_row['name'] ) {
        $wpsslc_is_status = $wpsslc_value;
        continue;
    }

    $wpsslc_entry_data[ $wpsslc_row['name'] ] = $wpsslc_value;
}

/*--------------------------------------------------------------
# Navigation
--------------------------------------------------------------*/

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpsslc_prev_id = $wpdb->get_var(
    $wpdb->prepare(
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        "SELECT MAX(data_id) FROM {$wpsslc_table_name} WHERE cf7_id = %d AND data_id < %d",
        $wpsslc_form_id,
        $wpsslc_entry_id
    )
);

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpsslc_next_id = $wpdb->get_var(
    $wpdb->prepare(
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        "SELECT MIN(data_id) FROM {$wpsslc_table_name} WHERE cf7_id = %d AND data_id > %d",
        $wpsslc_form_id,
        $wpsslc_entry_id
    )
);

$wpsslc_base_url = admin_url(
    'admin.php?page=wpsyncsheets-for-contact-form-7&form_id=' .
    $wpsslc_form_id .
    '&view=entry'
);

?>

<div class="wpssc-entry-wrap singleentry">
<div class="wpssc-entry-layout">

<?php
$wpsslc_settings     = get_option( 'wpssc_form_columns_' . $wpsslc_form_id, [] );
$wpsslc_field_labels = isset( $wpsslc_settings['wpssc_labels'] )
    ? $wpsslc_settings['wpssc_labels']
    : [];
?>

<div class="wpssc-entry-main">

<div class="postbox">
<div class="postbox-header">
<h2 class="hndle">Submission Details <a href="" onclick="return false;">#<?php echo esc_html( $wpsslc_entry_id ); ?></a></h2>
</div>

<div class="inside">

<table class="widefat striped wpssc-entry-table">
<tbody>

<?php
if ( ! empty( $wpsslc_rows ) ) :

    foreach ( $wpsslc_rows as $wpsslc_row ) :

        $wpsslc_field_key = $wpsslc_row['name'];

        if (
            in_array(
                $wpsslc_field_key,
                [
                    'submit_time',
                    'submit_ip',
                    'page_url',
                    'user_agent',
                    '_db_submission_speed_ms',
                    '_google_submission_speed_ms',
                    '_is_status',
                ],
                true
            )
        ) {
            continue;
        }

        $wpsslc_value = maybe_unserialize( $wpsslc_row['value'] );

        if ( is_array( $wpsslc_value ) ) {
            $wpsslc_value = implode( ', ', $wpsslc_value );
        }

        $wpsslc_label = isset( $wpsslc_field_labels[ $wpsslc_field_key ] )
            ? $wpsslc_field_labels[ $wpsslc_field_key ]
            : ucwords( str_replace( [ '-', '_' ], ' ', $wpsslc_field_key ) );
?>

<tr>
<th><?php echo esc_html( $wpsslc_label ); ?></th>
<td><?php echo nl2br( esc_html( $wpsslc_value ) ); ?></td>
</tr>

<?php
    endforeach;

else :
    echo '<tr><td colspan="2">No submission data available.</td></tr>';
endif;
?>

</tbody>
</table>

        </div>
    </div>
    <?php if ('no' !== (string)get_post_meta($wpsslc_form_id, 'wpssc_all_settings', true)) { ?>
    <div class="postbox wpssc-entry-notes-postbox">
        <div id="normal-sortables" class="meta-box-sortables ui-sortable">
            
            <div id="notes" class="postbox">
                
                <div class="postbox-header">
                    <h2 class="hndle ui-sortable-handle">Notes</h2>
                </div>

                <div class="inside">

                    
                    <div class="entry-notes">
                        
                        <h3 class="entry-notes-print-header">Notes</h3>

                        <!-- Note 1 -->
                        <div class="note" data-id="<?php echo esc_attr($wpsslc_entry_id); ?>" data-type="notification" data-sub-type="<?php echo esc_attr($wpsslc_is_status); ?>">
                            <?php
                            $wpsslc_status_class = 'wpssc_note_error';
                            $wpsslc_sheet_message = '';
                            if ('success' === $wpsslc_is_status ) {
                                $wpsslc_sheet_message = 'Entry successfully saved to Google Sheet.';
                                $wpsslc_status_class = 'wpssc_note_success';
                            }
                            elseif ('failed' === $wpsslc_is_status) {
                                $wpsslc_sheet_message = 'Entry failed to save to Google Sheet.';
                            }
                            elseif ('skipped' === $wpsslc_is_status) {
                                $wpsslc_sheet_message = 'Entry skipped for Google Sheet.';
                                $wpsslc_status_class = 'wpssc_note_info';
                            }
                            else {
                                $wpsslc_sheet_message = 'Entry was not processed for Google Sheet.';
                            }
                        ?>
                            
                            <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>
                    
                </div>
            </div>

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

        <!-- RIGHT SIDEBAR -->
        <div class="wpssc-entry-sidebar">

            <div class="postbox">
                <div class="postbox-header">
                    <h2 class="hndle">Entry Information</h2>
                </div>
                <div class="inside">

                    <div class="wpssc-meta-row">
                        <span class="label">Page URL</span>
                        <span class="value">
                            <?php
if (!empty($wpsslc_page_url)) {
    $wpsslc_trimmed = (strlen($wpsslc_page_url) > 35) ? substr($wpsslc_page_url, 0, 35) . '...' : $wpsslc_page_url;
?>
                            <span class="wpssc-custom-page-link-span">
                                <?php echo esc_html($wpsslc_trimmed); ?>
                            </span>
                            <a href="<?php echo esc_url($wpsslc_page_url); ?>" target="_blank" class="wpssc-custom-page-link">
                                <img src="<?php echo esc_url(WPSSLC_URL . 'assets/images/external-link-icon.svg'); ?>" alt="" >
                            </a>
                            <?php
}
else {
    echo esc_html( $wpsslc_page_url ? $wpsslc_page_url : '—' );
}?>
                        </span>
                    </div>

                    <div class="wpssc-meta-row">
                        <span class="label">User Agent</span>
                        <span class="value"><?php echo esc_html($wpsslc_user_agent ? $wpsslc_user_agent : '—'); ?></span>
                    </div>

                    <div class="wpssc-meta-row">
                        <span class="label">Submitted On</span>
                        <span class="value"><?php echo esc_html($wpsslc_submit_time ? $wpsslc_submit_time : '—'); ?></span>
                    </div>

                    <div class="wpssc-meta-row">
                        <span class="label">IP Address</span>
                        <span class="value"><?php echo esc_html($wpsslc_submit_ip ? $wpsslc_submit_ip : '—'); ?></span>
                    </div>

                    <div class="wpssc-navigation">

                        <?php if ($wpsslc_prev_id): ?>
                            <a class="button"
                               href="<?php echo esc_url($wpsslc_base_url . '&entryid=' . $wpsslc_prev_id); ?>">
                                ← Previous Entry
                            </a>
                        <?php
endif; ?>

                        <?php if ($wpsslc_next_id): ?>
                            <a class="button"
                               href="<?php echo esc_url($wpsslc_base_url . '&entryid=' . $wpsslc_next_id); ?>">
                                Next Entry →
                            </a>
                        <?php
endif; ?>

                    </div>

                </div>
            </div>

            <!-- Delete Section -->
            <div class="postbox wpssc-danger-box">
                <div class="postbox-header">
                    <h2 class="hndle">Delete Entry</h2>
                </div>
                <div class="inside">

                    <p class="description">
                        Permanently remove this submission from the database.
                        This action cannot be undone.
                    </p>

                    <form method="post">
                        <?php wp_nonce_field('delete_single_entry'); ?>
                        <input type="hidden" name="delete_entry_id" value="<?php echo esc_attr($wpsslc_entry_id); ?>">
                        <button type="submit" class="wpssc-delete-btn">
                            Delete Permanently
                        </button>
                    </form>

                </div>
            </div>

            <div class="postbox">
                <div class="postbox-header">
                    <h2 class="hndle">Submission Speed (ms)</h2>
                </div>
                <div class="inside">

                    <div class="wpssc-meta-row">
                        <span class="label">Google Submission Speed</span>
                        <span class="value"><?php echo esc_html($wpsslc_google_submission_speed_ms ? $wpsslc_google_submission_speed_ms : '—'); ?></span>
                    </div>
                    <div class="wpssc-meta-row">
                        <span class="label">DB Submission Speed</span>
                        <span class="value"><?php echo esc_html($wpsslc_db_submission_speed_ms ? $wpsslc_db_submission_speed_ms : '—'); ?></span>
                    </div>
                </div>
            </div>

        </div>

    </div>

</div>