<?php

/**
 * A1-WooBay - Admin UI Handler
 *
 * @package A1_WooBay
 * @since   0.2.0
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class A1WooBay_Admin {
    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_menu', array($this, 'register_menu') );
        add_action( 'admin_notices', array($this, 'maybe_show_notices') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_scripts') );
        add_action( 'admin_post_a1woobay_save_settings', array($this, 'handle_save_settings') );
        add_action( 'admin_post_a1woobay_disconnect', array($this, 'handle_disconnect') );
        add_action( 'admin_post_a1woobay_bulk_listings', array($this, 'handle_bulk_listings') );
    }

    public function enqueue_scripts( $hook ) {
        $screen = get_current_screen();
        if ( !$screen ) {
            return;
        }
        if ( false !== strpos( $screen->id, 'a1woobay-profiles' ) ) {
            wp_enqueue_script(
                'a1woobay-profiles-admin',
                A1WOOBAY_PLUGIN_URL . 'assets/js/profiles-admin.js',
                array('jquery'),
                A1WOOBAY_VERSION,
                true
            );
            wp_localize_script( 'a1woobay-profiles-admin', 'a1woobayAdmin', array(
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'nonce'    => wp_create_nonce( 'a1woobay_admin_ajax' ),
            ) );
        }
        // Settings page - was never enqueued, so "Import Orders Now" and
        // "Sync Now" had no click handlers bound at all (found 2026-08-18
        // while testing the puzzlesnmore.com eBay reconnect: 0 of 157
        // scripts loaded on this screen were the plugin's own JS).
        if ( false !== strpos( $screen->id, 'a1woobay-settings' ) ) {
            wp_enqueue_script(
                'a1woobay-settings-page',
                A1WOOBAY_PLUGIN_URL . 'assets/js/settings-page.js',
                array('jquery'),
                A1WOOBAY_VERSION,
                true
            );
            wp_localize_script( 'a1woobay-settings-page', 'a1wbSettings', array(
                'importingText'     => __( 'Importing…', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
                'importOrdersNonce' => wp_create_nonce( 'a1woobay_import_orders' ),
                'syncingText'       => __( 'Syncing…', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
                'manualSyncNonce'   => wp_create_nonce( 'a1woobay_manual_sync' ),
            ) );
        }
    }

    public function register_menu() {
        add_menu_page(
            __( 'A1 Marketplace Sync with eBay for WooCommerce', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            __( 'A1 Marketplace Sync with eBay for WooCommerce', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            'manage_woocommerce',
            'a1woobay-settings',
            array($this, 'render_settings_page'),
            'dashicons-store',
            58
        );
        add_submenu_page(
            'a1woobay-settings',
            __( 'Settings', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            __( 'Settings', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            'manage_woocommerce',
            'a1woobay-settings',
            array($this, 'render_settings_page')
        );
        add_submenu_page(
            'a1woobay-settings',
            __( 'eBay Profiles', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            __( 'eBay Profiles', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            'manage_woocommerce',
            'a1woobay-profiles',
            array($this, 'render_profiles_page')
        );
        add_submenu_page(
            'a1woobay-settings',
            __( 'Description Templates', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            __( 'Templates', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            'manage_woocommerce',
            'a1woobay-templates',
            array($this, 'render_templates_page')
        );
        add_submenu_page(
            'a1woobay-settings',
            __( 'eBay Listings', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            __( 'eBay Listings', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            'manage_woocommerce',
            'a1woobay-listings',
            array($this, 'render_listings_page')
        );
        add_submenu_page(
            'a1woobay-settings',
            __( 'eBay Orders', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            __( 'eBay Orders', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            'manage_woocommerce',
            'a1woobay-orders',
            array($this, 'render_orders_page')
        );
        add_submenu_page(
            'a1woobay-settings',
            __( 'Import & Adopt', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            __( 'Import & Adopt', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
            'manage_woocommerce',
            'a1woobay-import',
            array($this, 'render_import_page')
        );
    }

    public function render_settings_page() {
        if ( !current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) );
        }
        $auth = A1WooBay_Auth::get_instance();
        include A1WOOBAY_PLUGIN_DIR . 'admin/views/settings-page.php';
    }

    public function render_profiles_page() {
        if ( !current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) );
        }
        include A1WOOBAY_PLUGIN_DIR . 'admin/views/profiles-page.php';
    }

    public function render_templates_page() {
        if ( !current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) );
        }
        include A1WOOBAY_PLUGIN_DIR . 'admin/views/templates-page-upsell.php';
    }

    public function render_listings_page() {
        if ( !current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) );
        }
        include A1WOOBAY_PLUGIN_DIR . 'admin/views/listings-page.php';
    }

    public function render_orders_page() {
        if ( !current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) );
        }
        include A1WOOBAY_PLUGIN_DIR . 'admin/views/orders-page-upsell.php';
    }

    public function render_import_page() {
        if ( !current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) );
        }
        include A1WOOBAY_PLUGIN_DIR . 'admin/views/import-page.php';
    }

    public function handle_save_settings() {
        check_admin_referer( 'a1woobay_save_settings' );
        if ( !current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) );
        }
        $app_id = sanitize_text_field( wp_unslash( ( isset( $_POST['a1woobay_app_id'] ) ? $_POST['a1woobay_app_id'] : '' ) ) );
        $cert_id = sanitize_text_field( wp_unslash( ( isset( $_POST['a1woobay_cert_id'] ) ? $_POST['a1woobay_cert_id'] : '' ) ) );
        $runame = sanitize_text_field( wp_unslash( ( isset( $_POST['a1woobay_runame'] ) ? $_POST['a1woobay_runame'] : '' ) ) );
        $env = sanitize_text_field( wp_unslash( ( isset( $_POST['a1woobay_env'] ) ? $_POST['a1woobay_env'] : 'production' ) ) );
        if ( !in_array( $env, array('production', 'sandbox'), true ) ) {
            $env = 'production';
        }
        update_option( A1WooBay_Auth::OPT_ENV, $env );
        $auth = A1WooBay_Auth::get_instance();
        if ( '' === $app_id ) {
            $app_id = $auth->get_app_id();
        }
        if ( '' === $cert_id ) {
            $cert_id = $auth->get_cert_id();
        }
        if ( '' === $runame ) {
            $runame = $auth->get_runame();
        }
        if ( $app_id && $cert_id && $runame ) {
            $auth->save_credentials( $app_id, $cert_id, $runame );
            $redirect_args = array(
                'a1woobay_saved' => '1',
            );
        } else {
            $redirect_args = array(
                'a1woobay_error' => 'App ID, Cert ID, and RuName are all required.',
            );
        }
        wp_safe_redirect( add_query_arg( $redirect_args, admin_url( 'admin.php?page=a1woobay-settings' ) ) );
        exit;
    }

    public function handle_disconnect() {
        check_admin_referer( 'a1woobay_disconnect' );
        if ( !current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) );
        }
        A1WooBay_Auth::get_instance()->disconnect();
        wp_safe_redirect( add_query_arg( array(
            'a1woobay_disconnected' => '1',
        ), admin_url( 'admin.php?page=a1woobay-settings' ) ) );
        exit;
    }

    public function maybe_show_notices() {
        $screen = get_current_screen();
        if ( !$screen || false === strpos( $screen->id, 'a1woobay' ) ) {
            return;
        }
        if ( isset( $_GET['a1woobay_saved'] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) . '</p></div>';
        }
        if ( isset( $_GET['a1woobay_connected'] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Successfully connected to eBay!', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) . '</p></div>';
        }
        if ( isset( $_GET['a1woobay_disconnected'] ) ) {
            echo '<div class="notice notice-info is-dismissible"><p>' . esc_html__( 'Disconnected from eBay.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ) . '</p></div>';
        }
        if ( isset( $_GET['a1woobay_error'] ) ) {
            echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( urldecode( sanitize_text_field( wp_unslash( $_GET['a1woobay_error'] ) ) ) ) . '</p></div>';
        }
    }

    public function handle_bulk_listings() {
    }

}
