<?php

function easy_gpt_refresh_page_callback() {
	if (!current_user_can('manage_options')) {
		wp_die(__('You do not have sufficient permissions to access this page.'));
	}

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

	// Estadísticas generales
	$total = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
	$last_refresh = $wpdb->get_var("SELECT MAX(refresh_time) FROM $table_name");
	$last_24h = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE refresh_time >= NOW() - INTERVAL 1 DAY");

	// Paginación
	$per_page = 20;
	$page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
	$offset = ($page - 1) * $per_page;

	$total_pages = ceil($total / $per_page);

	$results = $wpdb->get_results($wpdb->prepare(
		"SELECT * FROM $table_name ORDER BY refresh_time DESC LIMIT %d OFFSET %d",
		$per_page, $offset
	));

	// Verificar si la licencia es válida
	$license_status = get_option('easy_gpt_license_status');
	$license_expires = get_option('easy_gpt_license_expires');
	$is_license_valid = $license_status === 'valid' && new DateTime($license_expires) > new DateTime();

	echo '<div class="wrap">';
	echo '<h1>Article Refresher Statistics</h1>';

	if (!$is_license_valid) {
		echo '<div class="notice notice-error"><p><strong>⚠️ Your license is invalid or has expired. Article refresher features are disabled until you renew your license.</strong></p></div>';
		//error_log("easy_gpt_refresh_page: Invalid or expired license, displaying notice.");
		//return;
	}

	// 🔹 Estilo de tarjetas
	echo '<style>
		.easy-gpt-cards {
			display: flex;
			gap: 20px;
			margin: 20px 0;
		}
		.easy-gpt-card {
			background: #fff;
			border: 1px solid #ddd;
			padding: 20px;
			border-radius: 8px;
			box-shadow: 0 1px 3px rgba(0,0,0,0.05);
			flex: 1;
			min-width: 180px;
			text-align: center;
		}
		.easy-gpt-card h3 {
			margin: 0;
			font-size: 28px;
			color: #0073aa;
		}
		.easy-gpt-card p {
			margin: 5px 0 0;
			color: #555;
			font-size: 14px;
		}
	</style>';

	echo '<div class="easy-gpt-cards">';
	echo '<div class="easy-gpt-card"><h3>' . intval($total) . '</h3><p>Total Refreshed Articles</p></div>';
	echo '<div class="easy-gpt-card"><h3>' . ($last_refresh ? date('Y-m-d H:i', strtotime($last_refresh)) : '—') . '</h3><p>Last Refreshed</p></div>';
	echo '<div class="easy-gpt-card"><h3>' . intval($last_24h) . '</h3><p>Refreshed in Last 24h</p></div>';
	echo '</div>';

	// 🔹 Tabla de historial
	echo '<h2>Refresh History</h2>';
	echo '<table class="widefat fixed striped">';
	echo '<thead><tr>
		<th>ID</th>
		<th>Article</th>
		<th>Type</th>
		<th>Date</th>
		<th>Status</th>
		<th>Cost ($)</th>
		<th>Actions</th>
	</tr></thead><tbody>';

	if ($results) {
		foreach ($results as $row) {
			$post_title = get_the_title($row->post_id);
			$post_link = get_edit_post_link($row->post_id);
			$date = date('Y-m-d H:i', strtotime($row->refresh_time));
			$status = $row->status;
			$error_message = $row->error_message;
			$status_label = ucfirst($status);
			$status_color = $status === 'success' ? 'green' : 'red';
			$cost = isset($row->refresh_cost) ? number_format($row->refresh_cost, 4) : '0.0000';
			$post_type = get_post_type($row->post_id);
			$type_label = ucfirst($post_type);

			echo "<tr>
				<td>{$row->id}</td>
				<td><a href='{$post_link}' target='_blank'>{$post_title}</a></td>
				<td>{$type_label}</td>
				<td>{$date}</td>
				<td>
					<span style='color: {$status_color}; font-weight: bold;'>{$status_label}</span>";
					if ($status !== 'success' && !empty($error_message)) {
						echo "<br><small style='color: #a00;'>{$error_message}</small>";
					}
			echo "</td>
				<td>\${$cost}</td>
				<td><a href='{$post_link}' class='button'>Edit</a></td>
			</tr>";
		}
	} else {
		echo '<tr><td colspan="6">No refresh history available.</td></tr>';
	}

	echo '</tbody></table>';

	// 🔹 Paginación
	if ($total_pages > 1) {
		echo '<div class="tablenav"><div class="tablenav-pages">';
		$base_url = admin_url('admin.php?page=easy-gpt-refresh');

		for ($i = 1; $i <= $total_pages; $i++) {
			$class = ($i === $page) ? 'class="current-page button button-primary"' : 'class="button"';
			echo "<a {$class} href='{$base_url}&paged={$i}'>{$i}</a> ";
		}

		echo '</div></div>';
	}

	echo '</div>';
}
