<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class MDSPBE_Handlers {

    function __construct() {
        add_action( 'admin_post_mdspbe_bulk_action', [ $this, 'handle_bulk_action' ] );
    }

    public function handle_bulk_action() {
        // Security check
        if ( ! isset( $_POST['mdspbe_bulk_action_nonce'] ) || 
            ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['mdspbe_bulk_action_nonce'] ) ), 'mdspbe_bulk_action' ) ) {
            wp_die( 'Invalid nonce' );
        }

        $page = isset( $_POST['page'] ) ? sanitize_text_field( wp_unslash( $_POST['page'] ) ) :  'mds-product-bulk-editor-for-woocommerce';
        $bulk_action = sanitize_text_field( wp_unslash( $_POST['bulk_action'] ?? '' ) );

        // Check capability
        if ( $bulk_action === 'duplicate' && ! current_user_can( 'publish_products' ) ) {
            wp_die( 'Permission denied' );
        } elseif ( in_array( $bulk_action, ['trash', 'delete', 'restore'] ) && ! current_user_can( 'delete_products' ) ) {
            wp_die( 'Permission denied' );
        }

        $function = apply_filters( 'mdpbe_bulk_action_function_name', 'mdspbe_' . $bulk_action . '_product', $bulk_action );
        if ( ! function_exists( $function ) ) {
            // Redirect back
            wp_redirect( admin_url( 'admin.php?page=' . $page ) );
            exit;
        }

        $product_ids = isset( $_POST['bulk_ids'] ) ? json_decode( sanitize_text_field( wp_unslash( $_POST['bulk_ids'] ) ) ) : [];
        if ( is_array( $product_ids ) && ! empty( $product_ids ) ) {
            $product_ids = array_map( 'intval', $product_ids );
            foreach ( $product_ids as $product_id ) {
                $function( $product_id );
            }
        }

        // Redirect back
        wp_redirect( admin_url( 'admin.php?page=' . $page . '&success=' . $bulk_action ) );
        exit;
    }

}

new MDSPBE_Handlers();




