<?php
/**
 * View Single Form Submission
 *
 * @since 6.2.7
 * @package the-plus-addons-for-elementor-page-builder
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

global $wpdb;

$submission_id = isset( $_GET['view'] ) ? absint( $_GET['view'] ) : 0;

$is_edit = false;

if ( ! $submission_id ) {
    wp_die( esc_html__( 'Invalid submission.', 'theplus' ) );
}
			
// include THEPLUS_PATH . 'modules/extensions/form-submissions/view-submission/class-tpaep-edit-submission.php';

$meta_table = $wpdb->prefix . 'tpaep_formsmeta';
$data_table = $wpdb->prefix . 'tpaep_forms';

// Guard: if the table doesn't exist yet, show a graceful message instead of a DB error.
$meta_table_exists = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $meta_table ) );
if ( ! $meta_table_exists ) {
    wp_die( esc_html__( 'Form submissions table does not exist. Please ensure the feature is properly set up.', 'theplus' ) );
}

$wpdb->update(
    $meta_table,
    [ 'is_read' => 1 ],
    [ 'id' => $submission_id ],
    [ '%d' ],
    [ '%d' ]
);

/**
 * Get submission meta
 */
$submission = $wpdb->get_row(
    $wpdb->prepare(
        "SELECT * FROM $meta_table WHERE id = %d",
        $submission_id
    )
);

if ( ! $submission ) {
    wp_die( esc_html__( 'Submission not found.', 'theplus' ) );
}

/**
 * Get submitted fields
 */
$form_fields = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT `key`, `value` FROM $data_table WHERE form_id = %d",
        $submission_id
    )
);

/**
 * User
 */
$user = ! empty( $submission->user_id )
    ? get_user_by( 'id', $submission->user_id )
    : false;
?>

