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

/**
 * Enqueue admin scripts for RSS Newssync (Insert topbar Clear Cache button).
 * Include/require this file from your admin bootstrap (e.g. includes/admin/settings-page.php).
 */

/* Fallback: garante que os helpers de request estão disponíveis. */
if ( ! function_exists( 'newssync_request_string' ) ) {
    $newssync_helper = __DIR__ . '/../core/request-helpers.php';
    if ( file_exists( $newssync_helper ) ) {
        require_once $newssync_helper;
    }
}

add_action( 'admin_enqueue_scripts', 'newssync_enqueue_admin_scripts' );
function newssync_enqueue_admin_scripts( $hook_suffix ) {
    // Read current page/tab via helper to avoid direct $_GET access (PHPCS warnings).
    $page = function_exists( 'newssync_request_string' ) ? newssync_request_string( 'page', 'GET', '' ) : '';
    $tab  = function_exists( 'newssync_request_string' ) ? newssync_request_string( 'tab', 'GET', 'general' ) : 'general';

    // Only on our plugin page(s)
    if ( $page !== 'rss-newssync' && strpos( (string) $hook_suffix, 'rss-newssync' ) === false ) {
        return;
    }

	// enqueue admin stylesheet (cache-bust with filemtime if available)
    // Resolve plugin path/URL with fallbacks to the new constants
    $main_plugin_file = dirname( __DIR__, 2 ) . '/rss-newssync.php';
    $plugin_path = defined( 'NEWSSYNC_PLUGIN_PATH' ) ? NEWSSYNC_PLUGIN_PATH : ( defined( 'NEWSSYNC_PLUGIN_PATH' ) ? NEWSSYNC_PLUGIN_PATH : ( file_exists( $main_plugin_file ) ? plugin_dir_path( $main_plugin_file ) : plugin_dir_path( __DIR__ . '/../../rss-newssync.php' ) ) );
    $plugin_url  = defined( 'NEWSSYNC_PLUGIN_URL' ) ? NEWSSYNC_PLUGIN_URL : ( defined( 'NEWSSYNC_PLUGIN_URL' ) ? NEWSSYNC_PLUGIN_URL : ( file_exists( $main_plugin_file ) ? plugin_dir_url( $main_plugin_file ) : plugin_dir_url( __DIR__ . '/../../rss-newssync.php' ) ) );

    // NOVO: Enqueue new admin CSS
    $style_path = $plugin_path . 'includes/assets/css/newssync-admin.css';
    $style_url  = $plugin_url  . 'includes/assets/css/newssync-admin.css';
	$ver = ( file_exists( $style_path ) ) ? filemtime( $style_path ) : '1.0.0';
	wp_enqueue_style( 'newssync-admin-style', $style_url, array(), $ver );

    // NOVO: Enqueue form hash sync FIRST (updates hidden newssync_current_tab fields)
    // This MUST run before newssync-admin-js to monitor hash changes
    $form_hash_path = $plugin_path . 'includes/assets/js/newssync-form-hash.js';
    $form_hash_url  = $plugin_url  . 'includes/assets/js/newssync-form-hash.js';
    if ( file_exists( $form_hash_path ) ) {
        wp_enqueue_script( 'newssync-form-hash', $form_hash_url, array(), filemtime( $form_hash_path ), true );
    }

    // NOVO: Enqueue new admin JS (sidebar navigation) - depends on form-hash
    $admin_js_path = $plugin_path . 'includes/assets/js/newssync-admin.js';
    $admin_js_url  = $plugin_url  . 'includes/assets/js/newssync-admin.js';
    if ( file_exists( $admin_js_path ) ) {
        wp_enqueue_script( 'newssync-admin-js', $admin_js_url, array( 'jquery', 'newssync-form-hash' ), filemtime( $admin_js_path ), true );
    }

    // Expose server-forced section to admin JS (helps submenu pages like Tools/Docs)
    $force_section = '';
    if ( $page === 'rss-newssync-tools' ) {
        $force_section = 'tools';
    } elseif ( $page === 'rss-newssync-docs' ) {
        $force_section = 'documentation';
    } elseif ( $page === 'rss-newssync' ) {
        // Map legacy tab query to sections
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Tab parameter is for navigation only, not form processing
        $tab_param = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '';
        if ( $tab_param === 'general' || empty( $tab_param ) ) {
            $force_section = 'hub';
        } elseif ( $tab_param === 'settings' ) {
            $force_section = 'settings';
        } else {
            // Default to hub for main page if no specific tab
            $force_section = 'hub';
        }
    }
    if ( ! empty( $force_section ) && wp_script_is( 'newssync-admin-js', 'enqueued' ) ) {
        wp_localize_script( 'newssync-admin-js', 'newssyncServerData', array( 'forceSection' => $force_section ) );
    }

    $script_url = $plugin_url . 'includes/assets/js/insert-clear-cache-topbar.js';
    wp_register_script( 'rsp-insert-clear-cache-topbar', $script_url, array(), '1.0.0', true );

	// register + localize admin-auto-import
    $script_url = $plugin_url . 'includes/assets/js/admin-auto-import.js';
	wp_register_script( 'rsp-admin-auto-import', $script_url, array(), '1.0.0', true );
	$auto_import_data = array(
		'ajax_url'           => admin_url( 'admin-ajax.php' ),
		'importing_text'     => __( 'Importing...', 'rss-newssync' ),
		'error_import_text'  => __( 'Error during import', 'rss-newssync' ),
		'timeout_msg_text'   => __( 'Import timed out or error — check posts for results.', 'rss-newssync' ),
		'force_label'        => __( 'Force Import Now', 'rss-newssync' ),
        'nonce'              => wp_create_nonce( 'newssync_force_import' ),
        'clear_cache_nonce'  => wp_create_nonce( 'newssync_clear_cache_action' ),
		'clearing_text'      => __( 'Clearing cache...', 'rss-newssync' ),
		'cache_cleared_text' => __( 'Cache cleared', 'rss-newssync' ),
		'current_tab'        => $tab,
	);
    wp_localize_script( 'rsp-admin-auto-import', 'RSPAutoImportData', $auto_import_data );
    // New global name for migration: expose the same payload under `newssyncAutoImportData`.
    wp_localize_script( 'rsp-admin-auto-import', 'newssyncAutoImportData', $auto_import_data );
	wp_enqueue_script( 'rsp-admin-auto-import' );


    $localize = array(
        'admin_post_url' => admin_url( 'admin-post.php' ),
        'admin_page_url' => admin_url( 'admin.php' ),
        'nonce'          => wp_create_nonce( 'newssync_clear_cache_action' ),
        'current_tab'    => $tab,
        'i18n'           => array(
            'confirm'     => __( 'Are you sure you want to clear the cache?', 'rss-newssync' ),
            'clearing'    => __( 'Clearing...', 'rss-newssync' ),
            'error'       => __( 'Error clearing cache', 'rss-newssync' ),
            'clear_label' => __( 'Clear Cache Now', 'rss-newssync' ),
        ),
    );

    wp_localize_script( 'rsp-insert-clear-cache-topbar', 'RSPAdminData', $localize );
    // Also expose under new global for migration compatibility
    wp_localize_script( 'rsp-insert-clear-cache-topbar', 'newssyncAdminData', $localize );
    wp_enqueue_script( 'rsp-insert-clear-cache-topbar' );
}
