<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- View template, variables are locally scoped.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Read-only tab navigation.
$current_tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'generate'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$plugin_page = 'sbpai-woocommerce';
?>
<div class="sbpai-view-header" style="display:flex; justify-content:space-between; align-items:center;">
    <div>
        <h2>WooCommerce Automation</h2>
        <p>Generate production-level stores with accurate variables, linked orders, and reviews.</p>
    </div>

</div>

<?php if ( ! class_exists('WooCommerce') ) : ?>
    <div style="background: #fef2f2; border: 1px solid #f87171; padding: 20px; border-radius: 8px; margin-top: 20px;">
        <h3 style="color: #dc2626; margin-top:0;">⚠️ WooCommerce is Not Active</h3>
        <p style="color: #991b1b; font-size: 15px; margin-bottom: 0;">The SandboxPress AI eCommerce simulation engine strictly requires WooCommerce to be installed and activated on your website. Please activate it to unlock this module.</p>
    </div>
<?php else : ?>

<div class="sbpai-tab-nav">
    <a href="?page=<?php echo esc_attr( $plugin_page ); ?>&tab=generate" class="<?php echo $current_tab === 'generate' ? 'active' : ''; ?>">Generate WooCommerce Data</a>
    <a href="?page=<?php echo esc_attr( $plugin_page ); ?>&tab=quick_setup" class="<?php echo $current_tab === 'quick_setup' ? 'active' : ''; ?>">Store Setup</a>
    <a href="?page=<?php echo esc_attr( $plugin_page ); ?>&tab=list_products" class="<?php echo $current_tab === 'list_products' ? 'active' : ''; ?>">View Dummy Products</a>
    <a href="?page=<?php echo esc_attr( $plugin_page ); ?>&tab=list_orders" class="<?php echo $current_tab === 'list_orders' ? 'active' : ''; ?>">View Dummy Orders</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>
                <!-- Product Generation Limits -->
                <tr>
                    <th><label>Simple Products</label></th>
                    <td>
                        <input type="number" id="sbpai-wc-count-simple" class="sbpai-input" value="10" min="0" style="max-width: 100px;">
                        <p class="description" style="display:inline-block; margin-left:10px;">Number of basic products to generate.</p>
                    </td>
                </tr>
                <tr>
                    <th><label>Variable Products</label></th>
                    <td>
                        <input type="number" id="sbpai-wc-count-variable" class="sbpai-input" value="0" min="0" style="max-width: 100px;">
                        <p class="description" style="display:inline-block; margin-left:10px;">Products with attributes like Size and Color.</p>
                    </td>
                </tr>
                <tr>
                    <th><label>Grouped Products</label></th>
                    <td>
                        <input type="number" id="sbpai-wc-count-grouped" class="sbpai-input" value="0" min="0" style="max-width: 100px;">
                        <p class="description" style="display:inline-block; margin-left:10px;">Products that bundle simple products together.</p>
                    </td>
                </tr>
                <tr>
                    <th><label>Virtual/Digital Products</label></th>
                    <td>
                        <input type="number" id="sbpai-wc-count-virtual" class="sbpai-input" value="0" min="0" style="max-width: 100px;">
                        <p class="description" style="display:inline-block; margin-left:10px;">Intangible items (e.g. Services, eBooks) downloaded upon purchase.</p>
                    </td>
                </tr>
                <tr>
                    <th><label>Random Dummy Orders</label></th>
                    <td>
                        <div style="margin-bottom: 15px;">
                            <label style="display:block; margin-bottom:5px;"><strong>Standalone Orders:</strong></label>
                            <input type="number" id="sbpai-wc-count-orders-standalone" class="sbpai-input" value="0" min="0" style="max-width: 100px;">
                            <p class="description" style="display:inline-block; margin-left:10px;">Exact number of randomized purchase histories to mock.</p>
                        </div>
                        <div style="padding: 12px; background: #f0f0f1; border-left: 4px solid #72aee6;">
                            <label style="font-weight: 600;">
                                <input type="checkbox" id="sbpai-wc-orders"> Also Auto-Create Order on Product Creation
                            </label>
                            <p class="description" style="margin-top:5px; margin-bottom:0;">Check this to dynamically spawn an order whenever a new product generates.</p>
                        </div>
                    </td>
                </tr>

                <!-- Content Source Engine -->
                <tr>
                    <th><label>Content Source Engine</label></th>
                    <td>
                        <select id="sbpai-wc-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">How the description and short descriptions are built.</p>
                    </td>
                </tr>

                <!-- Price Range -->
                <tr>
                    <th><label>Price Range Constraints</label></th>
                    <td>
                        <div class="date-wrap">
                            <span>Min $</span> <input type="number" id="sbpai-wc-price-min" class="sbpai-input" value="10" style="max-width:80px;">
                            <span style="margin-left: 10px;">Max $</span> <input type="number" id="sbpai-wc-price-max" class="sbpai-input" value="500" style="max-width:80px;">
                        </div>
                        <p class="description">Prices will randomize safely within this spectrum per variation or simple product.</p>
                    </td>
                </tr>

                <!-- Stock Status -->
                <tr>
                    <th><label>Stock Status Bias</label></th>
                    <td>
                        <select id="sbpai-wc-stock" class="sbpai-input" style="max-width: 200px;">
                            <option value="random">Randomized</option>
                            <option value="instock">Always In Stock</option>
                            <option value="outofstock">Always Out of Stock</option>
                        </select>
                    </td>
                </tr>

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

                <tr>
                    <th><label>Include Featured Images</label></th>
                    <td>
                        <input type="checkbox" id="sbpai-wc-image" checked>
                        <p class="description" style="display:inline-block; margin-left:5px;">Sideloads dynamic JPGs mapped to your global niche safely from external APIs.</p>
                    </td>
                </tr>

                <tr>
                    <th><label>Generate Tags/Categories</label></th>
                    <td>
                        <input type="checkbox" id="sbpai-wc-terms" checked>
                        <p class="description" style="display:inline-block; margin-left:5px;">Check this to smartly assign standard eCommerce taxonomies.</p>
                    </td>
                </tr>


                <tr>
                    <th><label>Auto-Generate Coupons</label></th>
                    <td>
                        <input type="checkbox" id="sbpai-wc-coupons">
                        <p class="description" style="display:inline-block; margin-left:5px;">Hooks coupon creation tasks into the Action Scheduler.</p>
                    </td>
                </tr>
                
                <tr>
                    <th><label>Auto-Generate Reviews</label></th>
                    <td>
                        <input type="checkbox" id="sbpai-wc-reviews" checked>
                        <p class="description" style="display:inline-block; margin-left:5px;">Injects 1-5 star custom comments onto the generated products.</p>
                    </td>
                </tr>

                <tr>
                    <th><label>ACF Field Support</label></th>
                    <td>
                        <input type="checkbox" id="sbpai-wc-acf" checked>
                        <p class="description" style="display:inline-block; margin-left:5px;">If Advanced Custom Fields is installed, auto-detects and populates them for Products.</p>
                    </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="woocommerce" data-input="sbpai-products-count">Generate eCommerce Simulation</button>
            <div class="sbpai-progress" id="progress-woocommerce"></div>
        </div>

    <?php elseif ( $current_tab === 'quick_setup' ) : ?>
        
        <table class="sbpai-form-table">
            <tbody>
                <tr class="sbpai-table-section-head">
                    <td colspan="2"><h3>Dummy Store Information</h3></td>
                </tr>
                <tr>
                    <th><label>Store Address</label></th>
                    <td>
                        <input type="text" id="sbpai-setup-address" class="sbpai-input" value="123 Dummy Protocol St." style="width:100%; max-width:300px;">
                    </td>
                </tr>
                <tr>
                    <th><label>City</label></th>
                    <td>
                        <input type="text" id="sbpai-setup-city" class="sbpai-input" value="New York" style="max-width:200px;">
                    </td>
                </tr>
                <tr>
                    <th><label>Country / State Code</label></th>
                    <td>
                        <input type="text" id="sbpai-setup-country" class="sbpai-input" value="US:NY" style="max-width:100px;">
                        <p class="description">Format: CountryCode or CountryCode:StateCode (e.g. US:NY or GB)</p>
                    </td>
                </tr>
                <tr>
                    <th><label>Postcode</label></th>
                    <td>
                        <input type="text" id="sbpai-setup-postcode" class="sbpai-input" value="10001" style="max-width:100px;">
                    </td>
                </tr>
                <tr>
                    <th><label>Currency</label></th>
                    <td>
                        <input type="text" id="sbpai-setup-currency" class="sbpai-input" value="USD" style="max-width:80px;">
                        <p class="description">3-letter currency code (USD, EUR, GBP, INR)</p>
                    </td>
                </tr>

                <tr class="sbpai-table-section-head">
                    <td colspan="2"><h3>Configuration Ecosystem</h3></td>
                </tr>
                <tr>
                    <th><label>Enable Taxes</label></th>
                    <td>
                        <input type="checkbox" id="sbpai-setup-tax" checked>
                        <p class="description" style="display:inline-block; margin-left:5px;">Check to enable standard tax calculations during checkout.</p>
                    </td>
                </tr>
                <tr>
                    <th><label>Enable Shipping Integration</label></th>
                    <td>
                        <input type="checkbox" id="sbpai-setup-shipping" checked>
                        <p class="description" style="display:inline-block; margin-left:5px;">Unlocks zones and shipping requirement logic natively.</p>
                    </td>
                </tr>

                <tr class="sbpai-table-section-head">
                    <td colspan="2"><h3>Payment Gateways</h3></td>
                </tr>
                <tr>
                    <th><label>Cash on Delivery (COD)</label></th>
                    <td><input type="checkbox" id="sbpai-setup-cod" checked></td>
                </tr>
                <tr>
                    <th><label>Direct Bank Transfer (BACS)</label></th>
                    <td><input type="checkbox" id="sbpai-setup-bacs"></td>
                </tr>
                <tr>
                    <th><label>Check Payments</label></th>
                    <td><input type="checkbox" id="sbpai-setup-cheque"></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-run-store-setup" style="font-size: 16px; padding: 10px 24px; background:#f59e0b; border:none; color:white;">Configure Store Options</button>
            <button class="sbpai-btn" id="sbpai-reset-store-setup" style="font-size: 16px; padding: 10px 24px; background:transparent; border:1px solid #ef4444; color:#ef4444;">Clear All Settings</button>
        </div>

    <?php elseif ( $current_tab === 'list_products' ) : 
        // Handle Inline Bulk Deletion for Products
        if ( isset( $_POST['bulk_action'] ) && 'delete' === $_POST['bulk_action'] && ! empty( $_POST['bulk_ids'] ) ) {
            check_admin_referer( 'sbpai_bulk_action_nonce' );
            $count = 0;
            foreach ( array_map( 'intval', (array) wp_unslash( $_POST['bulk_ids'] ) ) as $sbpai_pid ) {
                $sbpai_prod = wc_get_product( $sbpai_pid );
                if ( $sbpai_prod ) { $sbpai_prod->delete( true ); $count++; }
            }
            // translators: %d is the number of products deleted.
            echo '<div class="notice notice-success is-dismissible" style="margin-top:20px;"><p>' . sprintf( esc_html__( 'Successfully deleted %d products.', 'sandboxpress-ai' ), intval( $count ) ) . '</p></div>';
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash
        $filter_wc = isset( $_GET['filter_type'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_type'] ) ) : '';
        // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Admin-only dummy tracking query.
        $query_args = array(
            'limit'      => 100,
            'orderby'    => 'date',
            'order'      => 'DESC',
            'meta_key'   => '_sbpai_product',
            'meta_value' => '1'
        );
        // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
        if ( !empty($filter_wc) ) { $query_args['type'] = $filter_wc; }
    ?>
        
        <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_products">
            <select name="filter_type" style="max-width: 200px;">
                <option value="">All Product Types</option>
                <option value="simple" <?php selected($filter_wc, 'simple'); ?>>Simple Products</option>
                <option value="variable" <?php selected($filter_wc, 'variable'); ?>>Variable Products</option>
                <option value="grouped" <?php selected($filter_wc, 'grouped'); ?>>Grouped Products</option>
            </select>
            <button type="submit" class="button">Filter</button>
        </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 id="cb" class="manage-column column-cb check-column"><input id="cb-select-all-prods" type="checkbox"></td>
                        <th>Product</th>
                        <th>SKU/Type</th>
                        <th>Price</th>
                        <th>Stock</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ( !class_exists('WooCommerce') ) {
                        echo "<tr><td colspan='7'>WooCommerce is not installed.</td></tr>";
                    } else {
                        $dummy_products = wc_get_products( $query_args );

                        if ( ! empty( $dummy_products ) ) {
                            foreach ( $dummy_products as $p ) {
                                $edit_link = get_edit_post_link( $p->get_id() );
                                $type      = ucfirst($p->get_type());
                                $price_html = $p->get_price_html();
                                $stock     = $p->get_stock_status() === 'instock' ? 'In Stock' : 'Out of Stock';

                                echo '<tr>';
                                echo '<th scope="row" class="check-column"><input type="checkbox" name="bulk_ids[]" value="' . esc_attr( $p->get_id() ) . '"></th>';
                                echo '<td><strong><a href="' . esc_url( $edit_link ) . '">' . esc_html( $p->get_name() ) . '</a></strong></td>';
                                echo '<td>' . esc_html( $type ) . '</td>';
                                echo '<td>' . wp_kses_post( $price_html ) . '</td>';
                                echo '<td>' . esc_html( $stock ) . '</td>';
                                echo '<td>' . esc_html( $p->get_date_created()->date( 'Y-m-d' ) ) . '</td>';
                                echo '<td><a href="' . esc_url( get_delete_post_link( $p->get_id() ) ) . '" style="color:#dc3232;">Delete</a></td>';
                                echo '</tr>';
                            }
                        } else {
                            echo "<tr><td colspan='7'>No advanced dummy products generated yet.</td></tr>";
                        }
                    }
                    ?>
                </tbody>
            </table>
        </form>

    <?php elseif ( $current_tab === 'list_orders' ) :
        // Handle Inline Bulk Deletion for Orders
        if ( isset( $_POST['bulk_action'] ) && 'delete' === $_POST['bulk_action'] && ! empty( $_POST['bulk_ids'] ) ) {
            check_admin_referer( 'sbpai_bulk_action_nonce' );
            $count = 0;
            foreach ( array_map( 'intval', (array) wp_unslash( $_POST['bulk_ids'] ) ) as $sbpai_ord_pid ) {
                $sbpai_ord = wc_get_order( $sbpai_ord_pid );
                if ( $sbpai_ord ) { $sbpai_ord->delete( true ); $count++; }
            }
            // translators: %d is the number of orders deleted.
            echo '<div class="notice notice-success is-dismissible" style="margin-top:20px;"><p>' . sprintf( esc_html__( 'Successfully deleted %d orders.', 'sandboxpress-ai' ), intval( $count ) ) . '</p></div>';
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash
        $filter_order   = isset( $_GET['filter_type'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_type'] ) ) : '';
        // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Admin-only dummy tracking query.
        $query_args_ord = array(
            'limit'      => 100,
            'orderby'    => 'date',
            'order'      => 'DESC',
            'meta_key'   => '_sbpai_order',
            'meta_value' => '1'
        );
        // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
        if ( ! empty( $filter_order ) ) { $query_args_ord['status'] = $filter_order; }
    ?>

        <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_orders">
            <select name="filter_type" style="max-width: 200px;">
                <option value="">All Statuses</option>
                <option value="completed" <?php selected($filter_order, 'completed'); ?>>Completed</option>
                <option value="processing" <?php selected($filter_order, 'processing'); ?>>Processing</option>
                <option value="on-hold" <?php selected($filter_order, 'on-hold'); ?>>On-Hold</option>
                <option value="cancelled" <?php selected($filter_order, 'cancelled'); ?>>Cancelled</option>
            </select>
            <button type="submit" class="button">Filter</button>
        </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 id="cb" class="manage-column column-cb check-column"><input id="cb-select-all-orders" type="checkbox"></td>
                        <th>Order #</th>
                        <th>Customer</th>
                        <th>Total</th>
                        <th>Status</th>
                        <th>Items</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ( !class_exists('WooCommerce') ) {
                        echo "<tr><td colspan='7'>WooCommerce is not installed.</td></tr>";
                    } else {
                        $dummy_orders = wc_get_orders( $query_args_ord );

                        if ( ! empty( $dummy_orders ) ) {
                            foreach ( $dummy_orders as $order ) {
                                $edit_link = $order->get_edit_order_url();
                                $name      = $order->get_formatted_billing_full_name();
                                $total     = $order->get_formatted_order_total();
                                $status    = wc_get_order_status_name( $order->get_status() );
                                $items     = $order->get_item_count();

                                echo '<tr>';
                                echo '<th scope="row" class="check-column"><input type="checkbox" name="bulk_ids[]" value="' . esc_attr( $order->get_id() ) . '"></th>';
                                echo '<td><strong><a href="' . esc_url( $edit_link ) . '">#' . esc_html( $order->get_id() ) . '</a></strong></td>';
                                echo '<td>' . esc_html( $name ) . '</td>';
                                echo '<td>' . wp_kses_post( $total ) . '</td>';
                                echo '<td>' . esc_html( $status ) . '</td>';
                                echo '<td>' . esc_html( $items ) . ' ' . esc_html__( 'items', 'sandboxpress-ai' ) . '</td>';
                                echo '<td><a href="' . esc_url( get_delete_post_link( $order->get_id() ) ) . '" style="color:#dc3232;">Delete</a></td>';
                                echo '</tr>';
                            }
                        } else {
                            echo "<tr><td colspan='7'>No advanced dummy orders generated yet.</td></tr>";
                        }
                    }
                    ?>
                </tbody>
            </table>
        </form>

    <?php endif; ?>

</div>
<?php endif; ?>

