<?php
/**
 * Email Logs Display
 *
 * @link       https://mediahubster.in
 * @since      1.0.6
 *
 * @package    Subs_Sys
 * @subpackage Subs_Sys/admin/partials
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// Handle clear logs request
if ( isset( $_POST['clear_logs_action'] ) && check_admin_referer( 'clear_email_logs', 'clear_logs_nonce' ) ) {
	$clear_type = sanitize_text_field( $_POST['clear_logs_action'] );
	
	if ( $clear_type === 'all' ) {
		$deleted = Subs_Sys_Email_Logger::clear_all_logs();
		echo '<div class="notice notice-success is-dismissible"><p>' . 
			sprintf( esc_html__( 'Successfully deleted all email logs (%d records).', 'subscription-system' ), $deleted ) . 
			'</p></div>';
	} elseif ( $clear_type === 'old' ) {
		$days = isset( $_POST['days'] ) ? absint( $_POST['days'] ) : 90;
		$deleted = Subs_Sys_Email_Logger::delete_old_logs( $days );
		echo '<div class="notice notice-success is-dismissible"><p>' . 
			sprintf( esc_html__( 'Successfully deleted %d email logs older than %d days.', 'subscription-system' ), $deleted, $days ) . 
			'</p></div>';
	}
}

// Get filter parameters
$current_filter = isset( $_GET['filter_type'] ) ? sanitize_text_field( $_GET['filter_type'] ) : '';
$search = isset( $_GET['s'] ) ? sanitize_text_field( $_GET['s'] ) : '';
$paged = isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
$per_page = 20;

// Build query args
$args = array(
	'limit'  => $per_page,
	'offset' => ( $paged - 1 ) * $per_page,
	'search' => $search
);

if ( $current_filter === 'sent' ) {
	$args['status'] = 'sent';
} elseif ( $current_filter === 'failed' ) {
	$args['status'] = 'failed';
}

// Get logs
$logs = Subs_Sys_Email_Logger::get_logs( $args );
$total_logs = Subs_Sys_Email_Logger::count_logs( $args );
$total_pages = ceil( $total_logs / $per_page );

// Get statistics
$stats = Subs_Sys_Email_Logger::get_statistics();
?>

<div class="wrap subs-sys-email-logs">
	<h1 class="wp-heading-inline"><?php esc_html_e( 'Email Logs', 'subscription-system' ); ?></h1>
	
	<!-- Statistics Cards -->
	<div class="email-stats-cards">
		<div class="stat-card stat-total">
			<div class="stat-icon">📊</div>
			<div class="stat-content">
				<div class="stat-value"><?php echo esc_html( number_format_i18n( $stats['total'] ) ); ?></div>
				<div class="stat-label"><?php esc_html_e( 'Total Emails', 'subscription-system' ); ?></div>
			</div>
		</div>
		
		<div class="stat-card stat-sent">
			<div class="stat-icon">✅</div>
			<div class="stat-content">
				<div class="stat-value"><?php echo esc_html( number_format_i18n( $stats['sent'] ) ); ?></div>
				<div class="stat-label"><?php esc_html_e( 'Sent Successfully', 'subscription-system' ); ?></div>
			</div>
		</div>
		
		<div class="stat-card stat-failed">
			<div class="stat-icon">❌</div>
			<div class="stat-content">
				<div class="stat-value"><?php echo esc_html( number_format_i18n( $stats['failed'] ) ); ?></div>
				<div class="stat-label"><?php esc_html_e( 'Failed', 'subscription-system' ); ?></div>
			</div>
		</div>
		
		<div class="stat-card stat-today">
			<div class="stat-icon">📅</div>
			<div class="stat-content">
				<div class="stat-value"><?php echo esc_html( number_format_i18n( $stats['today'] ) ); ?></div>
				<div class="stat-label"><?php esc_html_e( 'Today', 'subscription-system' ); ?></div>
			</div>
		</div>
		
		<div class="stat-card stat-week">
			<div class="stat-icon">📆</div>
			<div class="stat-content">
				<div class="stat-value"><?php echo esc_html( number_format_i18n( $stats['this_week'] ) ); ?></div>
				<div class="stat-label"><?php esc_html_e( 'This Week', 'subscription-system' ); ?></div>
			</div>
		</div>
		
		<div class="stat-card stat-month">
			<div class="stat-icon">🗓️</div>
			<div class="stat-content">
				<div class="stat-value"><?php echo esc_html( number_format_i18n( $stats['this_month'] ) ); ?></div>
				<div class="stat-label"><?php esc_html_e( 'This Month', 'subscription-system' ); ?></div>
			</div>
		</div>
	</div>

	<hr class="wp-header-end">

	<!-- Filters and Search -->
	<div class="tablenav top">
		<div class="alignleft actions">
			<select name="filter_type" id="filter-type" onchange="window.location.href='<?php echo esc_url( admin_url( 'admin.php?page=subscription-email-logs' ) ); ?>&filter_type=' + this.value;">
				<option value=""><?php esc_html_e( 'All Status', 'subscription-system' ); ?></option>
				<option value="sent" <?php selected( $current_filter, 'sent' ); ?>><?php esc_html_e( 'Sent', 'subscription-system' ); ?></option>
				<option value="failed" <?php selected( $current_filter, 'failed' ); ?>><?php esc_html_e( 'Failed', 'subscription-system' ); ?></option>
			</select>
			
			<button type="button" class="button" onclick="document.getElementById('clear-logs-modal').style.display='block'">
				<?php esc_html_e( 'Clear Logs', 'subscription-system' ); ?>
			</button>
		</div>
		
		<form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" class="search-box">
			<input type="hidden" name="page" value="subscription-email-logs">
			<?php if ( $current_filter ) : ?>
				<input type="hidden" name="filter_type" value="<?php echo esc_attr( $current_filter ); ?>">
			<?php endif; ?>
			<input type="search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Search emails...', 'subscription-system' ); ?>">
			<button type="submit" class="button"><?php esc_html_e( 'Search', 'subscription-system' ); ?></button>
		</form>
	</div>

	<!-- Email Logs Table -->
	<table class="wp-list-table widefat fixed striped email-logs-table">
		<thead>
			<tr>
				<th class="column-date"><?php esc_html_e( 'Date/Time', 'subscription-system' ); ?></th>
				<th class="column-recipient"><?php esc_html_e( 'Recipient', 'subscription-system' ); ?></th>
				<th class="column-article"><?php esc_html_e( 'Article/Post', 'subscription-system' ); ?></th>
				<th class="column-subject"><?php esc_html_e( 'Subject', 'subscription-system' ); ?></th>
				<th class="column-status"><?php esc_html_e( 'Status', 'subscription-system' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php if ( empty( $logs ) ) : ?>
				<tr>
					<td colspan="5" class="no-logs">
						<?php esc_html_e( 'No email logs found.', 'subscription-system' ); ?>
					</td>
				</tr>
			<?php else : ?>
				<?php foreach ( $logs as $log ) : ?>
					<tr class="log-row <?php echo esc_attr( 'status-' . $log->status ); ?>">
						<td class="column-date">
							<?php echo esc_html( date_i18n( 'M j, Y g:i A', strtotime( $log->sent_at ) ) ); ?>
						</td>
						<td class="column-recipient">
							<strong><?php echo esc_html( $log->recipient_name ?: $log->recipient_email ); ?></strong><br>
							<span class="email-address"><?php echo esc_html( $log->recipient_email ); ?></span>
							<?php if ( $log->user_id ) : ?>
								<br><span class="user-id">User ID: <?php echo esc_html( $log->user_id ); ?></span>
							<?php endif; ?>
						</td>
						<td class="column-article">
							<?php if ( $log->post_id && $log->post_title ) : ?>
								<strong><?php echo esc_html( $log->post_title ); ?></strong><br>
								<?php if ( $log->post_url ) : ?>
									<a href="<?php echo esc_url( $log->post_url ); ?>" target="_blank" class="post-link">
										<?php esc_html_e( 'View Post', 'subscription-system' ); ?> →
									</a>
								<?php endif; ?>
								<br><span class="post-id">Post ID: <?php echo esc_html( $log->post_id ); ?></span>
							<?php else : ?>
								<span class="no-post"><?php esc_html_e( 'N/A', 'subscription-system' ); ?></span>
							<?php endif; ?>
						</td>
						<td class="column-subject">
							<?php echo esc_html( $log->subject ); ?>
							<?php if ( $log->content_plan_id ) : ?>
								<br><span class="plan-id">Plan ID: <?php echo esc_html( $log->content_plan_id ); ?></span>
							<?php endif; ?>
						</td>
						<td class="column-status">
							<?php if ( $log->status === 'sent' ) : ?>
								<span class="status-badge status-sent">✅ <?php esc_html_e( 'Sent', 'subscription-system' ); ?></span>
							<?php else : ?>
								<span class="status-badge status-failed">❌ <?php esc_html_e( 'Failed', 'subscription-system' ); ?></span>
								<?php if ( $log->error_message ) : ?>
									<br><span class="error-message" title="<?php echo esc_attr( $log->error_message ); ?>">
										⚠️ <?php echo esc_html( wp_trim_words( $log->error_message, 10 ) ); ?>
									</span>
								<?php endif; ?>
							<?php endif; ?>
						</td>
					</tr>
				<?php endforeach; ?>
			<?php endif; ?>
		</tbody>
	</table>

	<!-- Pagination -->
	<?php if ( $total_pages > 1 ) : ?>
		<div class="tablenav bottom">
			<div class="tablenav-pages">
				<?php
				$page_links = paginate_links( array(
					'base'      => add_query_arg( 'paged', '%#%' ),
					'format'    => '',
					'current'   => $paged,
					'total'     => $total_pages,
					'prev_text' => __( '&laquo; Previous', 'subscription-system' ),
					'next_text' => __( 'Next &raquo;', 'subscription-system' )
				) );
				
				if ( $page_links ) {
					echo '<span class="displaying-num">' . 
						sprintf( esc_html__( '%s items', 'subscription-system' ), number_format_i18n( $total_logs ) ) . 
						'</span>';
					echo $page_links;
				}
				?>
			</div>
		</div>
	<?php endif; ?>
</div>

<!-- Clear Logs Modal -->
<div id="clear-logs-modal" class="subs-sys-modal" style="display:none;">
	<div class="modal-content">
		<div class="modal-header">
			<h2><?php esc_html_e( 'Clear Email Logs', 'subscription-system' ); ?></h2>
			<span class="close" onclick="document.getElementById('clear-logs-modal').style.display='none'">&times;</span>
		</div>
		<div class="modal-body">
			<form method="post" action="">
				<?php wp_nonce_field( 'clear_email_logs', 'clear_logs_nonce' ); ?>
				
				<p><strong><?php esc_html_e( 'Select what to clear:', 'subscription-system' ); ?></strong></p>
				
				<label>
					<input type="radio" name="clear_logs_action" value="old" checked>
					<?php esc_html_e( 'Clear logs older than:', 'subscription-system' ); ?>
					<input type="number" name="days" value="90" min="1" style="width: 60px;">
					<?php esc_html_e( 'days', 'subscription-system' ); ?>
				</label>
				<br><br>
				
				<label>
					<input type="radio" name="clear_logs_action" value="all">
					<strong style="color: #dc3232;"><?php esc_html_e( 'Clear ALL logs (cannot be undone)', 'subscription-system' ); ?></strong>
				</label>
				
				<p class="description">
					<?php esc_html_e( 'Warning: This action cannot be undone. Please make sure you want to proceed.', 'subscription-system' ); ?>
				</p>
				
				<div class="modal-footer">
					<button type="button" class="button" onclick="document.getElementById('clear-logs-modal').style.display='none'">
						<?php esc_html_e( 'Cancel', 'subscription-system' ); ?>
					</button>
					<button type="submit" class="button button-primary">
						<?php esc_html_e( 'Clear Logs', 'subscription-system' ); ?>
					</button>
				</div>
			</form>
		</div>
	</div>
</div>

<style>
/* Statistics Cards */
.email-stats-cards {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
	gap: 15px;
	margin: 20px 0;
}

