<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( 'You are not allowed to call this page directly.' );
}

// WP_List_Table is not loaded automatically so we need to load it in our application
if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}

/**
 * Create the Protected Forms table class that will extend the WP_List_Table
 */
class FormShieldProtectedFormsListTable extends WP_List_Table {
	/**
	 * No bulk actions needed - forms are managed individually
	 *
	 * @return Array
	 */
	public function get_bulk_actions() {
		return array(); // No bulk actions
	}

	/**
	 * Process the bulk actions
	 *
	 * @return Void
	 */
	public function process_bulk_action() {
		$nonce = formshield_get_get_string('_wpnonce');
		$nonce_die_msg = '<div class="notice notice-error below-h2"><p><strong>Error:</strong> Invalid nonce value detected.</p></div>';

		if ( formshield_get_get_string('id') ) {
			// Verify the request nonce
			if ( ! wp_verify_nonce( $nonce, 'fm_action_nonce' ) ) {
				// Handle invalid nonce value
				wp_die( esc_html( $nonce_die_msg ) );
			}

		// Handle individual Enable/Disable actions
		$fid = formshield_get_get_string('id');
		$enabled    = 0;
		$alert_type = 'warning';

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WordPress List Table current_action() method handles bulk actions
		if ( $this->current_action() === 'enable' ) {
			$enabled    = 1;
			$alert_type = 'success';
		}

			// Show admin notice
			FormShieldForms::show_protected_forms_admin_notice( $fid, $enabled, $alert_type );
			// Enable the form to be protected
			FormShieldForms::enable_forms( $fid, $enabled );
		} elseif ( formshield_get_get_string('bulk-enable') ) {
			// Verify the nonce generated by the bulk actions menu
			if ( ! wp_verify_nonce( $nonce, 'bulk-' . $this->_args['plural'] ) ) {
				// Handle invalid nonce value
				wp_die( esc_html( $nonce_die_msg ) );
			}

		// Handle Bulk Enable/Disable actions
		$enabled    = 0;
		$alert_type = 'warning';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WordPress List Table current_action() method handles bulk actions
		if ( $this->current_action() === 'enable' ) {
			$enabled    = 1;
			$alert_type = 'success';
		}

			// Handle Bulk Enable/Disable actions
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading parameter from list table UI, not changing privileges here
			$bulk_enable = isset( $_GET['bulk-enable'] )
				? array_values( array_filter( array_map( 'absint', (array) wp_unslash( $_GET['bulk-enable'] ) ) ) )
				: array();

			if ( is_array( $bulk_enable ) && count( $bulk_enable ) > 1 ) {
				// Handle Multiple IDs
				foreach ( $bulk_enable as $fid ) {
					if ( $fid ) {
						FormShieldForms::show_protected_forms_admin_notice( $fid, $enabled, $alert_type );
						FormShieldForms::enable_forms( $fid, $enabled );
					}
				}
			} else {
				$fid = ! empty( $bulk_enable ) ? (int) $bulk_enable[0] : 0;
				if ( $fid ) {
					FormShieldForms::show_protected_forms_admin_notice( $fid, $enabled, $alert_type );
					FormShieldForms::enable_forms( $fid, $enabled );
				}
			}
		}
	}

	/**
	 * Prepare the items for the table to process
	 *
	 * @return Void
	 */
	public function prepare_items() {
		$columns  = $this->get_columns();
		$hidden   = $this->get_hidden_columns();
		$sortable = $this->get_sortable_columns();
		
		$data     = FormShieldForms::get_forms();
		usort( $data, array( &$this, 'sort_data' ) );
		$perPage     = 10;
		$currentPage = $this->get_pagenum();
		$totalItems  = count( $data );

		$this->set_pagination_args(
			array(
				'total_items' => $totalItems,
				'per_page'    => $perPage
			)
		);

		/** Process bulk action */
		$this->process_bulk_action();

		$data                  = array_slice( $data, ( ( $currentPage - 1 ) * $perPage ), $perPage );
		$this->_column_headers = array( $columns, $hidden, $sortable );
		$this->items           = $data;
	}

