<?php
/**
 * Plugin Name: RSS NewsSync
 * Plugin URI: https://daazlabs.com/newssync/
 * Description: RSS news aggregator with Grid, List, and Carousel
 * Version: 1.0.1
 * Author: NewsSync
 * Author URI: https://daazlabs.com/
 * Text Domain: rss-newssync
 * Domain Path: /languages
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * @package NewsSync
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Define plugin path and URL constants.
if ( ! defined( 'NEWSSYNC_PLUGIN_PATH' ) ) {
	define( 'NEWSSYNC_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'NEWSSYNC_PLUGIN_URL' ) ) {
	define( 'NEWSSYNC_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}
if ( ! defined( 'NEWSSYNC_PLUGIN_DIR' ) ) {
	define( 'NEWSSYNC_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}

// Load core helpers.
require_once NEWSSYNC_PLUGIN_PATH . 'includes/core/helpers/newssync-items.php';

// Load DB helpers.
require_once NEWSSYNC_PLUGIN_PATH . 'includes/core/newssync-db.php';
require_once NEWSSYNC_PLUGIN_PATH . 'includes/core/newssync-activation.php';

// Load admin interface.
if ( is_admin() ) {
	// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Local variable, not global
	$admin_file = NEWSSYNC_PLUGIN_PATH . 'includes/admin/newssync-settings-page.php';
	if ( file_exists( $admin_file ) ) {
		require_once $admin_file;
	}
}

// Load translations.
add_action( 'plugins_loaded', 'newssync_load_textdomain' );
/**
 * Load plugin textdomain.
 */
function newssync_load_textdomain() {
	$plugin_language = get_option( 'newssync_plugin_language', get_locale() );
	$mo_file = plugin_dir_path( __FILE__ ) . 'languages/rss-newssync-' . $plugin_language . '.mo';
	load_textdomain( 'rss-newssync', $mo_file );
}

// Initialize default language option.
add_action( 'init', 'newssync_init_language_option' );
/**
 * Initialize language option if not set.
 */
function newssync_init_language_option() {
	if ( false === get_option( 'newssync_plugin_language' ) ) {
		update_option( 'newssync_plugin_language', 'en_US' );
	}
}

// Activation hook.
register_activation_hook( __FILE__, 'newssync_plugin_activation' );
/**
 * Plugin activation callback.
 */
function newssync_plugin_activation() {
	update_option( 'newssync_default_layout', 'grid' );
	update_option( 'newssync_hero_max_items', 6 );
	flush_rewrite_rules();

	// Create optimized mapping table if available.
	if ( function_exists( 'newssync_create_item_map_table' ) ) {
		newssync_create_item_map_table();
	}
}

// Load server vars helper.
$newssync_helper_file = NEWSSYNC_PLUGIN_DIR . 'includes/core/helpers/newssync-server-vars.php';
if ( file_exists( $newssync_helper_file ) ) {
	require_once $newssync_helper_file;
}

// Load core bootstrap.
require_once NEWSSYNC_PLUGIN_PATH . 'includes/core/newssync-bootstrap.php';
require_once NEWSSYNC_PLUGIN_PATH . 'includes/core/newssync-items-provider.php';
require_once NEWSSYNC_PLUGIN_PATH . 'includes/core/newssync-auto-import.php';
require_once NEWSSYNC_PLUGIN_PATH . 'includes/core/newssync-shortcode.php';

// AJAX endpoint to get auto page URL (public endpoint).
add_action( 'wp_ajax_newssync_get_auto_page_url', 'newssync_ajax_get_auto_page_url' );
add_action( 'wp_ajax_nopriv_newssync_get_auto_page_url', 'newssync_ajax_get_auto_page_url' );
/**
 * AJAX handler to get auto page URL.
 * Public endpoint - no nonce verification required.
 */
function newssync_ajax_get_auto_page_url() {
	$page_id = absint( get_option( 'newssync_auto_page_id' ) );

	if ( $page_id && ( $page = get_post( $page_id ) ) && 'publish' === $page->post_status ) {
		wp_send_json_success( array( 'url' => esc_url( get_permalink( $page_id ) ) ) );
	}

	wp_send_json_error();
}

// Register activation and deactivation hooks.
register_activation_hook( __FILE__, 'newssync_plugin_activate' );
register_deactivation_hook( __FILE__, 'newssync_plugin_deactivate' );

// ✅ HELPER: Buscar metadados RSS de um post (reutilizável)
function newssync_get_post_rss_metadata( $post_id ) {
	$original_url = get_post_meta( $post_id, '_newssync_original_url', true );

	if ( ! $original_url ) {
		return false; // Não é post RSS
	}

	return array(
		'source_name' => get_post_meta( $post_id, '_newssync_source_name', true ),
		'source_url'  => get_post_meta( $post_id, '_newssync_source_url', true ),
		'author'      => get_post_meta( $post_id, '_newssync_author', true ),
		'category'    => get_post_meta( $post_id, '_newssync_source', true ),
	);
}

// ✅ NOVO: Substituir coluna "Author" por "RSS Source" nos posts
if ( is_admin() ) {
	add_filter( 'manage_posts_columns', 'newssync_replace_author_column' );
	add_action( 'manage_posts_custom_column', 'newssync_show_rss_source', 10, 2 );
	add_filter( 'manage_edit-post_sortable_columns', 'newssync_sortable_source_column' );
}

function newssync_replace_author_column( $columns ) {
	// Remover coluna Author padrão
	if ( isset( $columns['author'] ) ) {
		unset( $columns['author'] );
	}

	// Adicionar nova coluna RSS Source na mesma posição
	$new_columns = array();
	foreach ( $columns as $key => $title ) {
		$new_columns[ $key ] = $title;

		// Adicionar depois da coluna de título
		if ( $key === 'title' ) {
		$new_columns['rss_source'] = __( 'Source/Author', 'rss-newssync' );
		}
	}

	return $new_columns;
}

function newssync_show_rss_source( $column_name, $post_id ) {
	if ( $column_name !== 'rss_source' ) {
		return;
	}

	// ✅ Usar função helper para buscar dados RSS
	$rss_data = newssync_get_post_rss_metadata( $post_id );

	if ( $rss_data ) {
		// Post RSS - mostrar source_name e author
		$source_name = $rss_data['source_name'];
		$author = $rss_data['author'];
		$source_url = $rss_data['source_url'];

		if ( $source_name ) {
			if ( $source_url ) {
				echo '<a href="' . esc_url( $source_url ) . '" target="_blank" rel="noopener" style="font-weight:600;">' . esc_html( $source_name ) . '</a>';
			} else {
				echo '<strong>' . esc_html( $source_name ) . '</strong>';
			}

			if ( $author ) {
				echo '<br><small style="color:#666;">by ' . esc_html( $author ) . '</small>';
			}
		} elseif ( $author ) {
			echo '<strong>' . esc_html( $author ) . '</strong>';
		} else {
			echo '<em style="color:#999;">RSS</em>';
		}
	} else {
		// Post normal WordPress - mostrar autor
		$post = get_post( $post_id );
		$author_id = $post->post_author;
		$author_name = get_the_author_meta( 'display_name', $author_id );

		$author_link = get_edit_user_link( $author_id );
		if ( $author_link ) {
			echo '<a href="' . esc_url( $author_link ) . '">' . esc_html( $author_name ) . '</a>';
		} else {
			echo esc_html( $author_name );
		}
	}
}

function newssync_sortable_source_column( $columns ) {
	$columns['rss_source'] = 'author';
	return $columns;
}
