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

/**
 * includes/admin/newssync-settings-page.php
 *
 * Admin UI: Dashboard, Settings, Tools/Status, Documentation
 *
 * Este ficheiro deve ser included pelo ficheiro principal do plugin dentro de is_admin():
 * require_once plugin_dir_path( __FILE__ ) . 'includes/admin/newssync-settings-page.php';
 *
 * Notas:
 * - Todas as funções públicas usam guards if ( ! function_exists ) para evitar redeclaração.
 * - O menu/submenus são registados aqui (add_action 'admin_menu').
 * - Os includes de tabs/documentation são seguros (file_exists) para evitar fatals.
 */

/* Allow override via filter: se outro caminho for fornecido, carrega e retorna. */
$newssync_custom_path = apply_filters( 'newssync_settings_page_path', __DIR__ . '/newssync-settings-page.php' );
if ( ! empty( $newssync_custom_path ) && realpath( $newssync_custom_path ) !== realpath( __FILE__ ) ) {
    if ( file_exists( $newssync_custom_path ) ) {
        require_once $newssync_custom_path;
        return;
    }
}

/* Enqueue admin scripts/styles helper */
if ( file_exists( __DIR__ . '/enqueue-admin-scripts.php' ) ) {
    require_once __DIR__ . '/enqueue-admin-scripts.php';
}

// inclui as ferramentas (Tools) — só se existir
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Local variable, not global
$tools_file = trailingslashit( NEWSSYNC_PLUGIN_DIR ) . 'includes/admin/newssync-tools.php';
if ( file_exists( $tools_file ) ) {
    require_once $tools_file;
}

/* Ensure request helper is available (fallback if not loaded by bootstrap). */
if ( ! function_exists( 'newssync_request_string' ) ) {
    $newssync_helper = __DIR__ . '/../core/request-helpers.php';
    if ( file_exists( $newssync_helper ) ) {
        require_once $newssync_helper;
    }
}

/* Define plugin dir constant fallback if absent */
if ( ! defined( 'NEWSSYNC_PLUGIN_DIR' ) ) {
    $newssync_main_file = dirname( __DIR__, 2 ) . '/rss-newssync.php';
    if ( file_exists( $newssync_main_file ) ) {
        define( 'NEWSSYNC_PLUGIN_DIR', plugin_dir_path( $newssync_main_file ) );
    } else {
        define( 'NEWSSYNC_PLUGIN_DIR', plugin_dir_path( __DIR__ . '/../../rss-newssync.php' ) );
    }
}

/* Load the documentation file (defines redirect function) */
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Local variable, not global
$doc_file = __DIR__ . '/newssync-documentation.php';
if ( file_exists( $doc_file ) ) {
    require_once $doc_file;
}

/* ========================================================================
   Table status block (shown only on plugin admin pages) and helpers
   ======================================================================== */
if ( ! function_exists( 'newssync_render_table_status' ) ) {
    function newssync_render_table_status() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Only render when on our plugin screens
        $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
        if ( $screen && strpos( $screen->id, 'rss-newssync' ) === false && strpos( $screen->id, 'rss-newssync-tools' ) === false ) {
            return;
        }

        // Per-user dismiss
        $dismissed = get_user_meta( get_current_user_id(), 'newssync_dismiss_table_notice', true );
        if ( $dismissed ) {
            return;
        }

        // If table exists nothing to show
        if ( function_exists( 'newssync_table_exists' ) && newssync_table_exists() ) {
            return;
        }

        $referer  = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
        $nonce    = wp_create_nonce( 'newssync_create_table' );
        $docs_url = admin_url( 'admin.php?page=rss-newssync-docs' );
        ?>
        <div style="margin-bottom:18px;">
            <div class="notice notice-warning" style="background:#fff; border-left:4px solid #f59e0b; padding:12px;">
                <p style="margin:0 0 8px;">
                    <strong><?php esc_html_e( 'Optimized item→post mapping is not active', 'rss-newssync' ); ?></strong><br>
                    <?php esc_html_e( 'The plugin will continue using a compatible postmeta fallback. For large sites, performance may be degraded.', 'rss-newssync' ); ?>
                </p>
                <div>
                    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:inline;">
                        <input type="hidden" name="action" value="newssync_create_table">
                        <input type="hidden" name="_wpnonce" value="<?php echo esc_attr( $nonce ); ?>">
                        <input type="hidden" name="_wp_http_referer" value="<?php echo esc_attr( $referer ); ?>">
                        <button class="button button-primary" type="submit"><?php esc_html_e( 'Attempt to create optimized table', 'rss-newssync' ); ?></button>
                    </form>
                    &nbsp;
                    <a class="button" href="<?php echo esc_url( $docs_url ); ?>"><?php esc_html_e( 'Table & Migration docs', 'rss-newssync' ); ?></a>
                    &nbsp;
                    <span style="color:#666; margin-left:8px; font-size:0.95rem;"><?php esc_html_e( 'You can dismiss this message by visiting Tools → NewsSync Status after setup.', 'rss-newssync' ); ?></span>
                </div>
            </div>
        </div>
        <?php
    }
}