.stat-card {
	background: #fff;
	border: 1px solid #ddd;
	border-radius: 8px;
	padding: 15px;
	display: flex;
	align-items: center;
	gap: 12px;
	transition: all 0.2s;
}

.stat-card:hover {
	transform: translateY(-2px);
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
	font-size: 32px;
	line-height: 1;
}

.stat-content {
	flex: 1;
}

.stat-value {
	font-size: 24px;
	font-weight: 700;
	line-height: 1.2;
	color: #2271b1;
}

.stat-label {
	font-size: 12px;
	color: #666;
	margin-top: 4px;
}

.stat-sent .stat-value { color: #00a32a; }
.stat-failed .stat-value { color: #dc3232; }
.stat-today .stat-value { color: #996800; }

/* Email Logs Table */
.email-logs-table {
	margin-top: 20px;
}

.email-logs-table th {
	font-weight: 600;
}

.column-date { width: 15%; }
.column-recipient { width: 25%; }
.column-article { width: 25%; }
.column-subject { width: 25%; }
.column-status { width: 10%; }

.email-address {
	color: #666;
	font-size: 12px;
}

.user-id, .post-id, .plan-id {
	color: #999;
	font-size: 11px;
}

.post-link {
	font-size: 12px;
	text-decoration: none;
}

.no-post {
	color: #999;
	font-style: italic;
}

.status-badge {
	display: inline-block;
	padding: 4px 8px;
	border-radius: 4px;
	font-size: 12px;
	font-weight: 600;
}

.status-sent {
	background: #d4edda;
	color: #155724;
}

.status-failed {
	background: #f8d7da;
	color: #721c24;
}

.error-message {
	display: block;
	color: #dc3232;
	font-size: 11px;
	margin-top: 4px;
	cursor: help;
}

.no-logs {
	text-align: center;
	padding: 40px;
	color: #666;
	font-style: italic;
}

/* Modal Styles */
.subs-sys-modal {
	display: none;
	position: fixed;
	z-index: 100000;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
	background-color: #fefefe;
	margin: 5% auto;
	border-radius: 8px;
	width: 90%;
	max-width: 500px;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.modal-header {
	padding: 20px;
	border-bottom: 1px solid #ddd;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.modal-header h2 {
	margin: 0;
	font-size: 18px;
}

.close {
	color: #aaa;
	font-size: 28px;
	font-weight: bold;
	cursor: pointer;
	line-height: 1;
}

.close:hover {
	color: #000;
}

.modal-body {
	padding: 20px;
}

.modal-body label {
	display: block;
	margin-bottom: 15px;
}

.modal-footer {
	margin-top: 20px;
	text-align: right;
}

.modal-footer .button {
	margin-left: 10px;
}

/* Responsive */
@media (max-width: 782px) {
	.email-stats-cards {
		grid-template-columns: repeat(2, 1fr);
	}
	
	.stat-value {
		font-size: 20px;
	}
}
</style>

<script>
// Close modal when clicking outside
window.onclick = function(event) {
	var modal = document.getElementById('clear-logs-modal');
	if (event.target == modal) {
		modal.style.display = 'none';
	}
}
</script>


