<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- View template, variables are locally scoped.
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- view template, tab nav only.
$current_tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'generate'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$plugin_page = 'sbpai-users';

// Handle bulk DELETE on list tab
if ( $current_tab === 'list' && isset($_POST['bulk_action']) && $_POST['bulk_action'] === 'delete' && !empty($_POST['bulk_ids']) ) {
    check_admin_referer('sbpai_bulk_action_nonce');
    $count = 0;
    foreach ( array_map( 'intval', (array) wp_unslash( $_POST['bulk_ids'] ) ) as $uid ) {
        if ( wp_delete_user( intval($uid) ) ) $count++;
    }
    // translators: %d is the number of users deleted.
    echo '<div class="notice notice-success is-dismissible" style="margin-top:20px;"><p>' . sprintf( esc_html__( 'Successfully deleted %d users.', 'sandboxpress-ai' ), intval( $count ) ) . '</p></div>';
}
?>
<div class="sbpai-view-header" style="display:flex; justify-content:space-between; align-items:center;">
    <div>
        <h2>User Generation</h2>
        <p>Create realistic user profiles with WooCommerce billing addresses, custom roles, and avatars.</p>
    </div>
</div>

<div class="sbpai-tab-nav">
    <a href="?page=<?php echo esc_attr( $plugin_page ); ?>&tab=generate" class="<?php echo $current_tab === 'generate' ? 'active' : ''; ?>">Generate Users</a>
    <a href="?page=<?php echo esc_attr( $plugin_page ); ?>&tab=list"     class="<?php echo $current_tab === 'list'     ? 'active' : ''; ?>">View Dummy Users</a>
</div>

<div class="sbpai-card sbpai-settings-form" style="border-top-left-radius: 0;">

<?php if ( $current_tab === 'generate' ) : ?>

    <table class="sbpai-form-table">
        <tbody>

            <!-- ── Default Password ── -->
            <tr class="sbpai-table-section-head">
                <td colspan="2"><h3>🔐 Account Settings</h3></td>
            </tr>
            <tr>
                <th><label for="sbpai-user-password">Default Password</label></th>
                <td>
                    <input type="text" id="sbpai-user-password" class="sbpai-input" value="Password@123" style="max-width: 240px;">
                    <p class="description">All generated users will be created with this password. Leave blank for a random auto-generated password.</p>
                </td>
            </tr>

            <!-- ── Roles & Counts ── -->
            <tr class="sbpai-table-section-head">
                <td colspan="2"><h3>👥 Roles &amp; Counts</h3></td>
            </tr>
            <tr>
                <th><label>User Roles</label></th>
                <td>
                    <p class="description" style="margin-bottom: 12px;">Enable each role and set how many users should be created for it.</p>
                    <table style="border-collapse: collapse; width: 100%; max-width: 520px;">
                        <thead>
                            <tr>
                                <th style="text-align:left; padding: 6px 12px; background:#f6f7f7; border:1px solid #e2e4e7; font-weight:600;">Role</th>
                                <th style="text-align:left; padding: 6px 12px; background:#f6f7f7; border:1px solid #e2e4e7; font-weight:600;">Enable</th>
                                <th style="text-align:left; padding: 6px 12px; background:#f6f7f7; border:1px solid #e2e4e7; font-weight:600;">Count</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $all_roles = wp_roles()->roles;
                            $protected = ['administrator']; // Never generate admin accounts
                            foreach ( $all_roles as $role_key => $role_data ) :
                                if ( in_array( $role_key, $protected ) ) continue;
                                $label = translate_user_role( $role_data['name'] );
                            ?>
                            <tr>
                                <td style="padding: 8px 12px; border:1px solid #e2e4e7;">
                                    <strong><?php echo esc_html( $label ); ?></strong>
                                    <code style="margin-left:6px; font-size:11px; color:#888;"><?php echo esc_html( $role_key ); ?></code>
                                </td>
                                <td style="padding: 8px 12px; border:1px solid #e2e4e7; text-align:center;">
                                    <input type="checkbox" id="sbpai-role-enable-<?php echo esc_attr($role_key); ?>" class="sbpai-role-checkbox" data-role="<?php echo esc_attr($role_key); ?>" checked>
                                </td>
                                <td style="padding: 8px 12px; border:1px solid #e2e4e7;">
                                    <input type="number" id="sbpai-role-count-<?php echo esc_attr($role_key); ?>" class="sbpai-input sbpai-role-count" data-role="<?php echo esc_attr($role_key); ?>" value="5" min="0" max="500" style="max-width: 90px;">
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </td>
            </tr>

            <!-- ── User Profile Options ── -->
            <tr class="sbpai-table-section-head">
                <td colspan="2"><h3>🎨 Profile Options</h3></td>
            </tr>
            <tr>
                <th><label>Generate Avatars</label></th>
                <td>
                    <input type="checkbox" id="sbpai-user-avatar" checked>
                    <p class="description" style="display:inline-block; margin-left:6px;">Sideloads a unique face image from an external CDN as the local avatar.</p>
                </td>
            </tr>
            <tr>
                <th><label>WooCommerce Billing</label></th>
                <td>
                    <input type="checkbox" id="sbpai-user-wc-billing" checked>
                    <p class="description" style="display:inline-block; margin-left:6px;">Populates billing and shipping address meta fields for WooCommerce compatibility.</p>
                </td>
            </tr>
            <tr>
                <th><label>Bio &amp; Social Links</label></th>
                <td>
                    <input type="checkbox" id="sbpai-user-bio" checked>
                    <p class="description" style="display:inline-block; margin-left:6px;">Adds a generated biography text and fake website URL.</p>
                </td>
            </tr>

        </tbody>
    </table>

    <div style="margin-top: 30px; display:flex; gap:15px; align-items:center;">
        <button class="sbpai-btn sbpai-btn-primary" id="sbpai-generate-users-btn" style="font-size: 16px; padding: 10px 24px; background:#8b5cf6;">
            ⚡ Generate Users
        </button>
        <div class="sbpai-progress" id="progress-users"></div>
    </div>

