<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- View template, variables are locally scoped.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Tab navigation only.
$current_tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'generate'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$plugin_page = 'sbpai-content';
?>
<div class="sbpai-view-header">
    <h2>Generate Posts</h2>
    <p>Advanced Content Generation matching the classic flow, supercharged by AI.</p>
</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 Posts</a>
    <a href="?page=<?php echo esc_attr( $plugin_page ); ?>&tab=list" class="<?php echo $current_tab === 'list' ? 'active' : ''; ?>">View Fake Posts</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>
                <!-- Post Type -->
                <tr>
                    <th><label>Choose Post type</label></th>
                    <td>
                        <select id="sbpai-post-type" class="sbpai-input" style="max-width: 200px;">
                            <?php 
                            $post_types = get_post_types( array('public' => true), 'objects' );
                            foreach( $post_types as $pt ) {
                                if ( $pt->name === 'attachment' || $pt->name === 'product' ) continue;
                                echo '<option value="' . esc_attr( $pt->name ) . '">' . esc_html( $pt->label ) . '</option>';
                            }
                            ?>
                        </select>
                        <p class="description">Choose the post type for which you want to generate the dummy data.</p>
                    </td>
                </tr>

                <!-- Number of Posts -->
                <tr>
                    <th><label>Number of posts</label></th>
                    <td>
                        <input type="number" id="sbpai-posts-count" class="sbpai-input" value="10" min="1" max="5000" style="max-width: 100px;">
                        <p class="description">Enter the number of posts you want to generate. Please use at a max of 5000</p>
                    </td>
                </tr>

                <!-- Date Range -->
                <tr>
                    <th><label>Posts date range</label></th>
                    <td>
                        <div class="date-wrap">
                            <span>From</span> <input type="date" id="sbpai-date-from" class="sbpai-input">
                            <span style="margin-left: 10px;">To</span> <input type="date" id="sbpai-date-to" class="sbpai-input">
                        </div>
                        <p class="description">Choose the from and to date. The Plugin will pick any random date from this range to use as a post publish date.</p>
                    </td>
                </tr>

                <!-- Advanced Settings Section -->
                <tr class="sbpai-table-section-head">
                    <td colspan="2"><h3>Advanced Settings</h3></td>
                </tr>

                <tr>
                    <th><label>Content Engine (AI)</label></th>
                    <td>
                        <select id="sbpai-post-source" class="sbpai-input" style="max-width: 250px;">
                            <option value="hybrid">Hybrid (AI Title + Faker Content)</option>
                            <option value="ai">Full AI Contextual Generation</option>
                            <option value="faker">FakerPHP Speed Load</option>
                        </select>
                        <p class="description">Select how the post's text structure is generated.</p>
                    </td>
                </tr>

                <tr>
                    <th><label>Content Length</label></th>
                    <td>
                        <select id="sbpai-post-length" class="sbpai-input" style="max-width: 250px;">
                            <option value="medium">Medium (Standard article)</option>
                            <option value="short">Short (Brief update)</option>
                            <option value="long">Long (In-depth guide)</option>
                        </select>
                        <p class="description">Determine the length of the generated body text.</p>
                    </td>
                </tr>

                <tr>
                    <th><label>Page Builder Format</label></th>
                    <td>
                        <select id="sbpai-post-builder" class="sbpai-input" style="max-width: 250px;">
                            <option value="gutenberg">Gutenberg (Native Block HTML)</option>
                            <option value="elementor">Elementor (JSON Meta)</option>
                            <option value="divi">Divi Builder (Shortcodes)</option>
                            <option value="wpbakery">WPBakery (Visual Composer)</option>
                            <option value="bricks">Bricks Builder (JSON Meta)</option>
                            <option value="html">Basic HTML Framework</option>
                        </select>
                        <p class="description">Target output mapping to a specific Visual Builder.</p>
                    </td>
                </tr>

                <tr>
                    <th><label>Status & Author</label></th>
                    <td>
                        <select id="sbpai-post-status" class="sbpai-input" style="max-width: 150px;">
                            <option value="publish">Published</option>
                            <option value="draft">Draft</option>
                            <option value="pending">Pending</option>
                        </select>
                        <select id="sbpai-post-author" class="sbpai-input" style="max-width: 200px; margin-left:10px;">
                            <option value="random">Random Existing User</option>
                            <option value="<?php echo esc_attr( get_current_user_id() ); ?>">Current User</option>
                        </select>
                        <p class="description">Configure the publish status and who the post is assigned to.</p>
                    </td>
                </tr>

                <tr>
                    <th><label>Featured Image/Thumbnail</label></th>
                    <td>
                        <input type="checkbox" id="sbpai-post-image" checked>
                        <p class="description" style="display:inline-block; margin-left:5px;">Check this if you want to generate a featured image for these dummy posts.</p>
                    </td>
                </tr>

                <tr>
                    <th><label>Generate/assign terms</label></th>
                    <td>
                        <input type="checkbox" id="sbpai-post-terms" checked>
                        <p class="description" style="display:inline-block; margin-left:5px;">Check this if you want to attach terms to these dummy posts. Automatically generates and links fake taxonomies.</p>
                    </td>
                </tr>

                <tr>
                    <th><label>Simulate User Comments</label></th>
                    <td>
                        <div style="padding: 10px; background: #f0f0f1; border-left: 4px solid #72aee6; display:inline-block; margin-top:5px;">
                            <label style="font-weight: 600;">
                                <input type="checkbox" id="sbpai-post-comments"> Inject Dummy User Comments
                            </label>
                            <p class="description" style="margin-top:5px; margin-bottom:0;">Randomly adds 0-5 realistic comments to the post using your existing Dummy Users (along with their fake avatars!).</p>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>

        <div style="margin-top: 30px; display:flex; gap:15px; align-items:center;">
            <button class="sbpai-btn sbpai-btn-primary sbpai-generate-btn" style="font-size: 16px; padding: 10px 24px; background:#10b981;" data-type="posts" data-input="sbpai-posts-count">Generate posts</button>
            <div class="sbpai-progress" id="progress-posts"></div>
        </div>

    <?php elseif ( $current_tab === 'list' ) : 
        
        // Handle Inline Bulk Deletion
        if ( 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 $pid ) {
                if ( wp_delete_post( intval($pid), true ) ) $count++;
            }
            // translators: %d is the number of posts/items deleted.
            echo '<div class="notice notice-success is-dismissible" style="margin-top:20px;"><p>' . sprintf( esc_html__( 'Successfully deleted %d items.', 'sandboxpress-ai' ), intval( $count ) ) . '</p></div>';
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash
        $filter_pt = isset( $_GET['filter_type'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_type'] ) ) : 'any';
    ?>

        <!-- Filter Tools -->
        <form method="GET" style="margin-bottom: 10px; 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_type" style="max-width: 200px;">
                <option value="any">All Post Types</option>
                <?php 
                $post_types = get_post_types( array('public' => true), 'objects' );
                foreach( $post_types as $pt ) {
                    if ( $pt->name === 'attachment' ) continue;
                    echo '<option value="' . esc_attr( $pt->name ) . '"' . selected( $filter_pt, $pt->name, false ) . '>' . esc_html( $pt->label ) . '</option>';
                }
                ?>
            </select>
            <button type="submit" class="button">Filter</button>
        </form>

        <!-- Bulk Action List -->
        <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 id="cb" class="manage-column column-cb check-column"><input id="cb-select-all" type="checkbox"></td>
                        <th>Title</th>
                        <th>Post Type</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Author</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Intentional admin-only dummy tracking query.
                    $dummy_posts = get_posts( array(
                        'post_type'      => $filter_pt,
                        'post_status'    => 'any',
                        'meta_key'       => '_sbpai_post',
                        'meta_value'     => '1',
                        'posts_per_page' => 100,
                        'orderby'        => 'date',
                        'order'          => 'DESC'
                    ) );
                    // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value

                    if ( ! empty( $dummy_posts ) ) {
                        foreach ( $dummy_posts as $p ) {
                            $author_info = get_userdata($p->post_author);
                            $author_name = $author_info ? $author_info->user_nicename : 'Unknown';
                            $edit_link = get_edit_post_link( $p->ID );
                            echo '<tr>';
                            echo '<th scope="row" class="check-column"><input type="checkbox" name="bulk_ids[]" value="' . esc_attr( $p->ID ) . '"></th>';
                            echo '<td><strong><a href="' . esc_url( $edit_link ) . '">' . esc_html( $p->post_title ) . '</a></strong></td>';
                            echo '<td>' . esc_html( $p->post_type ) . '</td>';
                            echo '<td>' . esc_html( $p->post_status ) . '</td>';
                            echo '<td>' . esc_html( $p->post_date ) . '</td>';
                            echo '<td>' . esc_html( $author_name ) . '</td>';
                            echo '<td><a href="' . esc_url( get_delete_post_link( $p->ID ) ) . '" style="color:#dc3232;">Delete Permanently</a></td>';
                            echo '</tr>';
                        }
                    } else {
                        echo "<tr><td colspan='7'>No advanced dummy content generated yet.</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </form>
        <p class="description" style="margin-top: 15px;">Showing the last 100 generated items. You can perform bulk sweeps in the Global Settings tab.</p>

    <?php endif; ?>

</div>

