<?php
if (!defined('ABSPATH')) exit;

function easy_gpt_render_translations_page() {
    global $wpdb;

    $table = $wpdb->prefix . 'easy_gpt_translations';

    // 🔢 Tarjetas resumen
    $total = $wpdb->get_var("SELECT COUNT(*) FROM $table WHERE status = 'success'");
    $last = $wpdb->get_var("SELECT MAX(date_translated) FROM $table WHERE status = 'success'");
    $last_formatted = $last ? date('Y-m-d H:i', strtotime($last)) : '—';
    $recent = $wpdb->get_var($wpdb->prepare("
        SELECT COUNT(*) FROM $table 
        WHERE status = 'success' 
        AND date_translated >= %s
    ", date('Y-m-d H:i:s', strtotime('-24 hours'))));

    // 🔄 Paginación
    $per_page     = 20;
    $page         = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
    $offset       = ($page - 1) * $per_page;
    $total_items  = $wpdb->get_var("SELECT COUNT(*) FROM $table");
    $total_pages  = ceil($total_items / $per_page);

    // 🔍 Resultados con paginación
    $results = $wpdb->get_results($wpdb->prepare("
        SELECT * 
        FROM $table 
        ORDER BY date_translated DESC 
        LIMIT %d OFFSET %d
    ", $per_page, $offset));

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

// 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();

if (!$is_license_valid) {
    echo '<div class="notice notice-error"><p><strong>⚠️ Your license is invalid or has expired. Translation features are disabled until you renew your license.</strong></p></div>';
}
	
    // 🎨 Estilos
    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>';

    // 🔷 Tarjetas resumen
    echo '<div class="easy-gpt-cards">';
    echo '<div class="easy-gpt-card"><h3>' . intval($total) . '</h3><p>Total Translated Articles</p></div>';
    echo '<div class="easy-gpt-card"><h3>' . esc_html($last_formatted) . '</h3><p>Last Translation</p></div>';
    echo '<div class="easy-gpt-card"><h3>' . intval($recent) . '</h3><p>Translated in Last 24h</p></div>';
    echo '</div>';

    // 📄 Tabla
    echo '<h2>Translation History</h2>';
    echo '<table class="widefat fixed striped">';
    echo '<thead>
        <tr>
            <th>Original Post</th>
            <th>Original Language</th>
            <th>Translated Language</th>
            <th>Translated Title</th>
            <th>Status</th>
            <th>Cost ($)</th>
            <th>Date</th>
            <th>View</th>
            <th>Edit</th>
        </tr>
    </thead>';
    echo '<tbody>';

    if ($results) {
		foreach ($results as $row) {
			$original_title    = get_the_title($row->original_post_id);
			$translated_title  = $row->translated_title ?: '(?)';

			$status_label = ucfirst($row->status);
            $status_colors = [
                'success' => 'green',
                'skipped' => '#ff9800',
                'error'   => 'red',
            ];
            
            $status_color = isset($status_colors[$row->status]) ? $status_colors[$row->status] : '#666';

			echo '<tr>';
			echo '<td><a href="' . get_edit_post_link($row->original_post_id) . '" target="_blank">' . esc_html($original_title) . '</a></td>';
			echo '<td>' . esc_html(strtoupper($row->original_language)) . '</td>';
			echo '<td>' . esc_html(strtoupper($row->target_language)) . '</td>';
			echo '<td>' . esc_html($translated_title) . '</td>';

			// Estado con color y mensaje
			echo '<td><span style="color: ' . esc_attr($status_color) . '; font-weight: bold;">' . esc_html($status_label) . '</span>';
			if ($row->status !== 'success' && !empty($row->error_message)) {
				echo '<br><small style="color: #a00;">' . esc_html($row->error_message) . '</small>';
			}
			echo '</td>';

			echo '<td>$' . number_format((float)$row->cost_usd, 4) . '</td>';
			echo '<td>' . esc_html(date('Y-m-d H:i', strtotime($row->date_translated))) . '</td>';

			// View
			if (!empty($row->translated_post_id)) {
				$post_status = get_post_status($row->translated_post_id);
				if ($post_status === 'draft') {
					$view_link = get_preview_post_link($row->translated_post_id);
					echo '<td><a href="' . esc_url($view_link) . '" class="button" target="_blank">Preview</a></td>';
				} else {
					$view_link = get_permalink($row->translated_post_id);
					echo '<td><a href="' . esc_url($view_link) . '" class="button" target="_blank">View</a></td>';
				}
			} else {
				echo '<td><span style="color: #999;">—</span></td>';
			}

			// Edit
			if (!empty($row->translated_post_id)) {
				$edit_link = get_edit_post_link($row->translated_post_id);
				echo '<td><a href="' . esc_url($edit_link) . '" class="button button-secondary" target="_blank">Edit</a></td>';
			} else {
				echo '<td><span style="color: #999;">—</span></td>';
			}

			echo '</tr>';
		}

    } else {
        echo '<tr><td colspan="9">No translations found.</td></tr>';
    }

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

    // 🔚 Paginación
    if ($total_pages > 1) {
        echo '<div class="tablenav"><div class="tablenav-pages" style="margin: 20px 0;">';
        $base_url = admin_url('admin.php?page=easy-gpt-translations');

        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>';

}