/* ========================================================================
   Admin-post handler: attempt to create the optimized mapping table
   ======================================================================== */
if ( ! function_exists( 'newssync_admin_post_create_table' ) ) {
    add_action( 'admin_post_newssync_create_table', 'newssync_admin_post_create_table' );
    function newssync_admin_post_create_table() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Insufficient permissions', 'rss-newssync' ) );
        }

        $nonce = isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
        if ( empty( $_POST ) || ! wp_verify_nonce( $nonce, 'newssync_create_table' ) ) {
            wp_die( esc_html__( 'Invalid request.', 'rss-newssync' ) );
        }

        $referer = wp_get_referer() ?: admin_url();

        if ( ! function_exists( 'newssync_create_item_map_table' ) ) {
            $url = add_query_arg( 'newssync_create_table', 'error_no_function', $referer );
            wp_safe_redirect( $url );
            exit;
        }

        $ok = false;
        try {
            $ok = (bool) newssync_create_item_map_table();
        } catch ( Throwable $e ) {
            $ok = false;
        }

        if ( $ok ) {
            $url = add_query_arg( 'newssync_create_table', 'success', $referer );
        } else {
            $url = add_query_arg( 'newssync_create_table', 'error_create_failed', $referer );
        }
        wp_safe_redirect( $url );
        exit;
    }
}

/* ========================================================================
   Show transient notice after creation attempt
   ======================================================================== */
if ( ! function_exists( 'newssync_creation_result_notice' ) ) {
    add_action( 'admin_notices', 'newssync_creation_result_notice' );
    function newssync_creation_result_notice() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Displaying admin notice based on URL parameter
        if ( empty( $_GET['newssync_create_table'] ) ) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Displaying admin notice based on URL parameter
        $status = sanitize_text_field( wp_unslash( $_GET['newssync_create_table'] ) );
        if ( $status === 'success' ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Optimized item mapping table created successfully.', 'rss-newssync' ) . '</p></div>';
        } elseif ( $status === 'error_create_failed' ) {
            echo '<div class="notice notice-error"><p>' . esc_html__( 'Failed to create optimized table. Your database user may lack CREATE/ALTER privileges. Please contact your host or create the table manually.', 'rss-newssync' ) . '</p></div>';
        } elseif ( $status === 'error_no_function' ) {
            echo '<div class="notice notice-error"><p>' . esc_html__( 'Table creation support is not available (missing DB helper). Ensure the plugin files are intact.', 'rss-newssync' ) . '</p></div>';
        }
    }
}

/* ========================================================================
   Handlers: save settings, save feeds, save language, clear cache
   ======================================================================== */

