<?php
/**
 * Admin orchestrator — AfriRegions
 *
 * Uses native WordPress admin UI patterns:
 *   - Standard .wrap container
 *   - WordPress nav-tab-wrapper for tabs
 *   - WordPress notices for feedback
 *   - WordPress postbox/card patterns for content
 *
 * @package AfriRegions
 */

defined( 'ABSPATH' ) or die( 'Forbidden' );

class SCPWOO_Admin {

    private function get_tabs(): array {
        return array(
            'dashboard'    => __( 'Dashboard', 'afriregions-city-neighborhood-for-woocommerce' ),
            'geodata'      => __( 'Zones', 'afriregions-city-neighborhood-for-woocommerce' ),
            'restrictions' => __( 'Restrictions', 'afriregions-city-neighborhood-for-woocommerce' ),
            'settings'     => __( 'Settings', 'afriregions-city-neighborhood-for-woocommerce' ),
            'upgrade'      => __( 'Get Premium', 'afriregions-city-neighborhood-for-woocommerce' ),
        );
    }

    public function __construct() {
        $this->load_pages();

        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );

        // Suppress all admin notices on our plugin pages
        add_action( 'admin_head', function() {
            if ( isset( $_GET['page'] ) && 'scpwoo' === sanitize_key( $_GET['page'] ) ) {
                remove_all_actions( 'admin_notices' );
                remove_all_actions( 'all_admin_notices' );
            }
        } );

