<?php
// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


/**
 * Create the email logs table in the database.
 *
 * Creates the table structure for storing email logs including
 * email type, recipient, subject, message, status, and timestamp.
 *
 * @since 1.0.0
 */
function x4email_lite_create_logs_table() {
	global $wpdb;

	$table_name      = $wpdb->prefix . 'x4email_logs_lite';
	$charset_collate = $wpdb->get_charset_collate();

	$sql = "CREATE TABLE $table_name (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        mail_type VARCHAR(255) NOT NULL,
        recipient_email VARCHAR(255) NOT NULL,
        subject VARCHAR(255) NOT NULL,
        message LONGTEXT NOT NULL,
        status VARCHAR(50) NOT NULL,
        error_log TEXT NOT NULL,
        sent_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

	require_once ABSPATH . 'wp-admin/includes/upgrade.php';
	dbDelta( $sql );
}

add_action( 'admin_enqueue_scripts', 'x4email_enqueue_logs_assets' );

/**
 * Enqueue logs page assets.
 *
 * Loads CSS and JavaScript files specific to the logs page,
 * including AJAX configuration for log management.
 *
 * @since 1.0.0
 */
function x4email_enqueue_logs_assets() {
	// Check if we're on the logs page.
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin page parameter check, no form processing.
	if ( ! isset( $_GET['page'] ) || $_GET['page'] !== 'x4email-logs' ) {
		return;
	}

	wp_enqueue_style( 'x4email-logs-css', esc_url( plugins_url( 'assets/css/logs.css', dirname( __DIR__ ) ) ), array(), X4EMAIL_LITE_VER );
	wp_enqueue_script( 'x4email-logs-js', esc_url( plugins_url( 'assets/js/logs.js', dirname( __DIR__ ) ) ), array( 'jquery' ), X4EMAIL_LITE_VER, true );

	// Add nonce for AJAX requests.
	wp_localize_script(
		'x4email-logs-js',
		'x4email_logs',
		array(
			'nonce'   => wp_create_nonce( 'x4email_logs_nonce' ),
			'ajaxurl' => admin_url( 'admin-ajax.php' ),
		)
	);
}

/**
 * Display the email logs page.
 *
 * Renders the email logs interface with filtering, search,
 * and management capabilities for email delivery tracking.
 *
 * @since 1.0.0
 */
function x4email_logs_page() {
	wp_enqueue_style( 'x4email-admin-modern', plugins_url( 'assets/css/admin-modern.css', dirname( __DIR__ ) ), array(), X4EMAIL_LITE_VER );
	// Check if user has required capabilities.
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'x4email-lite' ) );
	}

	global $wpdb;
	$table_name = $wpdb->prefix . 'x4email_logs_lite';

	// Fetch logs with proper escaping and caching.
	$cache_key = 'x4email_logs_' . get_current_user_id();
	$logs      = wp_cache_get( $cache_key, 'x4email' );

	if ( false === $logs ) {
		// Validate table name exists and use direct query with proper escaping.
		$escaped_table_name = esc_sql( $table_name );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table query needed for plugin functionality.
		$logs = $wpdb->get_results(
			$wpdb->prepare(
      // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name cannot be prepared, but is properly escaped.
				"SELECT * FROM `$escaped_table_name` ORDER BY sent_at DESC LIMIT %d",
				100 // Limit results for performance
			)
		);

		// Cache results for 5 minutes.
		wp_cache_set( $cache_key, $logs, 'x4email', 300 );
	}

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is verified below before processing form data.
	if ( isset( $_POST['clear_logs'] ) ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Input is sanitized and nonce verified immediately below.
		$nonce_field = isset( $_POST['x4email_clear_logs_nonce_field'] ) ? sanitize_text_field( wp_unslash( $_POST['x4email_clear_logs_nonce_field'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce_field, 'x4email_clear_logs_nonce' ) ) {
			wp_die( esc_html__( 'Security check failed. Please try again.', 'x4email-lite' ) );
		}

		// Clear all logs from the database.
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name cannot be prepared.
		$wpdb->query( "TRUNCATE TABLE {$table_name}" );

		// Clear the logs cache.
		$cache_key = 'x4email_logs_' . get_current_user_id();
		wp_cache_delete( $cache_key, 'x4email' );

        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Only logs in debug mode.
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Conditional debug logging.
			error_log(
				sprintf(
					'X4Email: Logs cleared by user %s',
					get_current_user_id()
				)
			);
		}

		// Redirect to the logs page with a success message.
		wp_safe_redirect( add_query_arg( 'cleared', 'true', admin_url( 'admin.php?page=x4email-logs' ) ) );
		exit;
	}

	// Display success message if logs were cleared.
	if ( isset( $_GET['cleared'] ) && $_GET['cleared'] === 'true' ) {
		echo '<div class="notice notice-success is-dismissible"><p>' .
			esc_html__( 'All logs have been cleared successfully.', 'x4email-lite' ) .
			'</p></div>';
	}
	?>