	/**
	 * Override the parent columns method. Defines the columns to use in your listing table
	 *
	 * @return Array
	 */
	// ID | Enable | Name | Type | Submissions(Human, Suspicious, Total) | Activity
	public function get_columns() {
		$columns = array(
			'enabled'     => 'Enabled',
			'location'    => 'Location',
			'type'        => 'Type',
			'blocked'     => 'Blocked Attempts',
			'submissions' => 'Submissions',
			'activity'    => 'Activity'
		);

		return $columns;
	}

	/**
	 * Define which columns are hidden
	 *
	 * @return Array
	 */
	public function get_hidden_columns() {
		return array();
	}

	/**
	 * Define the sortable columns
	 *
	 * @return Array
	 */
	public function get_sortable_columns() {
		return array(
			'location' => array( 'location', false ),
			'type' => array( 'type', false ),
			'blocked' => array( 'blocked', false )
		);
	}

	/**
	 * Method for location column with navigation icon
	 *
	 * @param Array $item an array of column data
	 *
	 * @return String
	 */
	public function column_location( $item ) {
		$location_text = '';
		$navigation_link = '';
		
		// Get location text
		if ( isset( $item['location'] ) ) {
			$location_text = $item['location'];
		} else {
			$location_text = 'N/A';
		}
		
		// Create navigation link if we have page/post ID
		if ( isset( $item['page_id'] ) && !empty( $item['page_id'] ) ) {
			$page_url = get_permalink( $item['page_id'] );
			$navigation_link = sprintf(
				' <a href="%s" target="_blank" title="%s" style="text-decoration: none; margin-left: 8px;">
					<span style="color: #0073aa; font-size: 16px;">🔍</span>
				</a>',
				esc_url( $page_url ),
				esc_attr__('View form page', 'formshield')
			);
		} elseif ( isset( $item['id'] ) && strpos( $item['id'], 'divi' ) !== false ) {
			// For Divi forms, try to extract page ID from the form ID
			$page_id = str_replace( 'divi_', '', $item['id'] );
			if ( is_numeric( $page_id ) ) {
				$page_url = get_permalink( $page_id );
				$navigation_link = sprintf(
					' <a href="%s" target="_blank" title="%s" style="text-decoration: none; margin-left: 8px;">
						<span style="color: #0073aa; font-size: 16px;">🔍</span>
					</a>',
					esc_url( $page_url ),
					esc_attr__('View form page', 'formshield')
				);
			}
		} elseif ( isset( $item['id'] ) && strpos( $item['id'], 'cf7_' ) !== false ) {
			// For Contact Form 7, try to find where it's used
			$form_id = str_replace( 'cf7_', '', $item['id'] );
			
			$page_url = $this->find_contact_form_7_page( $form_id );
			
			if ( $page_url ) {
				$navigation_link = sprintf(
					' <a href="%s" target="_blank" title="%s" style="text-decoration: none; margin-left: 8px;">
						<span style="color: #0073aa; font-size: 16px;">🔍</span>
					</a>',
					esc_url( $page_url ),
					esc_attr__('View form page', 'formshield')
				);
			} else {
				// Form is not used anywhere - no warning, just no link
				$navigation_link = '';
			}
		} elseif ( isset( $item['id'] ) && strpos( $item['id'], 'wpforms_' ) !== false ) {
			// For WPForms, try to find where it's used
			$form_id = str_replace( 'wpforms_', '', $item['id'] );
			
			$page_url = $this->find_wpforms_page( $form_id );
			
			if ( $page_url ) {
				$navigation_link = sprintf(
					' <a href="%s" target="_blank" title="%s" style="text-decoration: none; margin-left: 8px;">
						<span style="color: #0073aa; font-size: 16px;">🔍</span>
					</a>',
					esc_url( $page_url ),
					esc_attr__('View form page', 'formshield')
				);
			} else {
				// Form is not used anywhere - no warning, just no link
				$navigation_link = '';
			}
		} elseif ( isset( $item['id'] ) && strpos( $item['id'], 'gravity_' ) !== false ) {
			// For Gravity Forms, try to find where it's used
			$form_id = str_replace( 'gravity_', '', $item['id'] );
			
			$page_url = $this->find_gravity_forms_page( $form_id );
			
			if ( $page_url ) {
				$navigation_link = sprintf(
					' <a href="%s" target="_blank" title="%s" style="text-decoration: none; margin-left: 8px;">
						<span style="color: #0073aa; font-size: 16px;">🔍</span>
					</a>',
					esc_url( $page_url ),
					esc_attr__('View form page', 'formshield')
				);
			} else {
				// Form is not used anywhere - no warning, just no link
				$navigation_link = '';
			}
		} elseif ( isset( $item['id'] ) && strpos( $item['id'], 'ninja_' ) !== false ) {
			// For Ninja Forms, try to find where it's used
			$form_id = str_replace( 'ninja_', '', $item['id'] );
			
			$page_url = $this->find_ninja_forms_page( $form_id );
			
			if ( $page_url ) {
				$navigation_link = sprintf(
					' <a href="%s" target="_blank" title="%s" style="text-decoration: none; margin-left: 8px;">
						<span style="color: #0073aa; font-size: 16px;">🔍</span>
					</a>',
					esc_url( $page_url ),
					esc_attr__('View form page', 'formshield')
				);
			} else {
				// Form is not used anywhere - no warning, just no link
				$navigation_link = '';
			}
		}
		
		// Add statistics button
		$stats_button = sprintf(
			' <button type="button" class="formshield-stats-btn" data-form-id="%s" title="View Form Statistics">
				<span style="color: #3498db; font-size: 14px;">📊</span>
			</button>',
			esc_attr( $item['id'] )
		);
		
		return '<div class="location-info">' . 
			   '<strong>' . esc_html( $location_text ) . '</strong>' . 
			   $navigation_link . 
			   $stats_button . 
			   '</div>';
	}



