<?php

// DESCRIPTION: Handles bulk content restriction (View Control) actions on the WordPress Posts list table.
// Allows admins to apply WPUF content visibility restrictions across multiple posts at once.

namespace WeDevs\Wpuf\Pro\Admin;

/**
 * Bulk Content Restriction
 *
 * Adds a "WPUF View Control" bulk action to the Posts screen,
 * enabling admins to set content visibility restrictions on
 * multiple posts at once.
 *
 * @since 4.2.14
 */
class Bulk_Content_Restriction {

    public function __construct() {
        add_filter( 'bulk_actions-edit-post', [ $this, 'register_bulk_action' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
        add_action( 'admin_footer-edit.php', [ $this, 'render_bulk_edit_panel' ] );
        add_filter( 'handle_bulk_actions-edit-post', [ $this, 'handle_bulk_action' ], 10, 3 );
        add_action( 'admin_notices', [ $this, 'show_admin_notice' ] );
    }

    /**
     * Register the WPUF View Control bulk action in the Posts dropdown
     *
     * @since 4.2.14
     *
     * @param array $bulk_actions Existing bulk actions
     *
     * @return array
     */
    public function register_bulk_action( $bulk_actions ) {
        $bulk_actions['wpuf_view_control'] = __( 'WPUF View Control', 'wpuf-pro' );

        return $bulk_actions;
    }

    /**
     * Enqueue CSS and JS assets on the edit-post screen
     *
     * @since 4.2.14
     *
     * @param string $hook_suffix The current admin page hook suffix
     *
     * @return void
     */
    public function enqueue_assets( $hook_suffix ) {
        if ( 'edit.php' !== $hook_suffix ) {
            return;
        }

        $screen = get_current_screen();

        if ( ! $screen || 'edit-post' !== $screen->id ) {
            return;
        }

        if ( ! current_user_can( 'edit_others_posts' ) ) {
            return;
        }

        wp_enqueue_style(
            'wpuf-bulk-content-restriction',
            WPUF_PRO_ASSET_URI . '/css/bulk-content-restriction.css',
            [],
            WPUF_PRO_VERSION
        );

        wp_enqueue_script(
            'wpuf-bulk-content-restriction',
            WPUF_PRO_ASSET_URI . '/js/bulk-content-restriction.js',
            [ 'jquery', 'wp-i18n', 'inline-edit-post' ],
            WPUF_PRO_VERSION,
            true
        );

        wp_localize_script( 'wpuf-bulk-content-restriction', 'wpufBulkViewControl', [
            'selectVisibility'   => __( 'Please select a visibility option.', 'wpuf-pro' ),
            'selectRole'         => __( 'Please select at least one user role.', 'wpuf-pro' ),
            'selectSubscription' => __( 'Please select at least one subscription plan.', 'wpuf-pro' ),
        ] );
    }

    /**
     * Render the hidden bulk edit panel HTML on the edit.php footer
     *
     * @since 4.2.14
     *
     * @return void
     */
    public function render_bulk_edit_panel() {
        $screen = get_current_screen();

        if ( ! $screen || 'edit-post' !== $screen->id ) {
            return;
        }

        if ( ! current_user_can( 'edit_others_posts' ) ) {
            return;
        }

        $all_roles     = get_editable_roles();
        $subscriptions = wpuf()->subscription->get_subscriptions();
        $column_count  = 0;

        // We need column count for colspan; get it from the list table
        if ( ! class_exists( 'WP_Posts_List_Table' ) ) {
            require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
            require_once ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php';
        }

        $wp_list_table = _get_list_table( 'WP_Posts_List_Table' );

        if ( $wp_list_table ) {
            $column_count = $wp_list_table->get_column_count();
        }

        if ( ! $column_count ) {
            $column_count = 7;
        }

        $this->render_panel_html( $all_roles, $subscriptions, $column_count );
    }

    /**
     * Render the hidden panel HTML markup
     *
     * @since 4.2.14
     *
     * @param array $all_roles     Editable roles from get_editable_roles()
     * @param array $subscriptions WPUF subscription packs
     * @param int   $column_count  Number of columns for colspan
     *
     * @return void
     */
    private function render_panel_html( $all_roles, $subscriptions, $column_count ) {
        ?>
        <table style="display: none;">
            <tbody>
                <tr id="wpuf-view-control-edit" class="inline-edit-row inline-edit-row-post" style="display: none;">
                    <td colspan="<?php echo (int) $column_count; ?>" class="colspanchange">
                        <div class="inline-edit-wrapper" role="region" aria-labelledby="wpuf-view-control-legend">

                            <fieldset class="inline-edit-col-left">
                                <legend class="inline-edit-legend" id="wpuf-view-control-legend">
                                    <?php esc_html_e( 'WPUF View Control', 'wpuf-pro' ); ?>
                                </legend>
                                <div class="inline-edit-col">
                                    <div id="wpuf-vc-bulk-title-div">
                                        <div id="wpuf-vc-bulk-titles"></div>
                                    </div>
                                </div>
                            </fieldset>

                            <fieldset class="inline-edit-col-center">
                                <div class="inline-edit-col">
                                    <span class="title inline-edit-categories-label"><?php esc_html_e( 'Visibility', 'wpuf-pro' ); ?></span>
                                    <select name="wpuf_res_display" id="wpuf-vc-display" style="width: 100%;">
                                        <option value=""><?php esc_html_e( '&mdash; Select &mdash;', 'wpuf-pro' ); ?></option>
                                        <option value="all"><?php esc_html_e( 'Remove restriction', 'wpuf-pro' ); ?></option>
                                        <option value="loggedin"><?php esc_html_e( 'Logged-in Users', 'wpuf-pro' ); ?></option>
                                        <option value="subscription"><?php esc_html_e( 'Subscription Users', 'wpuf-pro' ); ?></option>
                                    </select>
                                </div>
                            </fieldset>

                            <fieldset class="inline-edit-col-right">
                                <div class="inline-edit-col">
                                    <div id="wpuf-vc-roles-wrap" style="display: none;">
                                        <span class="title inline-edit-categories-label"><?php esc_html_e( 'User Roles', 'wpuf-pro' ); ?></span>
                                        <input type="hidden" name="wpuf_res_loggedin[]" value="0" />
                                        <ul class="cat-checklist wpuf-vc-roles-checklist">
                                            <?php foreach ( $all_roles as $role_name => $role_info ) : ?>
                                                <li>
                                                    <label>
                                                        <input type="checkbox" name="wpuf_res_loggedin[]" value="<?php echo esc_attr( $role_name ); ?>" />
                                                        <?php echo esc_html( $role_info['name'] ); ?>
                                                    </label>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>

                                    <div id="wpuf-vc-subscriptions-wrap" style="display: none;">
                                        <span class="title inline-edit-categories-label"><?php esc_html_e( 'Subscription Plans', 'wpuf-pro' ); ?></span>
                                        <?php if ( $subscriptions ) : ?>
                                            <input type="hidden" name="wpuf_res_subscription[]" value="0" />
                                            <ul class="cat-checklist wpuf-vc-subscriptions-checklist">
                                                <?php foreach ( $subscriptions as $pack ) : ?>
                                                    <li>
                                                        <label>
                                                            <input type="checkbox" name="wpuf_res_subscription[]" value="<?php echo (int) $pack->ID; ?>" />
                                                            <?php echo esc_html( $pack->post_title ); ?>
                                                        </label>
                                                    </li>
                                                <?php endforeach; ?>
                                            </ul>
                                        <?php else : ?>
                                            <p class="description"><?php esc_html_e( 'No subscription plan found.', 'wpuf-pro' ); ?></p>
                                        <?php endif; ?>
                                    </div>

                                    <div id="wpuf-vc-no-selection-msg">
                                        <p class="description"><?php esc_html_e( 'Select a visibility option to see available choices.', 'wpuf-pro' ); ?></p>
                                    </div>
                                </div>
                            </fieldset>

                            <div class="submit inline-edit-save">
                                <button type="button" class="button button-primary" id="wpuf-vc-bulk-update">
                                    <?php esc_html_e( 'Update', 'wpuf-pro' ); ?>
                                </button>
                                <button type="button" class="button" id="wpuf-vc-bulk-cancel">
                                    <?php esc_html_e( 'Cancel', 'wpuf-pro' ); ?>
                                </button>
                                <span class="spinner"></span>
                                <?php wp_nonce_field( 'wpuf_bulk_view_control', 'wpuf_vc_nonce', false ); ?>
                            </div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
        <?php
    }

    /**
     * Handle the bulk action server-side: update post meta for selected posts
     *
     * @since 4.2.14
     *
     * @param string $redirect_url The redirect URL after processing
     * @param string $doaction     The action being taken
     * @param array  $post_ids     The post IDs to process
     *
     * @return string
     */
    public function handle_bulk_action( $redirect_url, $doaction, $post_ids ) {
        if ( 'wpuf_view_control' !== $doaction ) {
            return $redirect_url;
        }

        $nonce = ! empty( $_REQUEST['wpuf_vc_nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['wpuf_vc_nonce'] ) ) : '';

        if ( ! wp_verify_nonce( $nonce, 'wpuf_bulk_view_control' ) ) {
            return $redirect_url;
        }

        if ( ! current_user_can( 'edit_others_posts' ) ) {
            return $redirect_url;
        }

        $display_to = '';

        if ( isset( $_REQUEST['wpuf_res_display'] ) && in_array( $_REQUEST['wpuf_res_display'], [ 'all', 'loggedin', 'subscription' ], true ) ) {
            $display_to = sanitize_text_field( wp_unslash( $_REQUEST['wpuf_res_display'] ) );
        }

        if ( empty( $display_to ) ) {
            return $redirect_url;
        }

        $all_roles      = get_editable_roles();
        $selected_roles  = [];
        $subscriptions   = [];
        $restricted      = 0;
        $unrestricted    = 0;

        if ( 'loggedin' === $display_to && ! empty( $_REQUEST['wpuf_res_loggedin'] ) && is_array( $_REQUEST['wpuf_res_loggedin'] ) ) {
            // Only allow valid editable roles
            $selected_roles = array_intersect(
                array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['wpuf_res_loggedin'] ) ),
                array_keys( $all_roles )
            );
        }

        if ( 'subscription' === $display_to && ! empty( $_REQUEST['wpuf_res_subscription'] ) && is_array( $_REQUEST['wpuf_res_subscription'] ) ) {
            $subscriptions = array_map( 'intval', $_REQUEST['wpuf_res_subscription'] );
        }

        foreach ( $post_ids as $post_id ) {
            $post_id = (int) $post_id;

            if ( ! current_user_can( 'edit_post', $post_id ) ) {
                continue;
            }

            update_post_meta( $post_id, '_wpuf_res_display', $display_to );

            if ( 'subscription' === $display_to ) {
                update_post_meta( $post_id, '_wpuf_res_subscription', $subscriptions );
                delete_post_meta( $post_id, '_wpuf_res_loggedin' );
                $restricted++;
            } elseif ( 'loggedin' === $display_to ) {
                update_post_meta( $post_id, '_wpuf_res_loggedin', $selected_roles );
                delete_post_meta( $post_id, '_wpuf_res_subscription' );
                $restricted++;
            } else {
                // 'all' — remove restrictions
                delete_post_meta( $post_id, '_wpuf_res_subscription' );
                delete_post_meta( $post_id, '_wpuf_res_loggedin' );
                $unrestricted++;
            }
        }

        $redirect_url = add_query_arg(
            [
                'wpuf_vc_restricted'   => $restricted,
                'wpuf_vc_unrestricted' => $unrestricted,
            ],
            $redirect_url
        );

        return $redirect_url;
    }

    /**
     * Show admin notice after bulk action processing
     *
     * @since 4.2.14
     *
     * @return void
     */
    public function show_admin_notice() {
        $screen = get_current_screen();

        if ( ! $screen || 'edit-post' !== $screen->id ) {
            return;
        }

        $restricted   = isset( $_GET['wpuf_vc_restricted'] ) ? (int) $_GET['wpuf_vc_restricted'] : 0; // phpcs:ignore WordPress.Security.NonceVerification
        $unrestricted = isset( $_GET['wpuf_vc_unrestricted'] ) ? (int) $_GET['wpuf_vc_unrestricted'] : 0; // phpcs:ignore WordPress.Security.NonceVerification

        if ( ! $restricted && ! $unrestricted ) {
            return;
        }

        $messages = [];

        if ( $restricted ) {
            /* translators: %d: number of posts restricted */
            $messages[] = sprintf( _n( '%d post restricted', '%d posts restricted', $restricted, 'wpuf-pro' ), $restricted );
        }

        if ( $unrestricted ) {
            /* translators: %d: number of posts unrestricted */
            $messages[] = sprintf( _n( '%d post unrestricted', '%d posts unrestricted', $unrestricted, 'wpuf-pro' ), $unrestricted );
        }

        printf(
            '<div class="notice notice-success is-dismissible"><p>%s</p></div>',
            esc_html( implode( ', ', $messages ) )
        );
    }
}
