<?php
class UserPackageManager
{
    public function __construct()
    {
        add_action('admin_menu', [$this, 'register_admin_submenu']);
        add_shortcode('user_package', [$this, 'display_user_package_shortcode']);
        add_filter('manage_users_columns', [$this, 'add_user_package_column']);
        add_action('manage_users_custom_column', [$this, 'show_user_package_column_content'], 10, 3);
    }

    public function register_admin_submenu()
    {
        add_submenu_page(
            'themes.php',
            esc_html__('Bulk Assign Packages to Users', 'adforest'),
            esc_html__('Bulk Assign Packages to Users', 'adforest'),
            'manage_options',
            'user-management',
            [$this, 'render_user_management_page']
        );
    }

    public function render_user_management_page()
    {
        if (isset($_POST['submit_user_packages']) && wp_verify_nonce($_POST['user_management_nonce'], 'user_management_action')) {
            $selected_users = isset($_POST['selected_users']) ? array_map('intval', $_POST['selected_users']) : [];
            $selected_package = isset($_POST['package_assignment']) ? sanitize_text_field($_POST['package_assignment']) : '';

            if (!empty($selected_users) && !empty($selected_package)) {
                $this->assign_package_to_users($selected_users, $selected_package);

                printf(
                    '<div class="notice notice-success"><p>%s</p></div>',
                    esc_html(sprintf(
                        __('Package "%s" assigned to %d user(s) successfully!', 'adforest'),
                        $selected_package,
                        count($selected_users)
                    ))
                );
            } else {
                echo '<div class="notice notice-error"><p>' . esc_html__('Please select users and a package.', 'adforest') . '</p></div>';
            }
        }

        $users = get_users(['orderby' => 'display_name', 'order' => 'ASC']);
        $packages = apply_filters('adforest_elementor_get_packages', []);

        ?>
        <div class="wrap">
            <h1><?php esc_html_e("Assign Package to Bulk Users", "adforest"); ?></h1>
            <p><?php esc_html_e('Select users and assign packages to them.', 'adforest'); ?></p>

            <form method="post" action="">
                <?php wp_nonce_field('user_management_action', 'user_management_nonce'); ?>

                <div style="margin-bottom: 20px;">
                    <h2><?php esc_html_e('Select Users', 'adforest'); ?></h2>
                    <div style="margin-bottom: 10px;">
                        <button type="button" id="select-all-users" class="button"><?php esc_html_e('Select All', 'adforest'); ?></button>
                        <button type="button" id="deselect-all-users" class="button"><?php esc_html_e('Deselect All', 'adforest'); ?></button>
                    </div>

                    <div style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; background: #fff;">
                        <?php foreach ($users as $user): ?>
                            <label style="display: block; margin-bottom: 5px;">
                                <input type="checkbox" name="selected_users[]" value="<?php echo esc_attr($user->ID); ?>" class="user-checkbox">
                                <?php echo esc_html($user->display_name); ?>
                                <span style="color: #666;">(<?php echo esc_html($user->user_email); ?>)</span>
                                <?php
//                                $current_package = get_user_meta($user->ID, 'assigned_package', true);
//                                if ($current_package) {
                                    //echo '<span style="color: #0073aa; font-size: 12px;"> - ' . esc_html__('Current:', 'adforest') . ' ' . esc_html($packages[$current_package] ?? $current_package) . '</span>';
//                                }
                                ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div style="margin-bottom: 20px;">
                    <h2><?php esc_html_e('Assign Package', 'adforest'); ?></h2>
                    <select name="package_assignment" id="package_assignment" class="regular-text" required>
                        <option value=""><?php esc_html_e('Select a package...', 'adforest'); ?></option>
                        <?php foreach ($packages as $value => $label): ?>
                            <option value="<?php echo esc_attr($value); ?>"><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <input type="submit" name="submit_user_packages" class="button button-primary"
                           value="<?php esc_attr_e('Assign Package to Selected Users', 'adforest'); ?>">
                </div>
            </form>
        </div>

        <script type="text/javascript">
            jQuery(document).ready(function ($) {
                $('#select-all-users').click(function () {
                    $('.user-checkbox').prop('checked', true);
                });

                $('#deselect-all-users').click(function () {
                    $('.user-checkbox').prop('checked', false);
                });

                $('form').submit(function (e) {
                    const selectedUsers = $('.user-checkbox:checked').length;
                    const selectedPackage = $('#package_assignment').val();

                    if (selectedUsers === 0) {
                        alert('<?php echo esc_js(__('Please select at least one user.', 'adforest')); ?>');
                        e.preventDefault();
                        return false;
                    }

                    if (!selectedPackage) {
                        alert('<?php echo esc_js(__('Please select a package.', 'adforest')); ?>');
                        e.preventDefault();
                        return false;
                    }

                    return confirm('<?php echo esc_js(__('Are you sure you want to assign', 'adforest')); ?> "' +
                        $('#package_assignment option:selected').text() + '" ' +
                        '<?php echo esc_js(__('to', 'adforest')); ?> ' + selectedUsers + ' <?php echo esc_js(__('user(s)?', 'adforest')); ?>');
                });
            });
        </script>

        <style>
            .user-checkbox { margin-right: 8px; }
            #package_assignment { min-width: 200px; }
            .notice { margin: 20px 0; }
            .wrap h2 { margin-top: 20px; margin-bottom: 10px; }
        </style>
        <?php
    }

    public function display_user_package_shortcode()
    {
        if (!is_user_logged_in()) {
            return esc_html__('Please log in to view your package.', 'adforest');
        }

        $user_id = get_current_user_id();
        $package = get_user_meta($user_id, 'assigned_package', true);

        if ($package) {
            $packages = apply_filters('adforest_elementor_get_packages', []);
            return esc_html__('Your assigned package:', 'adforest') . ' ' . esc_html($packages[$package] ?? $package);
        }

        return esc_html__('No package assigned.', 'adforest');
    }

    public function add_user_package_column($columns)
    {
        $columns['assigned_package'] = esc_html__('Assigned Package', 'adforest');
        return $columns;
    }

    public function show_user_package_column_content($value, $column_name, $user_id)
    {
        if ($column_name === 'assigned_package') {
            $package = get_user_meta($user_id, 'assigned_package', true);
            $packages = apply_filters('adforest_elementor_get_packages', []);
            return $package ? esc_html($packages[$package] ?? $package) : '<em>' . esc_html__('None', 'adforest') . '</em>';
        }
        return $value;
    }

    private function assign_package_to_users($user_ids, $product_id)
    {
        foreach ($user_ids as $user_id) {
            if (function_exists('adforest_give_user_package_from_admin')) {
                adforest_give_user_package_from_admin($product_id, $user_id);
            }
        }
    }
}