<div class="x4email-admin" style="min-height:100vh; background: var(--color-bg); padding: 2.5rem 0;">
	<div style="max-width: 1200px; margin: 0 auto;">
	<div class="x4email-title" style="display:flex;align-items:center;justify-content:space-between;gap:0.75em;flex-direction:row;">
		<div style="display:flex;flex-direction:column;align-items:flex-start;">
		<h1 style="color:#fff;">EMAIL LOGS</h1>
		<span style="font-size:1rem;color:#fff;opacity:0.9;margin-top:0.25em;letter-spacing:0.01em;">View your outgoing email logs. Filtering and advanced features are available in Pro.</span>
		</div>
		<span style="font-size:3.5em;opacity:0.95;line-height:1;display:flex;align-items:center;justify-content:center;"><svg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='white' stroke-width='2' width='48' height='48'><path stroke-linecap='round' stroke-linejoin='round' d='M15.75 9V5.25A2.25 2.25 0 0 0 13.5 3h-3A2.25 2.25 0 0 0 8.25 5.25V9m10.5 0v9A2.25 2.25 0 0 1 16.5 20.25h-9A2.25 2.25 0 0 1 5.25 18V9m13.5 0H5.25m13.5 0a2.25 2.25 0 0 0-2.25-2.25H6.75A2.25 2.25 0 0 0 4.5 9'/></svg></span>
	</div>
	<div class="x4email-card x4email-box-shadow x4email-mb-lg" style="margin-top:2.5rem;">
		<div style="position:relative;margin-bottom: 20px;display:flex;align-items:center;gap:1rem;filter: blur(2px); pointer-events: none; opacity: 0.7;">
		<form method="post" style="margin:0;">
			<?php wp_nonce_field( 'x4email_clear_logs_nonce', 'x4email_clear_logs_nonce_field' ); ?>
			<button type="submit" name="clear_logs" class="x4email-btn-outline" disabled>
			<svg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='currentColor' stroke-width='2' width='20' height='20' style='vertical-align:middle;margin-right:6px;'><path stroke-linecap='round' stroke-linejoin='round' d='M6 18L18 6M6 6l12 12'/></svg>
			<?php echo esc_html__( 'Clear Logs', 'x4email-lite' ); ?>
			</button>
		</form>
	 
		</div>
		<div style="position:relative;">
		<form method="get" style="margin-bottom: 20px;display:flex;flex-wrap:wrap;align-items:center;gap:1rem;filter: blur(2px); pointer-events: none; opacity: 0.7;">
			<input type="hidden" name="page" value="x4email-logs">
			<input type="text" name="s" value="" placeholder="<?php echo esc_attr__( 'Search logs...', 'x4email-lite' ); ?>" class="x4email-input" style="max-width:180px;" disabled>
			<input type="date" name="date" value="" placeholder="<?php echo esc_attr__( 'Filter by date', 'x4email-lite' ); ?>" class="x4email-input" style="max-width:140px;" disabled>
			<select name="type" class="x4email-input" style="max-width:160px;" disabled>
			<option value=""><?php echo esc_html__( 'All Types', 'x4email-lite' ); ?></option>
			<option value="Security"><?php echo esc_html__( 'Security Emails', 'x4email-lite' ); ?></option>
			<option value="Test Mail"><?php echo esc_html__( 'Test Mail', 'x4email-lite' ); ?></option>
			<option value="WooCommerce"><?php echo esc_html__( 'WooCommerce', 'x4email-lite' ); ?></option>
			</select>
			<select name="status" class="x4email-input" style="max-width:140px;" disabled>
			<option value=""><?php echo esc_html__( 'All Status', 'x4email-lite' ); ?></option>
			<option value="Successful"><?php echo esc_html__( 'Successful', 'x4email-lite' ); ?></option>
			<option value="Failed"><?php echo esc_html__( 'Failed', 'x4email-lite' ); ?></option>
			</select>
			<button type="submit" class="x4email-btn-outline" disabled><?php echo esc_html__( 'Filter', 'x4email-lite' ); ?></button>
			<a href="#" class="x4email-btn-outline" style="pointer-events: none; opacity: 0.5;"><?php echo esc_html__( 'Clear Filters', 'x4email-lite' ); ?></a>
		</form>
		<div style="position:absolute;top:0;left:0;width:100%;height:100%;display:flex;align-items:center;justify-content:center;z-index:2;pointer-events:auto;">
			<span style="background:rgba(255,255,255,0.95);padding:0.75em 1.5em;border-radius:8px;font-size:1.1em;color:#1976d2;font-weight:600;box-shadow:0 2px 8px 0 rgba(25,118,210,0.10);">
			<?php echo esc_html__( 'Upgrade to Pro to unlock log filtering and clearing features!', 'x4email-lite' ); ?>
			</span>
		</div>
		</div>
		<div class="x4email-table-scrollbar x4email-table-scrollbar-top"></div>
		<div class="x4email-table-responsive">
		<table>
			<thead> 
			<tr>
				<th style="width:32px;"></th>
				<th><?php echo esc_html__( 'ID', 'x4email-lite' ); ?></th>
				<th><?php echo esc_html__( 'Mail Type', 'x4email-lite' ); ?></th>
				<th><?php echo esc_html__( 'Recipient', 'x4email-lite' ); ?></th>
				<th><?php echo esc_html__( 'Subject', 'x4email-lite' ); ?></th>
				<th><?php echo esc_html__( 'Status', 'x4email-lite' ); ?></th>
				<th><?php echo esc_html__( 'Sent At', 'x4email-lite' ); ?></th>
				<th><?php echo esc_html__( 'Actions', 'x4email-lite' ); ?></th>
			</tr>
			</thead>
			<tbody>
			<?php if ( $logs ) : ?>
				<?php $log_count = count( $logs ); ?>
				<?php $max_rows = min( $log_count, 10 ); ?>
				<?php for ( $i = 0; $i < $max_rows; $i++ ) : ?>
					<?php $log = $logs[ $i ]; ?>
				<tr>
					<td><span class="x4email-status-dot <?php echo $log->status === 'Successful' ? 'active-dot' : 'disabled'; ?>"></span></td>
					<td><?php echo esc_html( $log->id ); ?></td>
					<td><?php echo esc_html( $log->mail_type ); ?></td>
					<td><?php echo esc_html( $log->recipient_email ); ?></td>
					<td><?php echo esc_html( $log->subject ); ?></td>
					<td>
					<?php
					echo $log->status === 'Successful' ?
						'<span style="color:#22c55e;font-weight:600;">Successful</span>' :
						'<span style="color:#ef4444;font-weight:600;">Failed</span>';
					?>
					</td>
					<td><?php echo esc_html( $log->sent_at ); ?></td>
					<td>
					<button class="x4email-btn-outline view-log-details" 
						data-id="<?php echo esc_attr( $log->id ); ?>" 
						data-mail-type="<?php echo esc_attr( $log->mail_type ); ?>" 
						data-recipient="<?php echo esc_attr( $log->recipient_email ); ?>" 
						data-subject="<?php echo esc_attr( $log->subject ); ?>" 
						data-message="<?php echo esc_attr( $log->message ); ?>" 
						data-status="<?php echo esc_attr( $log->status ); ?>" 
						data-error-log="<?php echo esc_attr( $log->error_log ); ?>" 
						data-sent-at="<?php echo esc_attr( $log->sent_at ); ?>">
						<svg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='currentColor' stroke-width='2' width='20' height='20' style='vertical-align:middle;margin-right:6px;'><circle cx='12' cy='12' r='10'/><path stroke-linecap='round' stroke-linejoin='round' d='M15 12a3 3 0 11-6 0 3 3 0 016 0z'/></svg>
						<?php echo esc_html__( 'View', 'x4email-lite' ); ?>
					</button>
					</td>
				</tr>
				<?php endfor; ?>
				<tr style="position: relative;">
				<td colspan="8" style="text-align:center; color:#1976d2; font-weight:600; background:rgba(255,255,255,0.7);">
				<span style="font-size:1.1em;">🔒 <?php echo esc_html__( 'Upgrade to Pro to see all logs', 'x4email-lite' ); ?></span>

				</td>
				</tr>
			  
			<?php else : ?>
				<tr>
				<td colspan="8"><?php echo esc_html__( 'No logs found.', 'x4email-lite' ); ?></td>
				</tr>
			<?php endif; ?>
			</tbody>
		</table>
		</div>
	</div>
	</div>