/* Save settings */
if ( ! function_exists( 'newssync_handle_save_settings' ) ) {
    add_action( 'admin_post_newssync_save_settings', 'newssync_handle_save_settings' );
    function newssync_handle_save_settings() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Insufficient permissions', 'rss-newssync' ) );
        }
        check_admin_referer( 'newssync_save_settings', 'newssync_nonce' );

        $newssync_default_layout = function_exists( 'newssync_request_string' ) ? newssync_request_string( 'newssync_default_layout', 'POST', 'grid', '', '', 'sanitize_key' ) : ( isset( $_POST['newssync_default_layout'] ) ? sanitize_key( wp_unslash( $_POST['newssync_default_layout'] ) ) : 'grid' );
        $allowed_layouts = array( 'grid', 'list', 'carousel', 'hero' );
        if ( ! in_array( $newssync_default_layout, $allowed_layouts, true ) ) {
            $newssync_default_layout = 'grid';
        }
        update_option( 'newssync_default_layout', $newssync_default_layout );

        $newssync_show_image = isset( $_POST['newssync_show_image'] ) ? absint( wp_unslash( $_POST['newssync_show_image'] ) ) : 0;
        if ( ! in_array( $newssync_show_image, array( 0, 1 ), true ) ) {
            $newssync_show_image = 0;
        }
        update_option( 'newssync_show_image', $newssync_show_image );

        $newssync_cache_duration = function_exists( 'newssync_request_string' ) ? newssync_request_string( 'newssync_cache_duration', 'POST', '6h', '', '', 'sanitize_key' ) : ( isset( $_POST['newssync_cache_duration'] ) ? sanitize_key( wp_unslash( $_POST['newssync_cache_duration'] ) ) : '6h' );
        $allowed_cache = array( '6h', '24h' );
        if ( ! in_array( $newssync_cache_duration, $allowed_cache, true ) ) {
            $newssync_cache_duration = '6h';
        }
        update_option( 'newssync_cache_duration', $newssync_cache_duration );
        update_option( 'newssync_cache_custom_hours', '' );

        $hero_max = function_exists( 'newssync_request_int' ) ? newssync_request_int( 'newssync_hero_max_items', 'POST', 6 ) : ( isset( $_POST['newssync_hero_max_items'] ) ? absint( wp_unslash( $_POST['newssync_hero_max_items'] ) ) : 6 );
        $hero_max = min( $hero_max, 6 );
        update_option( 'newssync_hero_max_items', $hero_max );

        $newssync_save_as_posts = isset( $_POST['newssync_save_as_posts'] ) ? absint( wp_unslash( $_POST['newssync_save_as_posts'] ) ) : 0;
        update_option( 'newssync_save_as_posts', $newssync_save_as_posts );

        $newssync_publish_status = function_exists( 'newssync_request_string' ) ? newssync_request_string( 'newssync_publish_status', 'POST', 'publish', '', '', 'sanitize_key' ) : ( isset( $_POST['newssync_publish_status'] ) ? sanitize_key( wp_unslash( $_POST['newssync_publish_status'] ) ) : 'publish' );
        $allowed_status = array( 'publish', 'draft' );
        if ( ! in_array( $newssync_publish_status, $allowed_status, true ) ) {
            $newssync_publish_status = 'publish';
        }
        update_option( 'newssync_publish_status', $newssync_publish_status );

        $newssync_list_mode = function_exists( 'newssync_request_string' ) ? newssync_request_string( 'newssync_list_mode', 'POST', 'standard', '', '', 'sanitize_key' ) : ( isset( $_POST['newssync_list_mode'] ) ? sanitize_key( wp_unslash( $_POST['newssync_list_mode'] ) ) : 'standard' );
        $allowed_list_modes = array( 'standard', 'minimal', 'custom' );
        if ( ! in_array( $newssync_list_mode, $allowed_list_modes, true ) ) {
            $newssync_list_mode = 'standard';
        }
        update_option( 'newssync_list_mode', $newssync_list_mode );

        update_option( 'newssync_max_import_items', 15 );
        update_option( 'newssync_dupe_threshold', 80 );
        update_option( 'newssync_show_readmore', 'yes' );

        set_transient( 'newssync_settings_saved', true, 30 );

        $page_slug   = 'rss-newssync';
        $redirect_url = admin_url( 'admin.php?page=' . $page_slug . '#settings' );
        wp_safe_redirect( $redirect_url );
        exit;
    }
}

