<?php
/**
 * DVC Listings Notifier - OPTIMIZED VERSION
 * 
 * PERFORMANCE IMPROVEMENTS:
 * - Bulk database queries instead of N+1 queries
 * - Comprehensive New Relic monitoring
 * - Execution time and memory limits
 * - Detailed performance metrics
 *
 * @package DVC
 * @version 2.2.0-optimized
 */

require_once '../../../wp-load.php';
require_once __DIR__ . '/classes/class-notifier-v3.php';

// OPTIMIZATION: Set execution limits
set_time_limit(300); // 5 minutes max
ini_set('memory_limit', '512M'); // Increase memory limit
ini_set('max_execution_time', 300);

$settings = array(
	'sparkpost_key' => '9d6c56193f3be74ecea12ddd7247c57e7a4dc6a1',
	'timeout'       => 20,
	'unsubscribe'   => 'https://www.dvcresalemarket.com/unsubscribe/',
	'salt'          => 'adlfj3kniuherna9j34l2j43',
	'debug'         => isset($_GET['debug']) ? true : false,
	'tables'        => array(
		'posts_table'    => 'wp_hmrb_posts',
		'meta_table'     => 'wp_hmrb_postmeta',
		'term_table'     => 'wp_hmrb_terms',
		'term_tax_table' => 'wp_hmrb_term_taxonomy',
	),
	'log'           => array(
		'uri' => __DIR__ . '/logs/',
	),
	'execution'     => array(
		'time_limit'   => 300,
		'memory_limit' => '512M',
		'batch_size'   => 50,
	),
);

// Add execution monitoring
$start_time = microtime(true);
$start_memory = memory_get_usage();

if (function_exists('\newrelic_name_transaction')) {
	\newrelic_name_transaction('DVCNotifier/Main/EntryPoint');
}

if (function_exists('\newrelic_add_custom_parameter')) {
	\newrelic_add_custom_parameter('entry_point_memory', $start_memory);
	\newrelic_add_custom_parameter('entry_point_time_limit', ini_get('max_execution_time'));
	\newrelic_add_custom_parameter('entry_point_memory_limit', ini_get('memory_limit'));
}

try {
	$notifier = new DVCNotifier\Notifier_V2($settings);
	$notifier->start();
	
	$success = true;
} catch (Exception $e) {
	if (function_exists('\newrelic_notice_error')) {
		\newrelic_notice_error($e->getMessage(), $e);
	}
	error_log('DVC Notifier Error: ' . $e->getMessage());
	$success = false;
}

$execution_time = microtime(true) - $start_time;
$memory_used = memory_get_peak_usage() - $start_memory;

if (function_exists('\newrelic_add_custom_parameter')) {
	\newrelic_add_custom_parameter('entry_point_execution_time', $execution_time);
	\newrelic_add_custom_parameter('entry_point_memory_used', $memory_used);
	\newrelic_add_custom_parameter('entry_point_success', $success ? 1 : 0);
}

// Log execution summary
error_log(sprintf(
	'DVC Notifier completed in %.2fs using %.2fMB memory. Success: %s',
	$execution_time,
	$memory_used / 1024 / 1024,
	$success ? 'YES' : 'NO'
));