</div>

<div id="log-details-modal" class="log-details-modal" style="display: none;">
	<div class="log-details-modal-content">
	<span class="log-details-modal-close">&times;</span>
	<h2><?php echo esc_html__( 'Email Log Details', 'x4email-lite' ); ?></h2>
	<div class="x4email-modal-table-responsive">
		<table>
		<tr>
			<th><?php echo esc_html__( 'ID', 'x4email-lite' ); ?></th>
			<td id="log-id"></td>
		</tr>
		<tr>
			<th><?php echo esc_html__( 'Mail Type', 'x4email-lite' ); ?></th>
			<td id="log-mail-type"></td>
		</tr>
		<tr>
			<th><?php echo esc_html__( 'Recipient', 'x4email-lite' ); ?></th>
			<td id="log-recipient"></td>
		</tr>
		<tr>
			<th><?php echo esc_html__( 'Subject', 'x4email-lite' ); ?></th>
			<td id="log-subject"></td>
		</tr>
		<tr>
			<th><?php echo esc_html__( 'Message', 'x4email-lite' ); ?></th>
			<td id="log-message"></td>
		</tr>
		<tr>
			<th><?php echo esc_html__( 'Status', 'x4email-lite' ); ?></th>
			<td id="log-status"></td>
		</tr>
		<tr>
			<th><?php echo esc_html__( 'Error Log', 'x4email-lite' ); ?></th>
			<td id="log-error-log"></td>
		</tr>
		<tr>
			<th><?php echo esc_html__( 'Sent At', 'x4email-lite' ); ?></th>
			<td id="log-sent-at"></td>
		</tr>
		</table>
	</div>
	</div>
</div>
	<?php
}