/* Save feeds */
if ( ! function_exists( 'newssync_handle_save_feeds' ) ) {
    add_action( 'admin_post_newssync_save_feeds', 'newssync_handle_save_feeds' );
    function newssync_handle_save_feeds() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Insufficient permissions', 'rss-newssync' ) );
        }
        check_admin_referer( 'newssync_save_feeds_action', 'newssync_feeds_nonce' );

        $feeds      = array();
        $urls       = isset( $_POST['feed_url'] ) ? array_map( 'esc_url_raw', (array) wp_unslash( $_POST['feed_url'] ) ) : array();
        $categories = isset( $_POST['feed_category'] ) ? array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['feed_category'] ) ) : array();

        $max = max( count( $urls ), count( $categories ) );
        for ( $i = 0; $i < $max; $i++ ) {
            $raw_u = $urls[ $i ] ?? '';
            $raw_c = $categories[ $i ] ?? '';
            $u = trim( (string) $raw_u );
            $c = trim( (string) $raw_c );
            if ( '' !== $u && '' !== $c ) {
                $feeds[] = array(
                    'url'      => esc_url_raw( $u ),
                    'category' => sanitize_text_field( $c ),
                );
            }
        }

        update_option( 'newssync_feeds', $feeds );
        set_transient( 'newssync_settings_saved', true, 30 );

        $page_slug   = 'rss-newssync';
        $redirect_url = admin_url( 'admin.php?page=' . $page_slug . '#feeds' );
        wp_safe_redirect( $redirect_url );
        exit;
    }
}

/* Save language */
if ( ! function_exists( 'newssync_handle_save_language' ) ) {
    add_action( 'admin_post_newssync_save_language', 'newssync_handle_save_language' );
    function newssync_handle_save_language() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Insufficient permissions', 'rss-newssync' ) );
        }
        check_admin_referer( 'newssync_save_language', 'newssync_lang_nonce' );

        $selected_lang = function_exists( 'newssync_request_string' ) ? newssync_request_string( 'newssync_plugin_language', 'POST', 'en_US', '', '', 'sanitize_text_field' ) : ( isset( $_POST['newssync_plugin_language'] ) ? sanitize_text_field( wp_unslash( $_POST['newssync_plugin_language'] ) ) : 'en_US' );
        update_option( 'newssync_plugin_language', $selected_lang );

        // Determine current tab from POST data
        $current_tab = 'hub';
        if ( isset( $_POST['newssync_current_tab'] ) && ! empty( $_POST['newssync_current_tab'] ) ) {
            $current_tab = sanitize_text_field( wp_unslash( $_POST['newssync_current_tab'] ) );
        }

        $page = 'rss-newssync';
        $redirect_url = admin_url( "admin.php?page={$page}#{$current_tab}" );
        wp_safe_redirect( $redirect_url );
        exit;
    }
}

/* Clear cache */
if ( ! function_exists( 'newssync_handle_clear_cache' ) ) {
    add_action( 'admin_post_newssync_clear_cache', 'newssync_handle_clear_cache' );
    function newssync_handle_clear_cache() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Insufficient permissions', 'rss-newssync' ) );
        }
        check_admin_referer( 'newssync_clear_cache_action', 'newssync_clear_cache_nonce' );

        global $wpdb;

        $patterns = array(
            '_transient_newssync_%',
            '_transient_timeout_newssync_%',
            '_transient_newssync_img_%',
            '_transient_timeout_newssync_img_%',
        );

        foreach ( $patterns as $like ) {
            $cache_key = 'newssync_option_names_like_' . md5( $like );
            $option_names = wp_cache_get( $cache_key, 'rsp' );

            if ( false === $option_names ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- listing options by LIKE justified here
                $option_names = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
                        $like
                    )
                );
                wp_cache_set( $cache_key, $option_names, 'rsp', MINUTE_IN_SECONDS * 5 );
            }

            if ( ! empty( $option_names ) ) {
                foreach ( $option_names as $opt_name ) {
                    delete_option( $opt_name );
                }
                wp_cache_delete( $cache_key, 'rsp' );
            }
        }

        set_transient( 'newssync_cache_cleared', true, 30 );

        // Determine current tab/section from POST data
        $current_section = 'hub';
        if ( isset( $_POST['newssync_current_tab'] ) && ! empty( $_POST['newssync_current_tab'] ) ) {
            $current_section = sanitize_text_field( wp_unslash( $_POST['newssync_current_tab'] ) );
        }

        $page_slug   = 'rss-newssync';
        $redirect_url = admin_url( 'admin.php?page=' . $page_slug . '#' . $current_section );
        wp_safe_redirect( $redirect_url );
        exit;
    }
}