<?php elseif ( $current_tab === 'list' ) :

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash
    $filter_role = isset( $_GET['filter_role'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_role'] ) ) : '';
    // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Intentional admin-only dummy tracking query.
    $query_args = array(
        'meta_key'   => '_sbpai_user',
        'meta_value' => '1',
        'number'     => 200,
        'orderby'    => 'registered',
        'order'      => 'DESC',
    );
    // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
    if ( !empty($filter_role) ) { $query_args['role'] = $filter_role; }
    $dummy_users = get_users( $query_args );
?>
    <!-- Filter -->
    <form method="GET" style="margin-bottom: 12px; display:flex; gap:10px; align-items:center;">
        <input type="hidden" name="page" value="<?php echo esc_attr($plugin_page); ?>">
        <input type="hidden" name="tab" value="list">
        <select name="filter_role" style="max-width: 200px;">
            <option value="">All Roles</option>
            <?php foreach ( wp_roles()->roles as $rk => $rd ) : ?>
            <option value="<?php echo esc_attr($rk); ?>" <?php selected($filter_role, $rk); ?>><?php echo esc_html(translate_user_role($rd['name'])); ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" class="button">Filter</button>
    </form>

    <!-- Bulk delete form -->
    <form method="POST">
        <?php wp_nonce_field('sbpai_bulk_action_nonce'); ?>
        <div class="tablenav top">
            <div class="alignleft actions bulkactions">
                <select name="bulk_action">
                    <option value="-1">Bulk actions</option>
                    <option value="delete">Delete Permanently</option>
                </select>
                <input type="submit" class="button action" value="Apply">
            </div>
        </div>
        <table class="wp-list-table widefat fixed striped table-view-list">
            <thead>
                <tr>
                    <td class="manage-column column-cb check-column"><input id="cb-select-all-users" type="checkbox"></td>
                    <th>Username</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Role</th>
                    <th>Registered</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if ( ! empty($dummy_users) ) : foreach( $dummy_users as $u ) :
                    $roles_str = implode(', ', array_map('ucfirst', $u->roles));
                ?>
                <tr>
                    <th scope="row" class="check-column"><input type="checkbox" name="bulk_ids[]" value="<?php echo esc_attr( $u->ID ); ?>"></th>
                    <td><strong><a href="<?php echo esc_url( get_edit_user_link( $u->ID ) ); ?>"><?php echo esc_html( $u->user_login ); ?></a></strong></td>
                    <td><?php echo esc_html( trim($u->first_name . ' ' . $u->last_name) ?: '—' ); ?></td>
                    <td><?php echo esc_html($u->user_email); ?></td>
                    <td><span style="background:#ede9fe;color:#7c3aed;padding:2px 8px;border-radius:4px;font-size:12px;"><?php echo esc_html($roles_str); ?></span></td>
                    <td><?php echo esc_html( substr($u->user_registered, 0, 10) ); ?></td>
                    <td><a href="<?php echo esc_url( admin_url( 'users.php?action=delete&user=' . intval( $u->ID ) ) ); ?>" style="color:#dc3232;">Delete</a></td>
                </tr>
                <?php endforeach; else : ?>
                <tr><td colspan="7">No dummy users generated yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </form>

<?php endif; ?>

</div>

