<?php
/**
 * The file that defines the core plugin class
 *
 * @link    https://posimyth.com/
 * @since   6.5.6
 *
 * @package the-plus-addons-for-elementor-page-builder
 */

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

/*
 * Cross Domain Copy Paste Theplus.
 */
if ( ! class_exists( 'Tpaep_Edit_Submission' ) ) {

	/**
	 * Define Tpaep_Edit_Submission class
	 */
	class Tpaep_Edit_Submission {

		/**
		 * A reference to an instance of this class.
		 *
		 * @since 6.5.6
		 * @var   object
		 */
		private static $instance = null;
		/**
		 * Returns a singleton instance of the class.
		 *
		 * This method ensures that only one instance of the class is created (singleton pattern).
		 * If an instance doesn't exist, it creates one using the provided shortcodes.
		 *
		 * @since 6.5.6
		 *
		 * @param array $shortcodes Optional. An array of shortcodes to initialize the instance with.
		 * @return self The single instance of the class.
		 */
		public static function get_instance( $shortcodes = array() ) {

			if ( null === self::$instance ) {
				self::$instance = new self( $shortcodes );
			}

			return self::$instance;
		}

		/**
		 * Initalize integration hooks
		 *
		 * @return void
		 */
		public function __construct() {
            add_action( 'wp_ajax_tpaep_update_submission',  [ $this, 'tpaep_update_submission' ] );
		}

        function tpaep_update_submission() {

            check_ajax_referer( 'tpae_update_submission', 'nonce' );

			if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( [
                    'message' => __( 'Permission denied.', 'theplus' ),
                ] );
            }

			global $wpdb;

			$submission_id = isset( $_POST['submission_id'] ) ? absint( $_POST['submission_id'] ) : 0;
			$fields        = isset( $_POST['fields'] ) && is_array( $_POST['fields'] ) ? $_POST['fields'] : [];

			if ( ! $submission_id || empty( $fields ) ) {
                wp_send_json_error( [
                    'message' => __( 'Invalid submission data.', 'theplus' ),
                ] );
            }

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

            // Guard: bail gracefully if the table does not exist yet.
            $meta_table_exists = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $meta_table ) );
            if ( ! $meta_table_exists ) {
                wp_send_json_error( [
                    'message' => __( 'Form submissions table does not exist.', 'theplus' ),
                ] );
            }

			foreach ( $fields as $key => $value ) {

                $wpdb->update(
                    $data_table,
                    [ 'value' => sanitize_textarea_field( $value ) ],
                    [
                        'form_id' => $submission_id,
                        'key'     => sanitize_key( $key ),
                    ],
                    [ '%s' ],
                    [ '%d', '%s' ]
                );
            }

            // Track the last updated timestamp in its own column
            $wpdb->update(
                $meta_table,
                [ 'updated_at' => current_time( 'mysql' ) ],
                [ 'id' => $submission_id ],
                [ '%s' ],
                [ '%d' ]
            );

            wp_send_json_success( [
                'message' => __( 'Submission updated successfully.', 'theplus' ),
				'updated_at' => date_i18n( 'F j, Y g:i a', time() ),
            ] );
        }
	}
}

Tpaep_Edit_Submission::get_instance();