<div class="wrap">

    <h1 class="wp-heading-inline">
        <?php esc_html_e( 'Form Submission Details', 'theplus' ); ?>
    </h1>

    <a href="<?php echo esc_url( admin_url( 'admin.php?page=tpae-form-submissions' ) ); ?>" class="page-title-action">
        &#8592; <?php esc_html_e( 'Back to Submissions', 'theplus' ); ?>
    </a>

    <hr class="wp-header-end">

    <div id="poststuff">
        <div id="post-body" class="metabox-holder columns-2">

            <!-- LEFT -->
            <div id="post-body-content">

                <div class="postbox">
                
                    <div class="tpae-postbox-header">
                        <h2 class="hndle">
                            <?php 
                            /* translators: %d: submission ID */
                            printf( esc_html__( 'Submission #%d', 'theplus' ), $submission->id ); 
                            ?>
                        </h2>

                        <button type="button" id="tpae-toggle-edit" class="button button-primary">
                            <?php esc_html_e( 'Edit', 'theplus' ); ?>
                        </button>

                    </div>

                    <div class="inside">
                        <form id="tpae-edit-submission-form">
                            <?php wp_nonce_field( 'tpae_update_submission', 'tpae_nonce' ); ?>
                            <input type="hidden" name="submission_id" value="<?php echo esc_attr( $submission_id ); ?>">

                            <div class="tpae-view-submission-details">

                                <table class="widefat striped">
                                    <tbody>
                                        <?php
                                        if ( ! empty( $form_fields ) ) :
                                            foreach ( $form_fields as $field ) :

                                                $key   = sanitize_key( $field->key );
                                                $label = ucwords( str_replace( '_', ' ', $key ) );
                                                $value = maybe_unserialize( $field->value );
                                                ?>
                                                <tr>
                                                    <th style="width:220px;"><?php echo esc_html( $label ); ?></th>
                                                    <td>
                                                        <!-- VIEW MODE -->
                                                        <div class="tpae-view-value">
                                                            <?php
                                                            if ( 'email' === $key && is_email( $value ) ) {
                                                                echo '<a href="mailto:' . esc_attr( $value ) . '">' . esc_html( $value ) . '</a>';
                                                            } elseif ( is_array( $value ) ) {
                                                                echo esc_html( implode( ', ', $value ) );
                                                            } else {
                                                                echo esc_html( $value );
                                                            }
                                                            ?>
                                                        </div>

                                                        <!-- EDIT MODE -->
                                                        <div class="tpae-edit-value" style="display:none;">
                                                            <?php if ( 'message' === $key ) : ?>
                                                                <textarea
                                                                    name="fields[<?php echo esc_attr( $key ); ?>]"
                                                                    rows="4"
                                                                    style="width:100%;"
                                                                ><?php echo esc_textarea( $value ); ?></textarea>
                                                            <?php else : ?>
                                                                <input
                                                                    type="text"
                                                                    name="fields[<?php echo esc_attr( $key ); ?>]"
                                                                    value="<?php echo esc_attr( is_array( $value ) ? implode( ', ', $value ) : $value ); ?>"
                                                                    style="width:100%;"
                                                                >
                                                            <?php endif; ?>
                                                        </div>

                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php else : ?>
                                            <tr>
                                                <td colspan="2"><?php esc_html_e( 'No form data found.', 'theplus' ); ?></td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>

                            </div>
                        </form>
                    </div>
                </div>

                <!-- <div class="postbox">
                    <h2 class="hndle"><?php // esc_html_e( 'Actions Log', 'theplus' ); ?></h2>
                    <div class="inside">
                        <p><?php // esc_html_e( 'No form actions.', 'theplus' ); ?></p>
                    </div>
                </div> -->

            </div>

            <!-- RIGHT -->
            <div id="postbox-container-1" class="postbox-container">

                <div class="postbox tpae-formview-additional-info">
                    <h2 class="hndle"><?php esc_html_e( 'Additional Info', 'theplus' ); ?></h2>
                    <div class="inside">

                        <!-- Top Divider -->
                        <div class="tpae-top-divider"></div>

                        <p>
                            <strong><?php esc_html_e( 'Form:', 'theplus' ); ?></strong>
                            <a href="<?php echo esc_url(
                                admin_url( 'post.php?post=' . absint( $submission->post_id ) . '&action=elementor' )
                            ); ?>" target="_blank">
                                <?php echo esc_html( $submission->form_name ); ?>
                                <span>(#<?php echo esc_html( substr( md5( $submission->form_id ), 0, 7 ) ); ?>)</span>
                            </a>
                        </p>

                        <p>
                            <strong><?php esc_html_e( 'Page:', 'theplus' ); ?></strong>
                            <a href="<?php echo esc_url( get_permalink( $submission->post_id ) ); ?>" target="_blank">
                                <?php echo esc_html( get_the_title( $submission->post_id ) ); ?>
                            </a>
                        </p>

                        <p>
                            <strong><?php esc_html_e( 'Create Date:', 'theplus' ); ?></strong>
                            <?php echo esc_html(
                                date_i18n( 'F j, Y g:i a', strtotime( $submission->submitted_at ) )
                            ); ?>
                        </p>

                        <p>
                            <strong><?php esc_html_e( 'Update Date:', 'theplus' ); ?></strong>
                            <span class="tpae-update-date-value">
                                <?php echo ! empty( $submission->updated_at )
                                    ? esc_html( date_i18n( 'F j, Y g:i a', strtotime( $submission->updated_at ) ) )
                                    : esc_html__( 'Never updated', 'theplus' );
                                ?>
                            </span>
                        </p>

                        <p>
                            <strong><?php esc_html_e( 'User Name:', 'theplus' ); ?></strong>
                            <?php echo $user ? esc_html( $user->display_name ) : esc_html__( 'Guest', 'theplus' ); ?>
                        </p>

                        <p>
                            <strong><?php esc_html_e( 'User IP:', 'theplus' ); ?></strong>
                            <?php echo esc_html( $submission->user_ip ); ?>
                        </p>

                        <p>
                            <strong><?php esc_html_e( 'User Agent:', 'theplus' ); ?></strong>
                            <small><?php echo esc_html( $submission->user_agent ); ?></small>
                        </p>

                        <!-- Bottom Divider -->
                        <div class="tpae-bottom-divider"></div>

                        <div class="tpae-add-info-footer">

                            <?php
                                $trash_url = wp_nonce_url(
                                    admin_url(
                                        'admin.php?page=tpae-form-submissions&delete=' . absint( $submission_id )
                                    ),
                                    'tpae_delete_submission'
                                );
                            ?>

                            <a href="<?php echo esc_url( $trash_url ); ?>" class="submitdelete deletion">
                                <?php esc_html_e( 'Delete', 'theplus' ); ?>
                            </a>

                            <button type="button" id="tpae-update-btn" class="button button-primary" disabled>
                                <?php esc_html_e( 'Update', 'theplus' ); ?>
                            </button>
                        </div>

                    </div>
                </div>

            </div>

            <style>.tpae-postbox-header{display:flex;align-items:center;justify-content:space-between;padding:8px 12px}.tpae-postbox-header .hndle{padding:0;margin:0}.tpae-view-submission-details table{border:1px solid #dcdcde;border-collapse:collapse}.tpae-view-submission-details th{width:220px;padding:14px;background:#f6f7f7;font-weight:600;text-align:left;border-right:1px solid #dcdcde}.tpae-view-submission-details td{padding:14px;background:#fff}.tpae-view-submission-details tr+tr th,.tpae-view-submission-details tr+tr td{border-top:1px solid #dcdcde}.tpae-formview-additional-info .tpae-top-divider{margin:0 -12px;border-top:1px solid #dcdcde}.tpae-formview-additional-info .tpae-bottom-divider{margin:12px -12px;border-top:1px solid #dcdcde}.tpae-formview-additional-info .submitdelete{color:#b32d2e;text-decoration:none;font-weight:500}.tpae-formview-additional-info .submitdelete:hover{color:#8a2424;text-decoration:underline}#tpae-update-btn:disabled{opacity:.5;cursor:not-allowed}#tpae-update-btn{float:right}.tpae-add-info-footer{position:relative;display:flex;justify-content:space-between;align-items:center}</style>
        </div>
    </div>

</div>


<script>
jQuery(document).ready(function ($) {

    let isEditMode = false;

    $('#tpae-toggle-edit').on('click', function () {

        isEditMode = !isEditMode;

        if (isEditMode) {
            // Show edit fields
            $('.tpae-view-value').hide();
            $('.tpae-edit-value').show();

            // Enable update
            $('#tpae-update-btn').prop('disabled', false);

            // Button text
            $(this)
                .text('<?php echo esc_js( __( 'Cancel', 'theplus' ) ); ?>')
                .removeClass('button-primary');
        } else {
            // Back to view mode
            $('.tpae-edit-value').hide();
            $('.tpae-view-value').show();

            // Disable update
            $('#tpae-update-btn').prop('disabled', true);

            $(this)
                .text('<?php echo esc_js( __( 'Edit', 'theplus' ) ); ?>')
                .addClass('button-primary');
        }
    });

    $('#tpae-update-btn').on('click', function (e) {
        if ($(this).prop('disabled')) {
            return;
        }

        e.preventDefault();

        const $btn = $(this);
        let fields = {};

        $('.tpae-edit-value').find('input, textarea').each(function () {
            const match = this.name.match(/\[(.*?)\]/);
            if (match) {
                fields[match[1]] = $(this).val();
            }
        });

        $btn.prop('disabled', true).text('<?php echo esc_js( __( 'Saving...', 'theplus' ) ); ?>');

        $.post(ajaxurl, {
            action: 'tpaep_update_submission',
            nonce: $('#tpae_nonce').val(),
            submission_id: $('input[name="submission_id"]').val(),
            fields: fields
        })
        .done(function (response) {
            if (response.success) {

                // ✅ Update each view-mode value with the newly saved data
                $('.tpae-edit-value').each(function () {
                    const $input   = $(this).find('input, textarea').first();
                    const newVal   = $input.val();
                    const $viewDiv = $(this).closest('td').find('.tpae-view-value');

                    // Get the field key from input name e.g. fields[email] → email
                    const match    = ($input.attr('name') || '').match(/\[(.*?)\]/);
                    const fieldKey = match ? match[1] : '';

                    if ( fieldKey === 'email' && newVal.indexOf('@') !== -1 ) {
                        // Rebuild mailto link safely
                        $viewDiv.empty().append(
                            $('<a>').attr('href', 'mailto:' + newVal).text(newVal)
                        );
                    } else {
                        $viewDiv.text(newVal);
                    }
                });

                // ✅ Update the "Update Date" in the sidebar
                if ( response.data.updated_at ) {
                    $('.tpae-update-date-value').text(response.data.updated_at);
                }

                // Reset back to view mode
                isEditMode = false;
                $('.tpae-edit-value').hide();
                $('.tpae-view-value').show();

                $('#tpae-toggle-edit')
                    .text('<?php echo esc_js( __( 'Edit', 'theplus' ) ); ?>')
                    .addClass('button-primary');

                $('#tpae-update-btn')
                    .prop('disabled', true)
                    .text('<?php echo esc_js( __( 'Update', 'theplus' ) ); ?>');

            } else {
                alert(response.data.message || 'Update failed');
            }
        })

        .fail(function () {
            alert('AJAX error occurred.');
            $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Update', 'theplus' ) ); ?>');
        });
    });

});
</script>