        // AJAX
        add_action( 'wp_ajax_scpwoo_save_settings', function() {
            $p = new SCPWOO_Page_Settings(); $p->ajax_save_settings();
        } );
        add_action( 'wp_ajax_scpwoo_get_region_data', function() {
            $p = new SCPWOO_Page_Geodata(); $p->ajax_get_region_data();
        } );
        add_action( 'wp_ajax_scpwoo_add_city', function() {
            $p = new SCPWOO_Page_Geodata(); $p->ajax_add_city();
        } );
        add_action( 'wp_ajax_scpwoo_delete_city', function() {
            $p = new SCPWOO_Page_Geodata(); $p->ajax_delete_city();
        } );
        add_action( 'wp_ajax_scpwoo_add_neighborhood', function() {
            $p = new SCPWOO_Page_Geodata(); $p->ajax_add_neighborhood();
        } );
        add_action( 'wp_ajax_scpwoo_delete_neighborhood', function() {
            $p = new SCPWOO_Page_Geodata(); $p->ajax_delete_neighborhood();
        } );
        add_action( 'wp_ajax_scpwoo_save_restrictions', function() {
            $p = new SCPWOO_Page_Restrictions(); $p->ajax_save_restrictions();
        } );
        add_action( 'wp_ajax_scpwoo_dismiss_guide', array( $this, 'ajax_dismiss_guide' ) );
        add_action( 'wp_ajax_scpwoo_load_tab', array( $this, 'ajax_load_tab' ) );
    }

    private function load_pages(): void {
        require_once plugin_dir_path( __FILE__ ) . 'class-scpwoo-audit.php';
        require_once plugin_dir_path( __FILE__ ) . 'class-scpwoo-geo-helper.php';

        SCPWOO_Geo_Helper::register_cache_hooks();

        $dir = plugin_dir_path( __FILE__ ) . 'pages/';

        require_once $dir . 'class-page-dashboard.php';
        require_once $dir . 'class-page-geodata.php';
        require_once $dir . 'class-page-restrictions.php';
        require_once $dir . 'class-page-settings.php';
        require_once $dir . 'class-page-upgrade.php';
    }

    public function add_admin_menu(): void {
        add_submenu_page(
            'woocommerce',
            __( 'AfriRegions', 'afriregions-city-neighborhood-for-woocommerce' ),
            __( 'AfriRegions', 'afriregions-city-neighborhood-for-woocommerce' ),
            'manage_woocommerce',
            'scpwoo',
            array( $this, 'render_page' )
        );
    }

    /**
     * Render admin page — WordPress native shell.
     *
     * @return void
     */
    public function render_page(): void {
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'afriregions-city-neighborhood-for-woocommerce' ) );
        }

        $tabs        = $this->get_tabs();
        $current_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'dashboard';

        if ( ! isset( $tabs[ $current_tab ] ) ) {
            $current_tab = 'dashboard';
        }

        $tab_icons = array(
            'dashboard'    => 'dashicons-dashboard',
            'geodata'      => 'dashicons-location-alt',
            'restrictions' => 'dashicons-shield',
            'settings'     => 'dashicons-admin-generic',
            'upgrade'      => 'dashicons-star-filled',
        );

        $base_url = admin_url( 'admin.php?page=scpwoo' );
        ?>
        <div class="wrap scpwoo-wrap">
            <div class="scpwoo-header-block">
                <div class="scpwoo-header">
                    <div class="scpwoo-header-left">
                        <img src="<?php echo esc_url( plugin_dir_url( __FILE__ ) . 'img/logo.svg' ); ?>" alt="AfriRegions" class="scpwoo-header-logo">
                        <span class="scpwoo-header-tagline"><?php esc_html_e( 'Structured address & shipping zones for Africa', 'afriregions-city-neighborhood-for-woocommerce' ); ?></span>
                    </div>
                </div>
            </div>

            <div class="scpwoo-layout">
                <nav class="scpwoo-sidebar scpwoo-tabs" role="navigation" aria-label="<?php esc_attr_e( 'AfriRegions settings', 'afriregions-city-neighborhood-for-woocommerce' ); ?>">
                <?php
                foreach ( $tabs as $slug => $label ) :
                    $url       = add_query_arg( 'tab', $slug, $base_url );
                    $is_active = $current_tab === $slug;
                    $icon      = isset( $tab_icons[ $slug ] ) ? $tab_icons[ $slug ] : 'dashicons-admin-generic';
                    $class     = 'scpwoo-sidebar-item nav-tab' . ( $is_active ? ' nav-tab-active' : '' );
                ?>
                    <a href="<?php echo esc_url( $url ); ?>"
                       class="<?php echo esc_attr( $class ); ?>"
                       data-tab="<?php echo esc_attr( $slug ); ?>"
                       role="tab"
                       title="<?php echo esc_attr( $label ); ?>"
                       aria-selected="<?php echo $is_active ? 'true' : 'false'; ?>"
                       aria-controls="scpwoo-tab-content"
                       id="scpwoo-tab-<?php echo esc_attr( $slug ); ?>">
                        <span class="dashicons <?php echo esc_attr( $icon ); ?>" aria-hidden="true"></span>
                        <span class="scpwoo-sidebar-label"><?php echo esc_html( $label ); ?></span>
                    </a>
                <?php endforeach; ?>
                    <div class="scpwoo-sidebar-footer">
                        <a href="https://afriregions.com/fr/docs/" target="_blank" rel="noopener noreferrer"
                           class="scpwoo-sidebar-item"
                           title="<?php esc_attr_e( 'Documentation', 'afriregions-city-neighborhood-for-woocommerce' ); ?>">
                            <span class="dashicons dashicons-editor-help" aria-hidden="true"></span>
                            <span class="scpwoo-sidebar-label"><?php esc_html_e( 'Documentation', 'afriregions-city-neighborhood-for-woocommerce' ); ?></span>
                        </a>
                        <a href="https://afriregions.com/fr/contact/" target="_blank" rel="noopener noreferrer"
                           class="scpwoo-sidebar-item"
                           title="<?php esc_attr_e( 'Support', 'afriregions-city-neighborhood-for-woocommerce' ); ?>">
                            <span class="dashicons dashicons-sos" aria-hidden="true"></span>
                            <span class="scpwoo-sidebar-label"><?php esc_html_e( 'Support', 'afriregions-city-neighborhood-for-woocommerce' ); ?></span>
                        </a>
                    </div>
                </nav>

                <div id="scpwoo-tab-content" class="scpwoo-tab-content" role="main" aria-labelledby="scpwoo-tab-<?php echo esc_attr( $current_tab ); ?>">
                    <?php $this->render_tab_content( $current_tab ); ?>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render tab content (used by full page and AJAX).
     *
     * @param string $tab Tab slug.
     * @return void
     */
    private function render_tab_content( string $tab ): void {
        $plugin_instance = SCPWOO_States_Places::instance();
        $has_supported   = $plugin_instance ? $plugin_instance->has_supported_allowed_country() : false;

        if ( 'upgrade' === $tab ) {
            $page = new SCPWOO_Page_Upgrade();
            $page->render();
            return;
        }

        if ( ! $has_supported ) {
            ?>
            <div class="notice notice-warning notice-no-support">
                <p>
                    <strong><?php esc_html_e( 'No supported country found', 'afriregions-city-neighborhood-for-woocommerce' ); ?></strong><br>
                    <?php esc_html_e( 'None of your WooCommerce selling or shipping countries are supported by this plugin. Add a supported African country to your WooCommerce settings.', 'afriregions-city-neighborhood-for-woocommerce' ); ?>
                </p>
                <p>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-settings&tab=general' ) ); ?>" class="button button-primary">
                        <?php esc_html_e( 'Go to WooCommerce settings', 'afriregions-city-neighborhood-for-woocommerce' ); ?>
                    </a>
                </p>
            </div>
            <?php
            return;
        }

        $page_classes = array(
            'dashboard'    => 'SCPWOO_Page_Dashboard',
            'geodata'      => 'SCPWOO_Page_Geodata',
            'restrictions' => 'SCPWOO_Page_Restrictions',
            'settings'     => 'SCPWOO_Page_Settings',
        );

        if ( isset( $page_classes[ $tab ] ) ) {
            $page = new $page_classes[ $tab ]();
            $page->render();
        }
    }

    /**
     * AJAX: Load tab content without full page reload.
     *
     * @return void
     */
    public function ajax_load_tab(): void {
        check_ajax_referer( SCPWOO_States_Places::NONCE_ADMIN, 'nonce' );

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( array( 'message' => 'Permission denied' ) );
        }

        $tabs = $this->get_tabs();
        $tab  = isset( $_POST['tab'] ) ? sanitize_key( $_POST['tab'] ) : 'dashboard';

        if ( ! isset( $tabs[ $tab ] ) ) {
            $tab = 'dashboard';
        }

        ob_start();
        try {
            $this->render_tab_content( $tab );
        } catch ( \Exception $e ) {
            ob_end_clean();
            // Log the real error internally, return generic message to client
            SCPWOO_Audit::log( 'error', 'Tab render failed: ' . $e->getMessage() );
            wp_send_json_error( array( 'message' => __( 'An error occurred while loading this tab.', 'afriregions-city-neighborhood-for-woocommerce' ) ) );
        }
        $html = ob_get_clean();

        if ( $html === '' ) {
            wp_send_json_error( array( 'message' => 'Render failed' ) );
        }

        // HTML is rendered by our own PHP templates (already escaped with esc_html/esc_attr).
        // Using wp_kses_post() here would strip form controls (inputs, selects, buttons)
        // needed by admin pages. The capability check above ensures only authorized admins
        // can trigger this endpoint.
        wp_send_json_success( array( 'html' => $html ) );
    }

    /** @return void */
    public function ajax_dismiss_guide(): void {
        check_ajax_referer( SCPWOO_States_Places::NONCE_ADMIN, 'nonce' );

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( array( 'message' => 'Permission denied' ), 403 );
        }

        update_user_meta( get_current_user_id(), SCPWOO_States_Places::META_GUIDE_DISMISSED, '1' );
        wp_send_json_success();
    }

    /** @return void */
    public function enqueue_admin_assets( string $hook_suffix ): void {
        $is_plugin_page = strpos( $hook_suffix, 'scpwoo' ) !== false;
        $is_wc_settings = $hook_suffix === 'woocommerce_page_wc-settings';
        if ( ! $is_plugin_page && ! $is_wc_settings ) {
            return;
        }

        $plugin_url = plugin_dir_url( SCPWOO_PLUGIN_FILE );

        wp_enqueue_style( 'scpwoo-admin-css', $plugin_url . 'admin/css/scpwoo-admin.css', array(), SCPWOO_States_Places::VERSION );
        wp_enqueue_script( 'scpwoo-admin-js', $plugin_url . 'admin/js/scpwoo-admin.js', array( 'jquery' ), SCPWOO_States_Places::VERSION, true );

        wp_localize_script( 'scpwoo-admin-js', 'scpwoo_admin_params', array(
            'ajax_url'    => admin_url( 'admin-ajax.php' ),
            'nonce'       => wp_create_nonce( SCPWOO_States_Places::NONCE_ADMIN ),
            'nonce_write' => wp_create_nonce( SCPWOO_States_Places::NONCE_ADMIN_WRITE ),
            'i18n'     => array(
                'confirm_delete_city'         => __( 'Delete this city and all its neighborhoods?', 'afriregions-city-neighborhood-for-woocommerce' ),
                'confirm_delete_neighborhood' => __( 'Delete this neighborhood?', 'afriregions-city-neighborhood-for-woocommerce' ),
                'city_added'                  => __( 'City added successfully.', 'afriregions-city-neighborhood-for-woocommerce' ),
                'city_deleted'                => __( 'City deleted.', 'afriregions-city-neighborhood-for-woocommerce' ),
                'neighborhood_added'          => __( 'Neighborhood added successfully.', 'afriregions-city-neighborhood-for-woocommerce' ),
                'neighborhood_deleted'        => __( 'Neighborhood deleted.', 'afriregions-city-neighborhood-for-woocommerce' ),
                'error'                       => __( 'An error occurred.', 'afriregions-city-neighborhood-for-woocommerce' ),
                'empty_name'                  => __( 'Please enter a name.', 'afriregions-city-neighborhood-for-woocommerce' ),
                'loading'                     => __( 'Loading...', 'afriregions-city-neighborhood-for-woocommerce' ),
                'blocked'                     => __( 'Blocked', 'afriregions-city-neighborhood-for-woocommerce' ),
                'entire_region_blocked'       => __( 'Entire region blocked', 'afriregions-city-neighborhood-for-woocommerce' ),
                'cancel'                      => __( 'Cancel', 'afriregions-city-neighborhood-for-woocommerce' ),
                'unsaved_changes'             => __( 'You have unsaved changes. Leave this tab and discard them?', 'afriregions-city-neighborhood-for-woocommerce' ),
                'leave'                       => __( 'Leave', 'afriregions-city-neighborhood-for-woocommerce' ),
                'city_name_placeholder'       => __( 'City name', 'afriregions-city-neighborhood-for-woocommerce' ),
                'add_city_btn'                => __( '+ Add a city', 'afriregions-city-neighborhood-for-woocommerce' ),
                'neighborhood_placeholder'    => __( 'Neighborhood name', 'afriregions-city-neighborhood-for-woocommerce' ),
                'add_neighborhood_btn'        => __( '+ Add', 'afriregions-city-neighborhood-for-woocommerce' ),
                'badge_custom'                => __( 'custom', 'afriregions-city-neighborhood-for-woocommerce' ),
                'badge_default'               => __( 'default', 'afriregions-city-neighborhood-for-woocommerce' ),
                'neighborhoods_count'         => __( 'neighborhoods', 'afriregions-city-neighborhood-for-woocommerce' ),
                'cities_count'                => __( 'cities', 'afriregions-city-neighborhood-for-woocommerce' ),
                'delete'                      => __( 'Delete', 'afriregions-city-neighborhood-for-woocommerce' ),
            ),
        ) );
    }
}