	/**
	 * Render the type column
	 *
	 * @param Array $item
	 *
	 * @return String
	 */
	public function column_type( $item ) {
		$type = isset( $item['type'] ) ? $item['type'] : 'Unknown';
		
		// Add icon based on form type
		$icon = $this->get_form_type_icon( $type );
		
		return sprintf(
			'<div class="form-type">
				<span class="type-icon">%s</span>
				<span class="type-text">%s</span>
			</div>',
			$icon,
			esc_html( $type )
		);
	}

	/**
	 * Get form type icon
	 *
	 * @param String $type
	 *
	 * @return String
	 */
	private function get_form_type_icon( $type ) {
		$icons = array(
			'contact' => '📧',
			'divi' => '🎨',
			'divi contact form' => '🎨',
			'contact-form-7' => '📝',
			'скенер' => '🔍',
			'contact form 7' => '📝',
			'ninja-forms' => '🥷',
			'ninja forms' => '🥷',
			'gravity-forms' => '⚖️',
			'gravity forms' => '⚖️',
			'wpforms' => '📋',
			'wp forms' => '📋',
			'elementor' => '🔧',
			'custom' => '⚙️',
			'wordpress comments' => '💬',
			'comments' => '💬',
			'form-detector' => '🔍',
			'form detector' => '🔍',
			'unknown' => '❓'
		);
		
		$type_lower = strtolower( trim( $type ) );
		
		// Check exact match first
		if ( isset( $icons[ $type_lower ] ) ) {
			return $icons[ $type_lower ];
		}
		
		// Check partial matches
		foreach ( $icons as $key => $icon ) {
			if ( strpos( $type_lower, $key ) !== false ) {
				return $icon;
			}
		}
		
		return $icons['unknown'];
	}

