<?php
/**
 * Structure Viewer — Admin Page
 *
 * Registers the Tools menu entry and renders the full admin page HTML.
 * Contains zero inline JavaScript — all JS lives in assets/js/sv-app.js.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit( 'Direct access denied.' );
}

final class SV_AdminPage {

    /** Register the Tools > Structure Viewer menu item. */
    public static function register_menu() {
        add_management_page(
            esc_html__( 'Structure Viewer', 'structure-viewer' ),
            esc_html__( 'Structure Viewer', 'structure-viewer' ),
            'manage_options',
            'structure-viewer',
            [ __CLASS__, 'render' ]
        );
    }

    /** AJAX: return the item list for the picker dropdown. */
    public static function ajax_get_item_list() {
        check_ajax_referer( STRUCTUREVIEWER_NONCE, 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Permission denied.' ] );
        }

        $type  = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : 'plugin';
        $dirs  = ( $type === 'plugin' )
            ? ( glob( WP_PLUGIN_DIR . '/*', GLOB_ONLYDIR ) ?: [] )
            : ( glob( get_theme_root() . '/*', GLOB_ONLYDIR ) ?: [] );

        $list = ( $type === 'plugin' )
            ? SV_ItemData::get_plugin_list( $dirs )
            : SV_ItemData::get_theme_list( $dirs );

        // Return [ folder => name ] map for the JS picker
        $result = [];
        foreach ( $list as $folder => $data ) {
            $result[ $folder ] = $data['Name'] ?? $folder;
        }

        wp_send_json_success( $result );
    }

    // ── Page render ───────────────────────────────────────────────────────────

    public static function render() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions.', 'structure-viewer' ) );
        }

        // Parse request: only trust values when a valid nonce is present
        if ( isset( $_GET['sv_nonce'] ) ) {
            if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['sv_nonce'] ) ), 'sv_form_action' ) ) {
                wp_die( esc_html__( 'Security check failed.', 'structure-viewer' ) );
            }
            $type = isset( $_GET['psv_type'] ) ? sanitize_text_field( wp_unslash( $_GET['psv_type'] ) ) : 'plugin';
            $item = isset( $_GET['psv_item'] ) ? SV_Sanitizer::item_name( sanitize_text_field( wp_unslash( $_GET['psv_item'] ) ) ) : '';
        } else {
            $type = 'plugin';
            $item = '';
        }

        if ( ! in_array( $type, [ 'plugin', 'theme' ], true ) ) {
            $type = 'plugin';
        }

        $settings   = SV_Settings::get();
        $sv_patterns = $settings['exclude_patterns'];
        $dash_stats  = SV_Dashboard::get_stats();

        include __DIR__ . '/views/page.php';
    }
}