<?php
/**
 * Funnel Views Trait
 *
 * Handles rendering of funnel analytics page views and components.
 *
 * @package opti-behavior
 * @copyright 2025 OptiUser
 * @version 1.0.0
 */

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

/**
 * Trait for funnel views rendering
 */
trait Opti_Behavior_Funnels_Views_Trait {

	/**
	 * Render the main funnels page
	 */
	public function render_funnels() {
		static $rendered = false;

		// Defensive guard: the page callback should only output once per request.
		// A re-entrant core initialization used to register the Funnels submenu
		// callback twice, duplicating the whole page in wp-admin.
		if ( $rendered ) {
			return;
		}
		$rendered = true;

		global $wpdb;
		$table_sessions = $wpdb->prefix . 'opti_behavior_sessions';

		// Check if tables exist
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Checking table existence.
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_sessions ) ) === $table_sessions;

		// Check if any funnels exist.
		$table_funnels = $wpdb->prefix . 'opti_behavior_funnels';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Checking table existence.
		$funnel_table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_funnels ) ) === $table_funnels;
		$funnel_count = 0;

		if ( $funnel_table_exists ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table names from $wpdb->prefix; analytics queries.
			$funnel_count = $wpdb->get_var( "SELECT COUNT(*) FROM {$table_funnels} WHERE status = 'active'" );
		}
		$tooltips = opti_behavior_get_funnels_tooltips();
		?>
		<div class="wrap opti-behavior-funnels-page">
			<!-- Header with Funnels Title -->
			<div class="heatmaps-header">
				<div class="heatmaps-header-content">
					<div class="heatmaps-title-section">
						<div class="heatmaps-icon"><i data-lucide="filter"></i></div>
						<div class="heatmaps-title-text">
							<h1 class="heatmaps-title"><?php esc_html_e( 'Funnels', 'opti-behavior' ); ?><?php opti_behavior_tooltip_e( $tooltips['what_is_funnel']['title'], $tooltips['what_is_funnel']['content'], $tooltips['what_is_funnel']['simple'], $tooltips['what_is_funnel']['example'], array( 'position' => 'bottom' ) ); ?></h1>
							<div class="heatmaps-subtitle"><?php esc_html_e( 'Track user journeys and conversion paths', 'opti-behavior' ); ?></div>
						</div>
					</div>
				</div>
			</div>
			<?php if ( function_exists( 'opti_behavior_pro_sodium_banner' ) ) { opti_behavior_pro_sodium_banner(); } ?>

			<div class="funnels-content-wrapper">
				<!-- Action Button (always visible) -->
				<div class="funnels-actions">
					<button class="btn-build-funnel">
						<span class="dashicons dashicons-plus-alt"></span>
						<?php esc_html_e( 'Build New Funnel', 'opti-behavior' ); ?>
					</button>
				</div>

				<?php if ( $funnel_count == 0 ) : ?>
				<!-- Empty State -->
				<div class="funnels-empty-state">
					<div class="empty-state-image">
						<img src="<?php echo esc_url( plugins_url( 'assets/images/Funnel-sales-lead.png', dirname( __FILE__ ) ) ); ?>" alt="<?php esc_attr_e( 'Funnel Illustration', 'opti-behavior' ); ?>" />
					</div>
					<h2 class="empty-state-title"><?php esc_html_e( 'No Funnels Yet', 'opti-behavior' ); ?></h2>
					<p class="empty-state-description">
						<?php esc_html_e( 'Create your first funnel to start tracking user behavior and conversion rates through your website.', 'opti-behavior' ); ?>
					</p>
				</div>
			<?php else : ?>
				<!-- Funnel Cards Container -->
				<div id="funnels-list-container">
					<!-- Funnels will be loaded here via AJAX -->
				</div>
			<?php endif; ?>

			<!-- Funnel Card (hidden template for reference) -->
			<div class="funnel-card" style="display: none;">
				<!-- Funnel Card Header -->
				<div class="funnel-card-header">
					<div class="funnel-title-section">
						<h2 class="funnel-title"><?php esc_html_e( 'Purchase Journey', 'opti-behavior' ); ?></h2>
					</div>
					<div class="funnel-controls">
						<!-- Time Period Filter -->
						<div class="funnel-control-wrapper">
							<button class="funnel-control-btn" id="funnel-period-btn">
								<span class="dashicons dashicons-calendar-alt"></span>
								<span id="funnel-period-label">7 Days</span>
								<span class="dashicons dashicons-arrow-down-alt2"></span>
							</button>
							<!-- Period Dropdown -->
							<div class="period-dropdown" id="period-dropdown" style="display: none;">
								<button class="period-option" data-period="7days"><?php esc_html_e( '7 Days', 'opti-behavior' ); ?></button>
								<button class="period-option" data-period="30days"><?php esc_html_e( '30 Days', 'opti-behavior' ); ?></button>
								<button class="period-option" data-period="90days"><?php esc_html_e( '90 Days', 'opti-behavior' ); ?></button>
								<button class="period-option" data-period="custom"><?php esc_html_e( 'Custom Range', 'opti-behavior' ); ?></button>
							</div>
						</div>

						<!-- Device Filter -->
						<div class="funnel-control-wrapper">
							<button class="funnel-control-btn" id="funnel-device-btn">
								<i data-lucide="layout-grid"></i>
								<span id="funnel-device-label">All Devices</span>
								<span class="dashicons dashicons-arrow-down-alt2"></span>
							</button>
							<!-- Device Dropdown -->
							<div class="period-dropdown" id="device-dropdown" style="display: none;">
								<button class="period-option" data-device="all"><?php esc_html_e( 'All Devices', 'opti-behavior' ); ?></button>
								<button class="period-option" data-device="desktop"><?php esc_html_e( 'Desktop', 'opti-behavior' ); ?></button>
								<button class="period-option" data-device="mobile"><?php esc_html_e( 'Mobile', 'opti-behavior' ); ?></button>
								<button class="period-option" data-device="tablet"><?php esc_html_e( 'Tablet', 'opti-behavior' ); ?></button>
							</div>
						</div>

						<!-- Country Filter -->
						<div class="funnel-control-wrapper">
							<button class="funnel-control-btn" id="funnel-country-btn">
								<i data-lucide="globe"></i>
								<span id="funnel-country-label">All Countries</span>
								<span class="dashicons dashicons-arrow-down-alt2"></span>
							</button>
							<!-- Country Dropdown -->
							<div class="period-dropdown" id="country-dropdown" style="display: none;">
								<button class="period-option" data-country="all"><?php esc_html_e( 'All Countries', 'opti-behavior' ); ?></button>
								<!-- Countries will be loaded dynamically -->
								<div id="country-options-container"></div>
							</div>
						</div>

						<!-- Top Metrics Badges -->
						<div class="funnel-metrics-badges">
							<span class="metric-badge metric-badge-blue" id="badge-1">
								<span class="dashicons dashicons-chart-bar"></span>
								<span class="badge-value">--</span>
							</span>
							<span class="metric-badge metric-badge-purple" id="badge-2">
								<span class="dashicons dashicons-groups"></span>
								<span class="badge-value">--</span>
							</span>
							<span class="metric-badge metric-badge-teal" id="badge-3">
								<span class="dashicons dashicons-visibility"></span>
								<span class="badge-value">--</span>
							</span>
							<span class="metric-badge metric-badge-green" id="badge-4">
								<span class="dashicons dashicons-yes-alt"></span>
								<span class="badge-value">--</span>
							</span>
						</div>

						<button class="funnel-control-btn funnel-more-btn">
							<span class="dashicons dashicons-ellipsis"></span>
						</button>
					</div>
				</div>

				<!-- Funnel Steps Visualization -->
				<div class="funnel-steps-container">
					<div class="funnel-steps-label"><?php esc_html_e( 'Steps', 'opti-behavior' ); ?></div>

					<!-- Steps Header with Numbers and Names -->
					<div class="funnel-steps-header" id="funnel-steps-header">
						<!-- Will be populated by JavaScript -->
						<div class="funnel-loading">
							<span class="loading-spinner"></span>
							<span><?php esc_html_e( 'Loading funnel data...', 'opti-behavior' ); ?></span>
						</div>
					</div>

					<!-- Steps Chart Area -->
					<div class="funnel-steps-chart" id="funnel-steps-chart">
						<!-- Will be populated by JavaScript -->
					</div>

					<!-- Steps Metrics -->
					<div class="funnel-steps-metrics" id="funnel-steps-metrics">
						<!-- Will be populated by JavaScript -->
					</div>
				</div>

				<!-- Pagination -->
				<div class="funnel-pagination">
					<button class="pagination-btn" id="prev-page" disabled>
						<span class="dashicons dashicons-arrow-left-alt2"></span>
					</button>
					<button class="pagination-btn" id="next-page">
						<span class="dashicons dashicons-arrow-right-alt2"></span>
					</button>
				</div>
			</div>

			<!-- Funnel Builder Modal -->
			<div class="funnel-builder-modal" id="funnel-builder-modal" style="display: none;">
				<div class="funnel-builder-overlay"></div>
				<div class="funnel-builder-content">
					<div class="funnel-builder-header">
						<h2><?php esc_html_e( 'Build New Funnel', 'opti-behavior' ); ?></h2>
						<button class="funnel-builder-close" id="close-funnel-builder">
							<span class="dashicons dashicons-no-alt"></span>
						</button>
					</div>
					<div class="funnel-builder-body">
						<form id="funnel-builder-form">
							<div class="form-field">
								<label for="funnel-name"><?php esc_html_e( 'Funnel Name', 'opti-behavior' ); ?> <span class="required">*</span><?php opti_behavior_tooltip_e( $tooltips['funnel_name']['title'], $tooltips['funnel_name']['content'], $tooltips['funnel_name']['simple'], $tooltips['funnel_name']['example'], array( 'position' => 'right' ) ); ?></label>
								<input type="text" id="funnel-name" name="funnel_name" placeholder="<?php esc_attr_e( 'e.g., Purchase Journey', 'opti-behavior' ); ?>" required />
							</div>

							<div class="form-field">
								<label for="funnel-description"><?php esc_html_e( 'Description', 'opti-behavior' ); ?></label>
								<textarea id="funnel-description" name="funnel_description" placeholder="<?php esc_attr_e( 'Describe what this funnel tracks...', 'opti-behavior' ); ?>"></textarea>
							</div>

							<div class="form-field">
								<label><?php esc_html_e( 'Funnel Steps', 'opti-behavior' ); ?> <span class="required">*</span><?php opti_behavior_tooltip_e( $tooltips['funnel_steps']['title'], $tooltips['funnel_steps']['content'], $tooltips['funnel_steps']['simple'], $tooltips['funnel_steps']['example'], array( 'position' => 'right' ) ); ?></label>
								<div id="funnel-steps-container">
									<!-- Steps will be added here dynamically -->
									<div class="funnel-step-item" data-step="1">
										<div class="step-number">1</div>
										<div class="step-fields">
											<input type="text" class="step-name" placeholder="<?php esc_attr_e( 'Step name (e.g., Landing Page)', 'opti-behavior' ); ?>" required />
											<select class="step-match-type">
												<option value="any"><?php esc_html_e( 'Any Page', 'opti-behavior' ); ?></option>
												<option value="exact"><?php esc_html_e( 'Exact URL', 'opti-behavior' ); ?></option>
												<option value="contains"><?php esc_html_e( 'URL Contains', 'opti-behavior' ); ?></option>
												<option value="starts_with"><?php esc_html_e( 'URL Starts With', 'opti-behavior' ); ?></option>
												<option value="ends_with"><?php esc_html_e( 'URL Ends With', 'opti-behavior' ); ?></option>
												<option value="regex"><?php esc_html_e( 'Regex', 'opti-behavior' ); ?></option>
												<option value="pageview"><?php esc_html_e( 'Any Page View', 'opti-behavior' ); ?></option>
											</select>
											<input type="text" class="step-url-pattern" placeholder="<?php esc_attr_e( 'URL pattern (e.g., /cart)', 'opti-behavior' ); ?>" />
										</div>
										<button type="button" class="remove-step" style="display: none;">
											<span class="dashicons dashicons-trash"></span>
										</button>
									</div>
								</div>
								<button type="button" id="add-funnel-step" class="btn-add-step">
									<span class="dashicons dashicons-plus-alt"></span>
									<?php esc_html_e( 'Add Step', 'opti-behavior' ); ?>
								</button>
								<?php opti_behavior_tooltip_e( $tooltips['add_step']['title'], $tooltips['add_step']['content'], $tooltips['add_step']['simple'], $tooltips['add_step']['example'], array( 'position' => 'right' ) ); ?>
							</div>
						</form>
					</div>
					<div class="funnel-builder-footer">
						<button type="button" class="btn-cancel" id="cancel-funnel-builder"><?php esc_html_e( 'Cancel', 'opti-behavior' ); ?></button>
						<button type="button" class="btn-save-funnel" id="save-funnel-builder"><?php esc_html_e( 'Save Funnel', 'opti-behavior' ); ?></button>
					</div>
				</div>
			</div>
			</div><!-- .funnels-content-wrapper -->
		</div>
		<?php
	}

}