/* ========================================================================
   Admin menu & submenus (register here only)
   ======================================================================== */
if ( ! function_exists( 'newssync_add_admin_menu' ) ) {
    add_action( 'admin_menu', 'newssync_add_admin_menu', 10 );
    function newssync_add_admin_menu() {
        // Top-level menu (short menu title "NewsSync")
        add_menu_page(
            __( 'RSS NewsSync', 'rss-newssync' ), // page title (H1)
            __( 'NewsSync', 'rss-newssync' ),     // menu title (short)
            'manage_options',
            'rss-newssync',                       // menu slug
            'newssync_render_dashboard_page',     // default callback - dashboard
            'dashicons-rss',
            100
        );

        // Dashboard submenu (first item) - same slug as parent
        add_submenu_page(
            'rss-newssync',
            __( 'Dashboard', 'rss-newssync' ),
            __( 'Dashboard', 'rss-newssync' ),
            'manage_options',
            'rss-newssync',
            'newssync_render_dashboard_page'
        );

        // Settings submenu (direct link to settings tab)
        add_submenu_page(
            'rss-newssync',
            __( 'Settings', 'rss-newssync' ),
            __( 'Settings', 'rss-newssync' ),
            'manage_options',
            'rss-newssync-settings',
            'newssync_render_settings_submenu_page'
        );

        // Tools / Status submenu
        add_submenu_page(
            'rss-newssync',
            __( 'Tools', 'rss-newssync' ),
            __( 'Tools', 'rss-newssync' ),
            'manage_options',
            'rss-newssync-tools',
            'newssync_render_tools_status_page'
        );

        // Documentation submenu (includes/admin/newssync-documentation.php)
        add_submenu_page(
            'rss-newssync',
            __( 'Documentation', 'rss-newssync' ),
            __( 'Documentation', 'rss-newssync' ),
            'manage_options',
            'rss-newssync-docs',
            'newssync_render_docs_page'
        );
    }
}

/* ========================================================================
   Dashboard callback (wrapper): forwards to settings page with tab=general
   ======================================================================== */
if ( ! function_exists( 'newssync_render_dashboard_page' ) ) {
    function newssync_render_dashboard_page() {
        // This is the main page renderer - calls the settings page function
        if ( function_exists( 'newssync_render_settings_page' ) ) {
            newssync_render_settings_page();
            return;
        }
        echo '<div class="wrap"><h1>' . esc_html__( 'Dashboard', 'rss-newssync' ) . '</h1>';
        echo '<p>' . esc_html__( 'Dashboard content not available.', 'rss-newssync' ) . '</p></div>';
    }
}

/* ========================================================================
   Dashboard submenu callback (redirects to #hub)
   ======================================================================== */
if ( ! function_exists( 'newssync_render_dashboard_submenu_page' ) ) {
    function newssync_render_dashboard_submenu_page() {
        // Redirect to main page with #hub hash
        wp_safe_redirect( admin_url( 'admin.php?page=rss-newssync#hub' ) );
        exit;
    }
}

/* ========================================================================
   Settings submenu callback (redirects to #settings)
   ======================================================================== */
if ( ! function_exists( 'newssync_render_settings_submenu_page' ) ) {
    function newssync_render_settings_submenu_page() {
        // Force the settings section to be active via global variable
        global $newssync_force_section;
        $newssync_force_section = 'settings';
        if ( function_exists( 'newssync_render_settings_page' ) ) {
            newssync_render_settings_page();
        }
    }
}

/* ========================================================================
   Settings page renderer (Tabs: general / settings)
   ======================================================================== */
if ( ! function_exists( 'newssync_render_settings_page' ) ) {
    function newssync_render_settings_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions.', 'rss-newssync' ) );
        }

        // Load modular layout with sections
        // Note: newssync_render_table_status() is called inside tools-section.php
        require_once __DIR__ . '/layout/newssync-main-layout.php';
    }
}
