<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class SBPAI_Admin {
    public function add_plugin_admin_menu() {
        // Main Menu
        // Custom SVG icon: robot logo encoded as base64 data URI
        $icon_svg = 'data:image/svg+xml;base64,' . base64_encode( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><rect x="11.25" y="2" width="1.5" height="4.5" fill="#8b5cf6" style="fill:#8b5cf6 !important;" rx="0.75"/><circle cx="12" cy="2" r="1.5" fill="#8b5cf6" style="fill:#8b5cf6 !important;"/><rect x="3" y="6" width="18" height="15" rx="5" fill="#7c3aed" style="fill:#7c3aed !important;"/><rect x="5.5" y="8.5" width="13" height="6.5" rx="3.25" fill="#ffffff" style="fill:#ffffff !important;"/><circle cx="9.5" cy="11.75" r="1.25" fill="#130f26" style="fill:#130f26 !important;"/><circle cx="14.5" cy="11.75" r="1.25" fill="#130f26" style="fill:#130f26 !important;"/><path d="M 10.5 16.2 Q 10.5 17.5 11.8 17.5 Q 10.5 17.5 10.5 18.8 Q 10.5 17.5 9.2 17.5 Q 10.5 17.5 10.5 16.2 Z" fill="#ffffff" style="fill:#ffffff !important;"/><path d="M 14.5 17.5 Q 14.5 18.5 15.5 18.5 Q 14.5 18.5 14.5 19.5 Q 14.5 18.5 13.5 18.5 Q 14.5 18.5 14.5 17.5 Z" fill="#ffffff" style="fill:#ffffff !important;"/></svg>' );
        add_menu_page( 
            'SandboxPress AI', 
            'SandboxPress AI', 
            'manage_options', 
            'sbpai-dashboard', 
            array( $this, 'view_dashboard' ), 
            $icon_svg,
            58 
        );

        // Submenus
        add_submenu_page( 'sbpai-dashboard', 'Dashboard', 'Dashboard', 'manage_options', 'sbpai-dashboard', array( $this, 'view_dashboard' ) );
        add_submenu_page( 'sbpai-dashboard', 'Content', 'Content', 'manage_options', 'sbpai-content', array( $this, 'view_content' ) );
        add_submenu_page( 'sbpai-dashboard', 'Users', 'Users', 'manage_options', 'sbpai-users', array( $this, 'view_users' ) );
        add_submenu_page( 'sbpai-dashboard', 'WooCommerce', 'WooCommerce', 'manage_options', 'sbpai-woocommerce', array( $this, 'view_woocommerce' ) );
        add_submenu_page( 'sbpai-dashboard', 'Settings', 'Settings', 'manage_options', 'sbpai-settings', array( $this, 'view_settings' ) );
    }

    public function enqueue_styles_scripts($hook) {
        // Prevent WordPress admin color schemes and themes from applying filters (like brightness/invert) that turn the colored logo white
        $menu_icon_css = '
            #adminmenu #toplevel_page_sbpai-dashboard .wp-menu-image img,
            #adminmenu #toplevel_page_sbpai-dashboard .wp-menu-image svg,
            #adminmenu #toplevel_page_sbpai-dashboard .wp-menu-image {
                filter: none !important;
                -webkit-filter: none !important;
            }
        ';
        wp_register_style( 'sbpai-admin-menu-fix', false );
        wp_enqueue_style( 'sbpai-admin-menu-fix' );
        wp_add_inline_style( 'sbpai-admin-menu-fix', $menu_icon_css );

        // Only load on sbpai pages
        if ( strpos( $hook, 'sbpai-' ) === false ) return;
        
        wp_enqueue_script( 'sbpai-admin-js', SBPAI_PLUGIN_URL . 'assets/js/admin.js', array('jquery'), SBPAI_VERSION, true );
        wp_localize_script( 'sbpai-admin-js', 'sbpai_obj', array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'sbpai_ajax_nonce' )
        ) );
        
        wp_enqueue_style( 'sbpai-admin-css', SBPAI_PLUGIN_URL . 'assets/css/admin.css', array(), SBPAI_VERSION );
        // Use system Inter font stack — no remote dependency.
        wp_add_inline_style( 'sbpai-admin-css', '.sbpai-app, .sbpai-app * { font-family: "Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }' );
    }

    /* Views */
    public function view_dashboard()   { $this->load_view( 'dashboard' ); }
    public function view_content()     { $this->load_view( 'content' ); }
    public function view_users()       { $this->load_view( 'users' ); }
    public function view_woocommerce() { $this->load_view( 'woocommerce' ); }
    public function view_settings()    { $this->load_view( 'settings' ); }

    private function load_view( $view_name ) {
        // Provide the layout wrapper globally
        include SBPAI_PLUGIN_DIR . 'admin/views/layout-wrapper.php';
    }

    public function handle_delete_all() {
        if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '', 'sbpai_delete_all' ) ) wp_die( 'Unauthorized' );

        $this->delete_all_by_meta('post', '_sbpai_post');
        $this->delete_all_by_meta('user', '_sbpai_user');
        $this->delete_all_by_meta('post', '_sbpai_media');
        
        wp_safe_redirect( admin_url( 'admin.php?page=sbpai-settings&deleted=true' ) );
        exit;
    }

    public function handle_ajax_delete_all() {
        check_ajax_referer( 'sbpai_ajax_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        // Flush any pending generation tasks so it stops creating after the wipe
        if ( function_exists( 'as_unschedule_all_actions' ) ) {
            as_unschedule_all_actions( '', array(), 'sbpai_dummy_data' );
            as_unschedule_all_actions( 'sbpai_generate_dummy_data_job' );
        }

        $this->delete_all_by_meta('post', '_sbpai_post');
        $this->delete_all_by_meta('post', '_sbpai_product');
        $this->delete_all_by_meta('user', '_sbpai_user');
        $this->delete_all_by_meta('post', '_sbpai_media');
        $this->delete_all_by_meta('order', '_sbpai_order');
        
        wp_send_json_success( 'All dummy data obliterated.' );
    }

    private function delete_all_by_meta($type, $meta_key) {
        if ($type === 'post') {
            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
            $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = '1'", $meta_key ) );
            foreach ($post_ids as $id) {
                wp_delete_post( $id, true );
            }
            // Eradicate orphaned metadata that causes inaccurate live dashboard counts
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key ) );

        } elseif ($type === 'user') {
            global $wpdb;
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
            $users = get_users( array( 'meta_key' => $meta_key, 'meta_value' => '1' ) );
            foreach ($users as $user) {
                wp_delete_user($user->ID);
            }
            // Eradicate orphaned user meta
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->usermeta WHERE meta_key = %s", $meta_key ) );

        } elseif ($type === 'order') {
            if ( class_exists('WooCommerce') ) {
                if ( class_exists('Automattic\WooCommerce\Utilities\OrderUtil') && Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
                    global $wpdb;
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
                    $order_ids = $wpdb->get_col( $wpdb->prepare( "SELECT order_id FROM {$wpdb->prefix}wc_orders_meta WHERE meta_key = %s AND meta_value = '1'", $meta_key ) );
                    foreach ($order_ids as $id) {
                        $order = wc_get_order( $id );
                        if ($order) $order->delete( true );
                    }
                    // Eradicate orphaned HPOS order meta
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}wc_orders_meta WHERE meta_key = %s", $meta_key ) );
                } else {
                    global $wpdb;
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
                    $order_ids = $wpdb->get_col( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = '1'", $meta_key ) );
                    foreach ($order_ids as $id) {
                        wp_delete_post($id, true);
                    }
                    // Eradicate orphaned order meta in postmeta
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key ) );
                }
            }
        }
    }
}