	/**
	 * Render the enabled column with toggle switch
	 *
	 * @param Array $item
	 *
	 * @return String
	 */
	public function column_enabled( $item ) {
		$enabled = isset( $item['enabled'] ) ? $item['enabled'] : 0;
		$form_id = isset( $item['id'] ) ? $item['id'] : '';
		
		$toggle_id = 'formshield-toggle-' . $form_id;
		
		$html = '<div class="formshield-toggle-wrapper">';
		$html .= '<label class="switch">';
		$html .= '<input type="checkbox" id="' . esc_attr($toggle_id) . '" class="formshield-toggle" data-form-id="' . esc_attr($form_id) . '" ' . checked($enabled, 1, false) . '>';
		$html .= '<span class="slider round"></span>';
		$html .= '</label>';
		$html .= '<span class="toggle-status ' . ($enabled ? 'enabled' : 'disabled') . '">';
		$html .= $enabled ? 'Enabled' : 'Disabled';
		$html .= '</span>';
		$html .= '</div>';
		
		return $html;
	}

	/**
	 * Render the blocked attempts column
	 *
	 * @param Array $item
	 *
	 * @return String
	 */
	public function column_blocked( $item ) {
		$blocked_count = isset( $item['blocked_attempts'] ) ? intval( $item['blocked_attempts'] ) : 0;
		
		if ( $blocked_count > 0 ) {
			return sprintf(
				'<span class="blocked-count" style="background: #e74c3c; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px; font-weight: bold;">%d</span>',
				$blocked_count
			);
		} else {
			return '<span class="no-blocked" style="color: #95a5a6; font-size: 12px;">0</span>';
		}
	}

	/**
	 * Render the submissions column
	 *
	 * @param Array $item
	 *
	 * @return String
	 */
	public function column_submissions( $item ) {
		$total_submissions = isset( $item['total_submissions'] ) ? intval( $item['total_submissions'] ) : 0;
		$human_submissions = isset( $item['human_submissions'] ) ? intval( $item['human_submissions'] ) : 0;
		$suspicious_submissions = isset( $item['suspicious_submissions'] ) ? intval( $item['suspicious_submissions'] ) : 0;
		
		if ( $total_submissions > 0 ) {
			$html = '<div class="submissions-stats">';
			$html .= '<div class="stat-item">';
			$html .= '<span class="stat-label">Total:</span>';
			$html .= '<span class="stat-value total">' . esc_html( $total_submissions ) . '</span>';
			$html .= '</div>';
			
			if ( $human_submissions > 0 ) {
				$html .= '<div class="stat-item">';
				$html .= '<span class="stat-label">Human:</span>';
				$html .= '<span class="stat-value human">' . esc_html( $human_submissions ) . '</span>';
				$html .= '</div>';
			}
			
			if ( $suspicious_submissions > 0 ) {
				$html .= '<div class="stat-item">';
				$html .= '<span class="stat-label">Suspicious:</span>';
				$html .= '<span class="stat-value suspicious">' . esc_html( $suspicious_submissions ) . '</span>';
				$html .= '</div>';
			}
			
			$html .= '</div>';
			return $html;
		} else {
			return '<span class="no-submissions" style="color: #95a5a6; font-size: 12px;">No submissions yet</span>';
		}
	}

	/**
	 * Render the activity column
	 *
	 * @param Array $item
	 *
	 * @return String
	 */
	public function column_activity( $item ) {
		$last_activity = isset( $item['last_activity'] ) ? $item['last_activity'] : '';
		$activity_type = isset( $item['activity_type'] ) ? $item['activity_type'] : '';
		
		if ( $last_activity ) {
			$html = '<div class="activity-info">';
			$html .= '<div class="activity-time">' . esc_html( $last_activity ) . '</div>';
			
			if ( $activity_type ) {
				$icon = $this->get_activity_icon( $activity_type );
				$html .= '<div class="activity-type">';
				$html .= '<span class="activity-icon">' . $icon . '</span>';
				$html .= '<span class="activity-text">' . esc_html( $activity_type ) . '</span>';
				$html .= '</div>';
			}
			
			$html .= '</div>';
			return $html;
		} else {
			return '<span class="no-activity" style="color: #95a5a6; font-size: 12px;">No activity</span>';
		}
	}

