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

use Elementor\Controls_Manager;
use Elementor\Widget_Base;
use Elementor\Plugin;

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

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

	/**
	 * Define Tpaep_Table_Form class
	 */
	class Tpaep_Table_Form {

		/**
		 * A reference to an instance of this class.
		 *
		 * @since 6.2.5
		 * @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.2.5
		 *
		 * @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;
		}

		/**
		 * Document Link For Need help
		 *
		 * @var tp_doc of the class.
		 */
		public $tp_doc = THEPLUS_TPDOC;

		/**
		 * Initalize integration hooks
		 *
		 * @since 6.2.5
		 * @return void
		 */
		public function __construct() {
			add_action( 'elementor/element/tp-table/section_table/after_section_end', array( $this, 'tp_add_plus_form_section' ), 10, 2 );
			add_action( 'wp_ajax_tp_get_form_fields', array( $this, 'tp_get_form_fields_callback' ) );
			add_action( 'elementor/editor/before_enqueue_scripts', array( $this, 'tp_enqueue_table_admin_scripts' ) );
		}

		/**
		 * Adds the "Plus Form Settings" controls section to the TP Table widget in Elementor.
		 *
		 * @param \Elementor\Element_Base $element    The Elementor element instance.
		 *
		 * @since 6.2.5
		 */
		public function tp_add_plus_form_section( $element ) {
			if ( $element->get_name() !== 'tp-table' ) {
				return;
			}

			$element->start_controls_section(
				'section_plus_form_settings',
				array(
					'label'     => esc_html__( 'Form Settings', 'theplus' ),
					'tab'       => Controls_Manager::TAB_CONTENT,
					'condition' => array(
						'table_selection' => 'plus_form',
					),
				)
			);

			$element->add_control(
				'form_label',
				array(
					'type'  => Controls_Manager::RAW_HTML,
					'raw'   => sprintf(
						'<p class="tp-controller-label-text"><i> %s <a class="tp-docs-link" href="%s" target="_blank" rel="noopener noreferrer">Learn More</a></i></p>',
						esc_html__( 'Select the "The Plus Addons for Elementor\'s" Form from the dropdown, it will appear with the same name as the Form ID you added in the Form Widget.', 'theplus' ),
						esc_url( $this->tp_doc . 'show-the-form-submission-entries-in-elementor-table/?utm_source=wpbackend&utm_medium=elementoreditor&utm_campaign=widget' )
					),
					'label_block' => true,
				)
			);

			$element->add_control(
				'select_form',
				array(
					'label'   => esc_html__( 'Select Form', 'theplus' ),
					'type'    => Controls_Manager::SELECT,
					'default' => 'None',
					'options' => $this->tp_get_form_options(),
				)
			);

			$element->add_control(
				'columns_selection',
				array(
					'label'   => esc_html__( 'Show Columns', 'theplus' ),
					'type'    => Controls_Manager::SELECT,
					'options' => array(
						'all_columns'      => esc_html__( 'All Columns', 'theplus' ),
						'selected_columns' => esc_html__( 'Selected Columns', 'theplus' ),
					),
					'default' => 'all_columns',
				)
			);

			$element->add_control(
				'form_columns',
				array(
					'label'       => esc_html__( 'Select Columns', 'theplus' ),
					'type'        => Controls_Manager::SELECT2,
					'multiple'    => true,
					'label_block' => true,
					'options'     => array(),
					'condition'   => array(
						'columns_selection' => 'selected_columns',
					),
				)
			);

			$element->end_controls_section();
		}

		/**
		 * Get a list of TP forms from the database.
		 *
		 * @return array Array of form options in the format [form_id => "Form Name (#ID)"].
		 */
		public function tp_get_form_options() {
			global $wpdb;

			$formsmeta_table = $wpdb->prefix . 'tpaep_formsmeta';
			$table_cache_key = 'tp_formsmeta_table_exists';
			$table_exists    = wp_cache_get( $table_cache_key, 'theplus' );
			if ( false === $table_exists ) {
				$table_exists = $wpdb->get_var(
					$wpdb->prepare(
						'SHOW TABLES LIKE %s',
						$formsmeta_table
					)
				);
				wp_cache_set( $table_cache_key, $table_exists, 'theplus', 300 );
			}
			if ( $table_exists !== $formsmeta_table ) {
				return array(
					'None' => esc_html__( 'None', 'theplus' ),
				);
			}

			$formsmeta_table_esc = esc_sql( $formsmeta_table );
			$results_cache_key   = 'tp_form_options';
			$results             = wp_cache_get( $results_cache_key, 'theplus' );
			if ( false === $results ) {
				$results = $wpdb->get_results(
					"SELECT form_id, MIN(form_name) as form_name FROM `{$formsmeta_table_esc}` GROUP BY form_id ORDER BY form_name ASC",
					ARRAY_A
				);
				wp_cache_set( $results_cache_key, $results, 'theplus', 300 );
			}

			$options = array(
				'None' => esc_html__( 'None', 'theplus' ),
			);

			if ( ! empty( $results ) ) {
				foreach ( $results as $row ) {
					$form_id   = esc_attr( $row['form_id'] );
					$form_name = esc_html( $row['form_name'] );

					$options[ $form_id ] = $form_name ? $form_name . ' (#' . $form_id . ')' : 'Form #' . $form_id;
				}
			}

			return $options;
		}

		/**
		 * Handles AJAX request to get form field keys for the selected form.
		 *
		 * @since 6.2.5
		 * @return void Outputs JSON response with form field keys or error.
		 */
		public function tp_get_form_fields_callback() {
			if ( ! isset( $_POST['nonce'] ) || ! check_ajax_referer( 'form_table', 'nonce', false ) ) {
				wp_send_json(
					array(
						'success' => false,
						'message' => esc_html__( 'Invalid or missing nonce.', 'theplus' ),
					)
				);
			}
			if ( ! isset( $_POST['form_id'] ) ) {
				wp_send_json(
					array(
						'success' => false,
						'message' => esc_html__( 'Missing form_id', 'theplus' ),
					)
				);
			}

			global $wpdb;

			$submitted_form_slug = sanitize_text_field( wp_unslash( $_POST['form_id'] ) );

			$meta_table     = $wpdb->prefix . 'tpaep_formsmeta';
			$meta_table_esc = esc_sql( $meta_table );
			$meta_cache_key = 'tp_meta_id_' . $submitted_form_slug;
			$meta_id        = wp_cache_get( $meta_cache_key, 'theplus' );
			if ( false === $meta_id ) {
				$meta_id = $wpdb->get_var(
					$wpdb->prepare(
						"SELECT id FROM `{$meta_table_esc}` WHERE form_id = %s",
						$submitted_form_slug
					)
				);
				wp_cache_set( $meta_cache_key, $meta_id, 'theplus', 300 );
			}

			if ( ! $meta_id ) {
				wp_send_json(
					array(
						'success' => false,
						'message' => esc_html__( 'Invalid form_id or not found', 'theplus' ),
					)
				);
			}

			$values_table     = $wpdb->prefix . 'tpaep_forms';
			$values_table_esc = esc_sql( $values_table );
			$fields_cache_key = 'tp_form_fields_' . $meta_id;
			$results          = wp_cache_get( $fields_cache_key, 'theplus' );
			if ( false === $results ) {
				$results = $wpdb->get_col(
					$wpdb->prepare(
						"SELECT DISTINCT `key` FROM `{$values_table_esc}` WHERE form_id = %d",
						$meta_id
					)
				);
				wp_cache_set( $fields_cache_key, $results, 'theplus', 300 );
			}

			if ( empty( $results ) ) {
				wp_send_json(
					array(
						'success' => false,
						'message' => esc_html__( 'No fields found', 'theplus' ),
					)
				);
			}

			$fields = array();
			foreach ( $results as $field_key ) {
				$fields[ $field_key ] = $field_key;
			}

			wp_send_json(
				array(
					'success' => true,
					'message' => $fields,
				)
			);
		}

		/**
		 * Enqueues the admin script for the Plus Table Form module.
		 *
		 * This script is used to add necessary JavaScript functionality
		 * for the Plus Table module in the admin panel.
		 *
		 * @since 6.3.9 Add your actual plugin version here.
		 * @return void
		 */
		public function tp_enqueue_table_admin_scripts() {
			wp_enqueue_script( 'plus-table-form-js', $this->pathurl_security2( THEPLUS_URL . DIRECTORY_SEPARATOR . 'modules/widget-patch/table/plus-table-form.js' ), array(), THEPLUS_VERSION, true );
		}

		/**
		 * Sanitizes a given URL by removing protocol and double slashes.
		 *
		 * This helps in preventing invalid paths or insecure mixed content warnings.
		 *
		 * @since 6.3.9 Add your actual plugin version here.
		 * @param string $url The URL to sanitize.
		 * @return string Sanitized URL.
		 */
		public function pathurl_security2( $url ) {
			return preg_replace( array( '/^http:/', '/^https:/', '/(?!^)\/\//' ), array( '', '', '/' ), $url );
		}
	}
}

Tpaep_Table_Form::get_instance();