<?php

/**

 * Manual Integration Test Script for SensFRX DB Helper

 * 

 * INSTRUCTIONS:

 * 1. Upload this file to your WordPress root directory

 * 2. Access it via browser: http://yourdomain.com/manual-test-script.php

 * 3. Review the test results

 * 4. DELETE this file after testing (security risk if left on server)

 * 

 * @package SensFRX

 */



// Security check - only run from localhost or with a secret key

$allowed = (

	$_SERVER['REMOTE_ADDR'] === '127.0.0.1' ||

	$_SERVER['REMOTE_ADDR'] === '::1' ||

	(isset($_GET['test_key']) && $_GET['test_key'] === 'sensfrx_test_2024')

);



if (!$allowed) {

	die('Access denied. Run from localhost or use ?test_key=sensfrx_test_2024');

}



// Load WordPress

require_once( dirname(__FILE__) . '/wp-load.php' );



// Load the DB Helper

require_once( dirname(__FILE__) . '/wp-content/plugins/sensfrx-fraud-prevention-for-woocommerce/includes/class-sensfrx-db-helper.php' );



// Start HTML output

?>

<!DOCTYPE html>

<html>

<head>

	<title>SensFRX DB Helper - Manual Test Results</title>

	<style>

		body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }

		.container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }

		h1 { color: #333; border-bottom: 3px solid #0073aa; padding-bottom: 10px; }

		h2 { color: #0073aa; margin-top: 30px; }

		.test { background: #f9f9f9; padding: 15px; margin: 10px 0; border-left: 4px solid #ccc; }

		.test.pass { border-left-color: #46b450; }

		.test.fail { border-left-color: #dc3232; background: #fee; }

		.test.warn { border-left-color: #ffb900; background: #fff5e5; }

		.result { font-weight: bold; padding: 5px 10px; border-radius: 3px; display: inline-block; }

		.pass .result { background: #46b450; color: white; }

		.fail .result { background: #dc3232; color: white; }

		.warn .result { background: #ffb900; color: black; }

		.code { background: #282c34; color: #abb2bf; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; overflow-x: auto; margin: 10px 0; }

		.summary { background: #0073aa; color: white; padding: 20px; border-radius: 8px; margin: 20px 0; }

		.summary h3 { margin-top: 0; }

		.summary-stats { display: flex; justify-content: space-around; margin-top: 15px; }

		.stat { text-align: center; }

		.stat-number { font-size: 32px; font-weight: bold; }

		.stat-label { font-size: 14px; opacity: 0.9; }

		pre { background: #f5f5f5; padding: 10px; border-radius: 4px; overflow-x: auto; }

		.info { background: #e7f3ff; border-left: 4px solid #0073aa; padding: 15px; margin: 20px 0; }

		.warning-box { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; }

	</style>

</head>

<body>

	<div class="container">

		<h1>🔒 SensFRX DB Helper - Manual Integration Tests</h1>

		<div class="info">

			<strong>⚠️ IMPORTANT:</strong> This test script is for development/testing only. 

			<strong style="color: #dc3232;">DELETE THIS FILE</strong> after testing for security reasons.

		</div>



<?php



$total_tests = 0;

$passed_tests = 0;

$failed_tests = 0;

$warnings = 0;



/**

 * Helper function to run a test and display results

 */

function run_test($test_name, $callable) {

	global $total_tests, $passed_tests, $failed_tests, $warnings;

	$total_tests++;

	

	echo '<div class="test ';

	

	try {

		$result = $callable();

		

		if ($result['status'] === 'pass') {

			echo 'pass">';

			echo '<span class="result">✓ PASS</span> ';

			$passed_tests++;

		} elseif ($result['status'] === 'fail') {

			echo 'fail">';

			echo '<span class="result">✗ FAIL</span> ';

			$failed_tests++;

		} else {

			echo 'warn">';

			echo '<span class="result">⚠ WARNING</span> ';

			$warnings++;

		}

		

		echo "<strong>{$test_name}</strong>";

		

		if (isset($result['message'])) {

			echo "<div style='margin-top: 10px;'>{$result['message']}</div>";

		}

		

		if (isset($result['data'])) {

			echo '<pre>' . print_r($result['data'], true) . '</pre>';

		}

		

	} catch (Exception $e) {

		echo 'fail">';

		echo '<span class="result">✗ ERROR</span> ';

		echo "<strong>{$test_name}</strong>";

		echo "<div style='margin-top: 10px; color: #dc3232;'>Exception: " . $e->getMessage() . "</div>";

		$failed_tests++;

	}

	

	echo '</div>';

}



echo '<h2>1. Environment Check</h2>';



run_test('WordPress Loaded', function() {

	return [

		'status' => defined('ABSPATH') ? 'pass' : 'fail',

		'message' => 'WordPress Version: ' . (defined('ABSPATH') ? get_bloginfo('version') : 'Not loaded')

	];

});



run_test('Plugin Active', function() {

	$active = is_plugin_active('sensfrx-fraud-prevention-for-woocommerce/sensfrx-fraud-prevention-for-woocommerce.php');

	return [

		'status' => $active ? 'pass' : 'fail',

		'message' => $active ? 'SensFRX plugin is active' : 'Plugin not active - activate it first'

	];

});



run_test('DB Helper Class Loaded', function() {

	return [

		'status' => class_exists('SensFRX_DB_Helper') ? 'pass' : 'fail',

		'message' => class_exists('SensFRX_DB_Helper') ? 'Class loaded successfully' : 'Class not found'

	];

});



echo '<h2>2. Database Connection</h2>';



run_test('WordPress Database Connection', function() {

	global $wpdb;

	$test = $wpdb->get_var("SELECT 1");

	return [

		'status' => ($test === '1') ? 'pass' : 'fail',

		'message' => "Database connected, prefix: {$wpdb->prefix}"

	];

});



echo '<h2>3. Table Validation Tests</h2>';



run_test('Valid Table Name (sensfrx_custome_filed)', function() {

	$table = SensFRX_DB_Helper::get_table_name('sensfrx_custome_filed');

	global $wpdb;

	$expected = $wpdb->prefix . 'sensfrx_custome_filed';

	return [

		'status' => ($table === $expected) ? 'pass' : 'fail',

		'message' => "Returned: {$table}"

	];

});



run_test('Invalid Table Name (malicious_table)', function() {

	$table = SensFRX_DB_Helper::get_table_name('malicious_table');

	return [

		'status' => ($table === false) ? 'pass' : 'fail',

		'message' => 'Invalid table correctly rejected'

	];

});



run_test('SQL Injection in Table Name', function() {

	$table = SensFRX_DB_Helper::get_table_name("users; DROP TABLE wp_users; --");

	return [

		'status' => ($table === false) ? 'pass' : 'fail',

		'message' => 'SQL injection attempt blocked'

	];

});



echo '<h2>4. Plugin Tables Exist</h2>';



$plugin_tables = [

	'sensfrx_sleep',

	'sensfrx_webhook_logout',

	'sensfrx_api_active_and_webhook',

	'sensfrx_tab_data',

	'sensfrx_custome_filed',

	'sensfrx_real_activity',

	'sensfrx_shadow_activity',

	'sensfrx_email_templates',

	'sensfrx_pre_payment_order',

];



foreach ($plugin_tables as $table_suffix) {

	run_test("Table exists: {$table_suffix}", function() use ($table_suffix) {

		global $wpdb;

		$table_name = $wpdb->prefix . $table_suffix;

		$exists = ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") === $table_name);

		return [

			'status' => $exists ? 'pass' : 'warn',

			'message' => $exists ? 'Table exists' : 'Table not found (may be created on first use)'

		];

	});

}



echo '<h2>5. Safe SELECT Query Test</h2>';



run_test('safe_select() - Query Custom Fields', function() {

	$results = SensFRX_DB_Helper::safe_select(

		'sensfrx_custome_filed',

		'id, sensfrx_custom_field',

		'',

		array(),

		'',

		ARRAY_A

	);

	

	return [

		'status' => is_array($results) ? 'pass' : 'fail',

		'message' => 'Query executed successfully, returned ' . (is_array($results) ? count($results) : 0) . ' rows',

		'data' => is_array($results) && count($results) > 0 ? array_slice($results, 0, 3) : 'No data'

	];

});



echo '<h2>6. SQL Injection Prevention Test</h2>';



run_test('SQL Injection in WHERE Clause', function() {

	global $wpdb;

	$before_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}sensfrx_custome_filed");

	

	// Attempt SQL injection

	$results = SensFRX_DB_Helper::safe_select(

		'sensfrx_custome_filed',

		'*',

		'sensfrx_custom_field = %s',

		array("'; DROP TABLE {$wpdb->prefix}sensfrx_custome_filed; --"),

		'',

		ARRAY_A

	);

	

	$after_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}sensfrx_custome_filed");

	

	return [

		'status' => ($before_count === $after_count) ? 'pass' : 'fail',

		'message' => "Table intact. Rows before: {$before_count}, after: {$after_count}. SQL injection blocked!"

	];

});



echo '<h2>7. Integration with Plugin Files</h2>';



run_test('DB Helper Used in Payment File', function() {

	$file = dirname(__FILE__) . '/wp-content/plugins/sensfrx-fraud-prevention-for-woocommerce/admin/class-sensfrx-payment.php';

	if (!file_exists($file)) {

		return ['status' => 'fail', 'message' => 'File not found'];

	}

	$content = file_get_contents($file);

	$count = substr_count($content, 'SensFRX_DB_Helper::safe_select');

	return [

		'status' => ($count > 0) ? 'pass' : 'fail',

		'message' => "Found {$count} safe_select() calls in payment file"

	];

});



run_test('DB Helper Used in Webhook File', function() {

	$file = dirname(__FILE__) . '/wp-content/plugins/sensfrx-fraud-prevention-for-woocommerce/admin/class-sensfrx-webhook.php';

	if (!file_exists($file)) {

		return ['status' => 'fail', 'message' => 'File not found'];

	}

	$content = file_get_contents($file);

	$count = substr_count($content, 'SensFRX_DB_Helper::safe_select');

	return [

		'status' => ($count > 0) ? 'pass' : 'fail',

		'message' => "Found {$count} safe_select() calls in webhook file"

	];

});



echo '<h2>8. Security Sanitization Tests</h2>';



run_test('Column Name Sanitization', function() {

	// This test verifies the helper handles invalid columns gracefully

	$results = SensFRX_DB_Helper::safe_select(

		'sensfrx_custome_filed',

		'invalid_column_that_does_not_exist',

		'',

		array(),

		'',

		ARRAY_A

	);

	

	return [

		'status' => is_array($results) ? 'pass' : 'fail',

		'message' => 'Invalid column handled gracefully (no fatal error)'

	];

});



run_test('ORDER BY Sanitization', function() {

	$results = SensFRX_DB_Helper::safe_select(

		'sensfrx_custome_filed',

		'*',

		'',

		array(),

		'id; DELETE FROM users',  // Malicious ORDER BY

		ARRAY_A

	);

	

	return [

		'status' => is_array($results) ? 'pass' : 'fail',

		'message' => 'Malicious ORDER BY sanitized/rejected, query still succeeded'

	];

});



// Summary

$success_rate = $total_tests > 0 ? round(($passed_tests / $total_tests) * 100, 1) : 0;



?>



		<div class="summary">

			<h3>📊 Test Summary</h3>

			<div class="summary-stats">

				<div class="stat">

					<div class="stat-number"><?php echo $total_tests; ?></div>

					<div class="stat-label">Total Tests</div>

				</div>

				<div class="stat">

					<div class="stat-number"><?php echo $passed_tests; ?></div>

					<div class="stat-label">Passed ✓</div>

				</div>

				<div class="stat">

					<div class="stat-number"><?php echo $failed_tests; ?></div>

					<div class="stat-label">Failed ✗</div>

				</div>

				<div class="stat">

					<div class="stat-number"><?php echo $warnings; ?></div>

					<div class="stat-label">Warnings ⚠</div>

				</div>

				<div class="stat">

					<div class="stat-number"><?php echo $success_rate; ?>%</div>

					<div class="stat-label">Success Rate</div>

				</div>

			</div>

		</div>



		<?php if ($failed_tests > 0): ?>

			<div class="warning-box">

				<strong>⚠️ Some tests failed.</strong> Review the failed tests above and fix any issues before deploying to production.

			</div>

		<?php else: ?>

			<div class="test pass" style="font-size: 18px; padding: 20px;">

				<strong>✓ All critical tests passed!</strong> Your SensFRX DB Helper implementation is working correctly. 

				You can proceed with additional manual testing or move to Phase 5 (Standards Compliance).

			</div>

		<?php endif; ?>



		<div class="info">

			<strong>Next Steps:</strong>

			<ol>

				<li>Review the test results above</li>

				<li>If all tests passed, manually test critical workflows (orders, registration, login)</li>

				<li>Check WordPress debug log for any PHP errors</li>

				<li><strong style="color: #dc3232;">DELETE THIS FILE (manual-test-script.php)</strong> - it's a security risk!</li>

				<li>If everything works, proceed to Phase 5: Standards Compliance</li>

			</ol>

		</div>



		<div class="code">

			Test completed at: <?php echo date('Y-m-d H:i:s'); ?><br>

			WordPress Version: <?php echo get_bloginfo('version'); ?><br>

			PHP Version: <?php echo PHP_VERSION; ?><br>

			Database Prefix: <?php echo $GLOBALS['wpdb']->prefix; ?>

		</div>

	</div>

</body>

</html>

<?php



// End of script