	/**
	 * Get activity icon based on activity type
	 *
	 * @param String $activity_type
	 *
	 * @return String
	 */
	private function get_activity_icon( $activity_type ) {
		$icons = array(
			'submission' => '📝',
			'attack_blocked' => '🚫',
			'form_accessed' => '👁️',
			'protection_enabled' => '🛡️',
			'protection_disabled' => '⚠️',
			'error' => '❌',
			'warning' => '⚠️',
			'info' => 'ℹ️'
		);
		
		return isset( $icons[ $activity_type ] ) ? $icons[ $activity_type ] : '📊';
	}
	

	

	
	
	

	
	/**
	 * Render the bulk enable checkbox
	 *
	 * @param Array $item
	 *
	 * @return String
	 */
	public function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="bulk-enable[]" value="%s" />', $item['id']
		);
	}

	/**
	 * Define what data to show on each column of the table
	 *
	 * @param  Array $item Data
	 * @param  String $column_name - Current column name
	 *
	 * @return Mixed
	 */
	public function column_default( $item, $column_name ) {
		switch ( $column_name ) {
			case 'enabled':
			case 'type':
			case 'blocked':
				return $item[ $column_name ];
			case 'submissions':
				return $this->column_submissions( $item );
			case 'activity':
				return $this->column_activity( $item );
		default:
			return '';
		}
	}

	/**
	 * Allows you to sort the data by the variables set in the $_GET
	 *
	 * @return Mixed
	 */
	private function sort_data( $a, $b ) {
		// Set defaults
		$orderby = 'location';
		$order   = 'asc';

		// If orderby is set, use this as the sort column
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- reading admin navigation param only
		$orderby_input = isset( $_GET['orderby'] ) ? sanitize_key( wp_unslash( $_GET['orderby'] ) ) : '';
		if ( ! empty( $orderby_input ) ) {
			$orderby = $orderby_input;
		}

		// If order is set use this as the order
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- reading admin navigation param only
		$order_input = isset( $_GET['order'] ) ? sanitize_key( wp_unslash( $_GET['order'] ) ) : '';
		if ( ! empty( $order_input ) ) {
			$order = in_array( strtolower( $order_input ), array( 'asc', 'desc' ) ) ? strtolower( $order_input ) : 'asc';
		}

		$result = strcmp( $a[ $orderby ], $b[ $orderby ] );

		if ( 'asc' === $order ) {
			return $result;
		}

		return - $result;
	}

	public static function display_protected_forms_table() {
		$protected_forms_table = new self();
		$protected_forms_table->prepare_items();
		
		// Check if there are any forms to display
		if ($protected_forms_table->items && count($protected_forms_table->items) > 0) {
			$protected_forms_table->display();
		} else {
			// Show message when no forms are detected
			echo '<div class="formshield-no-forms-message">';
			echo '<div class="no-forms-content">';
			echo '<div class="no-forms-icon">🔍</div>';
			echo '<h3>Няма открити форми</h3>';
			echo '<p>Все още не са открити форми на вашия сайт. Използвайте бутоните по-горе за да сканирате за форми.</p>';
			echo '<div class="no-forms-actions">';
			echo '<button type="button" class="button button-primary" id="scan-forms-btn">🔍 Сканирай за форми</button>';
			echo '<button type="button" class="button button-secondary" id="rescan-forms-btn">🔄 Пресканирай всички</button>';
			echo '</div>';
			echo '</div>';
			echo '</div>';
		}
	}
}
