<?php
/**
 * Bizmart — Products list template.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals

(static function() {

// Pagination
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$paged = isset($_GET['paged']) ? max(1, intval(wp_unslash($_GET['paged']))) : 1;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$limit = isset($_GET['limit']) ? max(1, intval(wp_unslash($_GET['limit']))) : 20;
if (!in_array($limit, [10, 20, 50, 100])) {
    $limit = 20;
}
$offset = ($paged - 1) * $limit;

// Order & Orderby
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$orderby = isset($_GET['orderby']) ? sanitize_key(wp_unslash($_GET['orderby'])) : 'date';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$order = isset($_GET['order']) ? strtoupper(sanitize_key(wp_unslash($_GET['order']))) : 'DESC';
if (!in_array($order, ['ASC', 'DESC'])) {
    $order = 'DESC';
}

// Hook into the WooCommerce product query args filter to apply custom sorting safely (bypassing WooCommerce meta query stripping)
add_filter('woocommerce_product_data_store_cpt_get_products_query', function($wp_query_args, $query_vars) {
    if (isset($query_vars['bizmart_custom_orderby'])) {
        $orderby = $query_vars['bizmart_custom_orderby'];
        $order = $query_vars['order'] ?? 'DESC';
        
        if ($orderby === 'cost') {
            $wp_query_args['meta_query'][] = [
                'relation' => 'OR',
                'cost_clause' => [
                    'key'     => '_purchase_price',
                    'type'    => 'NUMERIC',
                    'compare' => 'EXISTS',
                ],
                'no_cost_clause' => [
                    'key'     => '_purchase_price',
                    'compare' => 'NOT EXISTS',
                ],
            ];
            $wp_query_args['orderby'] = [
                'cost_clause' => $order,
            ];
        } elseif ($orderby === 'stock') {
            $wp_query_args['meta_query'][] = [
                'relation' => 'OR',
                'stock_clause' => [
                    'key'     => '_stock',
                    'type'    => 'NUMERIC',
                    'compare' => 'EXISTS',
                ],
                'no_stock_clause' => [
                    'key'     => '_stock',
                    'compare' => 'NOT EXISTS',
                ],
            ];
            $wp_query_args['orderby'] = [
                'stock_clause' => $order,
            ];
        } elseif ($orderby === 'sku') {
            $wp_query_args['meta_query'][] = [
                'relation' => 'OR',
                'sku_clause' => [
                    'key'     => '_sku',
                    'compare' => 'EXISTS',
                ],
                'no_sku_clause' => [
                    'key'     => '_sku',
                    'compare' => 'NOT EXISTS',
                ],
            ];
            $wp_query_args['orderby'] = [
                'sku_clause' => $order,
            ];
        } elseif ($orderby === 'status') {
            add_filter('posts_orderby', function($orderby_sql) use ($order) {
                global $wpdb;
                return "{$wpdb->posts}.post_status {$order}, {$wpdb->posts}.post_date DESC";
            });
        }
    }
    return $wp_query_args;
}, 10, 2);

// Query Products
$args = [
    'limit' => $limit,
    'offset' => $offset,
    'status' => ['publish', 'draft', 'private'],
    'paginate' => true,
];

$args['order'] = $order;

if ($orderby === 'name') {
    $args['orderby'] = 'title';
} elseif ($orderby === 'price') {
    $args['orderby'] = 'price';
} elseif ($orderby === 'id') {
    $args['orderby'] = 'id';
} elseif (in_array($orderby, ['cost', 'stock', 'sku', 'status'])) {
    $args['bizmart_custom_orderby'] = $orderby;
} else {
    $args['orderby'] = 'date';
}

// Handle Search
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$search = isset($_GET['s']) ? sanitize_text_field(wp_unslash($_GET['s'])) : '';
if (!empty($search)) {
    $args['s'] = $search;
}

$product_query = wc_get_products($args);
$products = $product_query->products;
$total_products = $product_query->total;
$total_pages = $product_query->max_num_pages;

// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$page_param = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

$sort_icon_func = function($field) use ($orderby, $order) {
    if ($orderby === $field) {
        return ($order === 'ASC') ? '🔼' : '🔽';
    }
    return '↕️';
};
?>

<!-- Style 1 moved to assets/products.css -->

<div class="biz-card" style="background: transparent; box-shadow: none; padding: 0; overflow: visible !important;">
    
    <!-- Header with Search -->
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <div>
            <h2 style="margin: 0; color: #111827; font-size: 24px; font-weight: 700;">📦 <?php echo esc_html(bizmart_text('Inventory', 'Inventaire', 'المخزون')); ?></h2>
            <p style="margin: 4px 0 0 0; color: #6b7280; font-size: 14px;"><?php echo esc_html(bizmart_text('Manage your products, prices, and stock levels.', 'Gérez vos produits, prix et stocks.', 'إدارة منتجاتك وأسعارك ومستويات المخزون.')); ?></p>
        </div>
        
        <form method="get" style="display: flex; gap: 12px; align-items: center;">
            <input type="hidden" name="page" value="<?php echo esc_attr($page_param); ?>">
            <input type="hidden" name="view" value="list">
            <?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
            <?php if (isset($_GET['orderby'])) : ?>
                <?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
                <input type="hidden" name="orderby" value="<?php echo esc_attr(sanitize_key($_GET['orderby'])); ?>">
            <?php endif; ?>
            <?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
            <?php if (isset($_GET['order'])) : ?>
                <?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
                <input type="hidden" name="order" value="<?php echo esc_attr(sanitize_key($_GET['order'])); ?>">
            <?php endif; ?>

            <!-- Page Size Limit Dropdown -->
            <div style="display: flex; align-items: center; background: white; border: 1px solid #e2e8f0; border-radius: 12px; padding: 4px 12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); height: 38px; box-sizing: border-box;">
                <span style="font-size: 13px; color: #64748b; font-weight: 600; margin-right: 6px; display: inline-flex; align-items: center; gap: 4px;">📄 <?php echo esc_html(bizmart_text('Show:', 'Afficher :', 'عرض:')); ?></span>
                <select name="limit" onchange="this.form.submit()" style="border: none; background: transparent; font-size: 13px; font-weight: 700; color: #1e293b; outline: none; cursor: pointer; padding: 0 4px; height: 100%;">
                    <?php
                    $limits = [10, 20, 50, 100];
                    foreach ($limits as $l) {
                        $selected = ($limit === $l) ? 'selected' : '';
                        echo '<option value="' . intval($l) . '" ' . esc_attr($selected) . '>' . intval($l) . '</option>';
                    }
                    ?>
                </select>
            </div>

            <!-- Search -->
            <div style="display: flex; align-items: center; background: white; border: 1px solid #e2e8f0; border-radius: 12px; padding: 4px 12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); height: 38px; box-sizing: border-box;">
                <span style="font-size: 16px; margin-right: 4px;">🔍</span>
                <input type="text" name="s" value="<?php echo esc_attr($search); ?>" placeholder="<?php echo esc_attr(bizmart_text('Search products...', 'Rechercher...', 'بحث عن منتجات...')); ?>" class="biz-input" style="width: 200px; border:none; padding: 4px 0; outline: none; background: transparent; font-size: 13px; font-weight: 600; color: #1e293b;">
            </div>
        </form>
    </div>

    <?php if (empty($products)) : ?>
        <div class="biz-alert biz-alert-info" style="border-radius: 12px; border: none; background: #eff6ff; color: #1e40af; padding: 20px;">
            <?php echo esc_html(bizmart_text('No products found matching your search.', 'Aucun produit ne correspond à votre recherche.', 'لم يتم العثور على منتجات مطابقة لبحثك.')); ?>
        </div>
    <?php else : ?>
        <div class="biz-table-wrapper">
            <table class="biz-table">
                <thead>
                    <tr>
                        <th class="biz-sortable" data-sort="id" style="cursor: pointer; user-select: none; width: 80px;"><?php echo esc_html(bizmart_text('Preview', 'Aperçu', 'معاينة')); ?> <span class="biz-sort-icon" style="margin-left: 4px; font-size: 11px; opacity: 0.7;"><?php echo esc_html($sort_icon_func('id')); ?></span></th>
                        <th class="biz-sortable" data-sort="name" style="cursor: pointer; user-select: none;"><?php echo esc_html(bizmart_text('Product', 'Produit', 'المنتج')); ?> <span class="biz-sort-icon" style="margin-left: 4px; font-size: 11px; opacity: 0.7;"><?php echo esc_html($sort_icon_func('name')); ?></span></th>
                        <th class="biz-sortable" data-sort="sku" style="cursor: pointer; user-select: none; width: 140px;"><?php echo esc_html(bizmart_text('SKU', 'UGS', 'SKU')); ?> <span class="biz-sort-icon" style="margin-left: 4px; font-size: 11px; opacity: 0.7;"><?php echo esc_html($sort_icon_func('sku')); ?></span></th>
                        <th class="biz-sortable" data-sort="price" style="cursor: pointer; user-select: none; width: 180px;"><?php echo esc_html(bizmart_text('Pricing', 'Tarification', 'التسعير')); ?> <span class="biz-sort-icon" style="margin-left: 4px; font-size: 11px; opacity: 0.7;"><?php echo esc_html($sort_icon_func('price')); ?></span></th>
                        <th class="biz-sortable" data-sort="cost" style="cursor: pointer; user-select: none; width: 140px;"><?php echo esc_html(bizmart_text('Cost', 'Coût', 'التكلفة')); ?> <span class="biz-sort-icon" style="margin-left: 4px; font-size: 11px; opacity: 0.7;"><?php echo esc_html($sort_icon_func('cost')); ?></span></th>
                        <th class="biz-sortable" data-sort="stock" style="cursor: pointer; user-select: none; width: 150px;"><?php echo esc_html(bizmart_text('Stock', 'Stock', 'المخزون')); ?> <span class="biz-sort-icon" style="margin-left: 4px; font-size: 11px; opacity: 0.7;"><?php echo esc_html($sort_icon_func('stock')); ?></span></th>
                        <th class="biz-sortable" data-sort="status" style="cursor: pointer; user-select: none; width: 150px;"><?php echo esc_html(bizmart_text('Status', 'Statut', 'الحالة')); ?> <span class="biz-sort-icon" style="margin-left: 4px; font-size: 11px; opacity: 0.7;"><?php echo esc_html($sort_icon_func('status')); ?></span></th>
                        <th style="width: 60px;"></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($products as $product) : 
                        $p_id = $product->get_id();
                        $image_url = wp_get_attachment_image_url($product->get_image_id(), 'thumbnail');
                        if (!$image_url) $image_url = wc_placeholder_img_src();
                        
                        $edit_link = admin_url('admin.php?page=bizmart-products&view=create&action=edit&id=' . $p_id);
                        
                        // Prices
                        $reg_price = $product->get_regular_price();
                        $sale_price = $product->get_sale_price();
                        // Cost price logic
                        $cost_price = get_post_meta($p_id, '_purchase_price', true);
                        if (!$cost_price) $cost_price = get_post_meta($p_id, '_alg_wc_cog_cost', true);

                        // Statuses
                        $stock_status = $product->get_stock_status();
                        $stock_qty = $product->get_stock_quantity();
                        $post_status = $product->get_status(); // publish, draft, private
                        
                        // Handle Variable Products Logic
                        $variations_html = '';
                        $is_variable = $product->is_type('variable');
                        $variable_total_stock = 0;
                        
                        if ($is_variable) {
                            $variations = $product->get_children();
                            if (!empty($variations)) {
                                foreach ($variations as $var_id) {
                                    $variation = wc_get_product($var_id);
                                    if (!$variation) continue;
                                    
                                    $v_stock = $variation->get_stock_quantity();
                                    $v_stock_status = $variation->get_stock_status();
                                    $v_price = $variation->get_price();
                                    $v_reg_price = $variation->get_regular_price();
                                    $v_sale_price = $variation->get_sale_price();
                                    $v_cost = get_post_meta($var_id, '_purchase_price', true);
                                    
                                    if ($v_stock && is_numeric($v_stock)) {
                                        $variable_total_stock += (int) $v_stock;
                                    }
                                    
                                    // Variation Attributes String
                                    $attributes = $variation->get_attributes();
                                    $attr_strings = [];
                                    foreach ($attributes as $key => $val) {
                                        // $val is essentially the slug, we want a label if possible, but slug is fine for list
                                        $attr_strings[] = ucfirst(str_replace('attribute_', '', $key)) . ': ' . $val;
                                    }
                                    $attr_desc = implode(', ', $attr_strings);
                                    
                                    $v_badge_class = 'biz-badge-gray';
                                    if ($v_stock_status === 'instock') $v_badge_class = 'biz-badge-success';
                                    elseif ($v_stock_status === 'outofstock') $v_badge_class = 'biz-badge-danger';
                                    
                                    // Variation Image
                                    $v_image_id = $variation->get_image_id();
                                    $v_img_html = '';
                                    if ($v_image_id) {
                                        $v_image_url = wp_get_attachment_image_url($v_image_id, 'thumbnail');
                                        if ($v_image_url) {
                                            $v_img_html = '<img src="' . esc_url($v_image_url) . '" class="biz-product-image" style="width: 32px; height: 32px; margin-left: 8px;">';
                                        }
                                    }

                                    $variations_html .= '<tr class="biz-variation-row" style="background: #fcfcfc;">
                                        <td>' . $v_img_html . '</td>
                                        <td style="padding-left: 40px;">
                                            <div style="display:flex; align-items:center; gap:10px;">
                                                <span style="font-size:18px; color:#9ca3af;">↳</span>
                                                <div>
                                                    <span style="font-size:13px; font-weight:600; color:#4b5563;">' . esc_html($attr_desc ?: "Variation #{$var_id}") . '</span>
                                                    <div style="font-size:11px; color:#9ca3af;">ID: ' . intval($var_id) . '</div>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span style="font-family:monospace; font-size:11px; color:#6b7280; background:#f3f4f6; padding:1px 5px; border-radius:3px;">
                                                ' . esc_html($variation->get_sku() ?: '---') . '
                                            </span>
                                        </td>
                                        <td>
                                            <span style="font-size:13px; color:#374151;">' . wc_price($v_price) . '</span>
                                        </td>
                                        <td>
                                            <span style="font-size:13px; color:#6b7280;">' . ($v_cost ? wc_price($v_cost) : '-') . '</span>
                                        </td>
                                        <td>
                                            <div class="biz-badge ' . $v_badge_class . '" style="padding: 2px 8px; font-size: 11px;">
                                                ' . ($v_stock !== null ? intval($v_stock) : esc_html($v_stock_status)) . '
                                            </div>
                                        </td>
                                        <td></td>
                                        <td style="text-align:right; white-space:nowrap;">
                                            <button type="button" onclick="BizPriceHistory.open(' . $var_id . ')" title="' . esc_attr(bizmart_text('Price History', 'Historique des Prix', 'سجل الأسعار')) . '" style="background:none; border:1px solid #e5e7eb; border-radius:50%; width:28px; height:28px; cursor:pointer; font-size:14px; transition:all 0.2s;" onmouseover="this.style.background=\'#eef2ff\'; this.style.borderColor=\'#6366f1\';" onmouseout="this.style.background=\'none\'; this.style.borderColor=\'#e5e7eb\';">📊</button>
                                        </td>
                                    </tr>';
                                }
                                // If parent has no managed stock but variations do, use sum
                                if (is_null($stock_qty) || $stock_qty === 0) {
                                    $stock_qty = $variable_total_stock;
                                }
                            }
                        }

                        // Determine Badge Colors/Labels for Stock
                        $stock_badge_class = 'biz-badge-gray';
                        $stock_label = bizmart_text('In Stock', 'En Stock', 'متوفر');
                        if ($stock_status === 'instock') {
                            $stock_badge_class = 'biz-badge-success';
                        } elseif ($stock_status === 'outofstock') {
                            $stock_badge_class = 'biz-badge-danger';
                            $stock_label = bizmart_text('Out of Stock', 'Rupture', 'غير متوفر');
                        } elseif ($stock_status === 'onbackorder') {
                            $stock_badge_class = 'biz-badge-warning';
                            $stock_label = bizmart_text('Backorder', 'Sur Commande', 'طلب مسبق');
                        }

                        // Determine Badge for Status
                        $status_badge_class = 'biz-badge-blue';
                        $status_label = bizmart_text('Online', 'En Ligne', 'متصل'); // Default publish
                        if ($post_status === 'draft') {
                            $status_badge_class = 'biz-badge-gray';
                            $status_label = bizmart_text('Draft', 'Brouillon', 'مسودة');
                        } elseif ($post_status === 'private') {
                            $status_badge_class = 'biz-badge-warning';
                            $status_label = bizmart_text('Private', 'Privé', 'خاص');
                        }

                        $currency = get_woocommerce_currency_symbol();
                    ?>
                    <tr data-product-id="<?php echo intval($p_id); ?>" data-stock="<?php echo intval($stock_qty); ?>" data-status-val="<?php echo esc_attr($post_status); ?>" data-sku="<?php echo esc_attr($product->get_sku()); ?>">
                        <!-- Image -->
                        <td>
                            <img src="<?php echo esc_url($image_url); ?>" class="biz-product-image">
                        </td>
                        
                        <!-- Name & Category -->
                        <td>
                            <a href="<?php echo esc_url($edit_link); ?>" class="biz-product-name"><?php echo esc_html($product->get_name()); ?></a>
                            <div style="font-size: 12px; color: #9ca3af; margin-top: 4px;">ID: <?php echo intval($p_id); ?></div>
                        </td>

                        <!-- SKU -->
                        <td>
                             <span style="font-family: 'Monaco', monospace; font-size: 12px; color: #6b7280; background: #f3f4f6; padding: 2px 6px; border-radius: 4px;">
                                <?php echo esc_html($product->get_sku() ?: '---'); ?>
                             </span>
                        </td>

                        <!-- Pricing (Reg + Sale) -->
                        <td>
                             <?php if ($product->is_type('variable')) : ?>
                                <div style="font-size: 13px; font-weight: 600; color: #4f46e5; background: #eef2ff; padding: 4px 10px; border-radius: 6px; display: inline-block;">
                                    <?php echo esc_html(bizmart_text('Variable', 'Variable', 'متغير')); ?>
                                </div>
                             <?php else : ?>
                                <div style="display: flex; flex-direction: column; gap: 4px;">
                                    <!-- Regular Price -->
                                    <div class="biz-ghost-input-wrapper" title="<?php echo esc_attr(bizmart_text('Regular Price', 'Prix Régulier', 'السعر العادي')); ?>">
                                        <span class="biz-currency-symbol"><?php echo esc_html($currency); ?></span>
                                        <input type="number" step="0.01" class="biz-ghost-input biz-quick-edit" data-field="regular_price" value="<?php echo esc_attr($reg_price); ?>" placeholder="0.00">
                                    </div>
                                    <!-- Sale Price (if any) -->
                                    <div class="biz-ghost-input-wrapper" title="<?php echo esc_attr(bizmart_text('Sale Price', 'Prix Promo', 'سعر التخفيض')); ?>">
                                        <span class="biz-currency-symbol" style="color: #ef4444; <?php echo ($sale_price === '' || $sale_price === null) ? 'display: none;' : ''; ?>"><?php echo esc_html($currency); ?></span>
                                        <input type="number" step="0.01" class="biz-ghost-input biz-quick-edit" data-field="sale_price" value="<?php echo esc_attr($sale_price); ?>" placeholder="Sale" style="color: #ef4444;">
                                    </div>
                                </div>
                             <?php endif; ?>
                        </td>

                        <!-- Cost -->
                        <td>
                            <?php if ($product->is_type('variable')) : ?>
                                <div style="font-size: 12px; color: #94a3b8; font-style: italic;">
                                    <?php echo esc_html(bizmart_text('See variations', 'Voir variations', 'عرض التنويعات')); ?>
                                </div>
                            <?php else : ?>
                                <div class="biz-ghost-input-wrapper" title="<?php echo esc_attr(bizmart_text('Cost Price', 'Prix d\'Achat', 'سعر التكلفة')); ?>">
                                    <span class="biz-currency-symbol"><?php echo esc_html($currency); ?></span>
                                    <input type="number" step="0.01" class="biz-ghost-input biz-quick-edit" data-field="purchase_price" value="<?php echo esc_attr($cost_price); ?>" placeholder="0.00" style="color: #6b7280;">
                                </div>
                            <?php endif; ?>
                        </td>

                        <!-- Stock Status Custom Dropdown -->
                        <td>
                            <div class="biz-status-dropdown" tabindex="0">
                                <div class="biz-badge <?php echo esc_attr($stock_badge_class); ?>">
                                    <?php echo esc_html($stock_label); ?> 
                                    <?php if (!is_null($stock_qty)) echo '(' . intval($stock_qty) . ')'; ?>
                                </div>
                                <div class="biz-dropdown-menu">
                                    <div class="biz-dropdown-item <?php echo esc_attr($stock_status === 'instock' ? 'selected' : ''); ?>" data-value="instock" data-field="stock_status" onclick="BizQuickEdit.updateStatus(this)">
                                        <div style="width: 8px; height: 8px; background: #10b981; border-radius: 50%; margin-right: 8px;"></div>
                                        <?php echo esc_html(bizmart_text('In Stock', 'En Stock', 'متوفر')); ?>
                                    </div>
                                    <div class="biz-dropdown-item <?php echo esc_attr($stock_status === 'outofstock' ? 'selected' : ''); ?>" data-value="outofstock" data-field="stock_status" onclick="BizQuickEdit.updateStatus(this)">
                                        <div style="width: 8px; height: 8px; background: #ef4444; border-radius: 50%; margin-right: 8px;"></div>
                                        <?php echo esc_html(bizmart_text('Out of Stock', 'Rupture', 'غير متوفر')); ?>
                                    </div>
                                    <div class="biz-dropdown-item <?php echo esc_attr($stock_status === 'onbackorder' ? 'selected' : ''); ?>" data-value="onbackorder" data-field="stock_status" onclick="BizQuickEdit.updateStatus(this)">
                                        <div style="width: 8px; height: 8px; background: #f59e0b; border-radius: 50%; margin-right: 8px;"></div>
                                        <?php echo esc_html(bizmart_text('Backorder', 'Sur Commande', 'طلب مسبق')); ?>
                                    </div>
                                </div>
                            </div>
                        </td>

                        <!-- Post Status Custom Dropdown -->
                        <td>
                             <div class="biz-status-dropdown" tabindex="0">
                                <div class="biz-badge <?php echo esc_attr($status_badge_class); ?>">
                                    <?php echo esc_html($status_label); ?>
                                </div>
                                <div class="biz-dropdown-menu">
                                    <div class="biz-dropdown-item <?php echo esc_attr($post_status === 'publish' ? 'selected' : ''); ?>" data-value="publish" data-field="post_status" onclick="BizQuickEdit.updateStatus(this)">
                                        🟢 <?php echo esc_html(bizmart_text('Online', 'En Ligne', 'متصل')); ?>
                                    </div>
                                    <div class="biz-dropdown-item <?php echo esc_attr($post_status === 'draft' ? 'selected' : ''); ?>" data-value="draft" data-field="post_status" onclick="BizQuickEdit.updateStatus(this)">
                                        ⚫ <?php echo esc_html(bizmart_text('Draft', 'Brouillon', 'مسودة')); ?>
                                    </div>
                                    <div class="biz-dropdown-item <?php echo esc_attr($post_status === 'private' ? 'selected' : ''); ?>" data-value="private" data-field="post_status" onclick="BizQuickEdit.updateStatus(this)">
                                        🔒 <?php echo esc_html(bizmart_text('Private', 'Privé', 'خاص')); ?>
                                    </div>
                                </div>
                            </div>
                        </td>

                        <td style="text-align: right; white-space:nowrap;">
                            <button type="button" onclick="BizPriceHistory.open(<?php echo intval($p_id); ?>)" title="<?php echo esc_attr(bizmart_text('Price History', 'Historique des Prix', 'سجل الأسعار')); ?>" style="background:none; border:1px solid #e5e7eb; border-radius:50%; width:32px; height:32px; cursor:pointer; font-size:16px; transition:all 0.2s; margin-right:4px;" onmouseover="this.style.background='#eef2ff'; this.style.borderColor='#6366f1';" onmouseout="this.style.background='none'; this.style.borderColor='#e5e7eb';">📊</button>
                            <a href="<?php echo esc_url($edit_link); ?>" title="<?php echo esc_attr(bizmart_text('Edit Details', 'Modifier', 'تعديل التفاصيل')); ?>" style="color: #9ca3af; text-decoration: none; font-size: 18px; padding: 8px; border-radius: 50%; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='transparent'">
                                ✏️
                            </a>
                        </td>
                    </tr>
                    <?php
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $variations_html is built with esc_html/esc_attr calls above
                    echo $variations_html;
                    ?>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- AJAX SCRIPT -->
        <script>
        window.BizQuickEdit = {
            nonce: '<?php echo esc_attr(wp_create_nonce('bizmart-analytics-nonce')); ?>',
            
            // Handle Ghost Input Changes
            initInputs: function() {
                var self = this;
                jQuery('.biz-ghost-input-wrapper').on('click', function() {
                    jQuery(this).find('input').focus();
                });
                
                jQuery('.biz-ghost-input-wrapper input').on('focus input', function() {
                    jQuery(this).parent().addClass('focus-within');
                    jQuery(this).siblings('.biz-currency-symbol').show();
                }).on('blur', function() {
                    jQuery(this).parent().removeClass('focus-within');
                    if (jQuery(this).val() === '') {
                        jQuery(this).siblings('.biz-currency-symbol').hide();
                    }
                }).on('change', function() {
                    self.saveInput(jQuery(this));
                });
            },

            initSorting: function() {
                var self = this;
                jQuery('.biz-sortable').on('click', function() {
                    var field = jQuery(this).data('sort');
                    var currentField = '<?php echo esc_js($orderby); ?>';
                    var currentOrder = '<?php echo esc_js($order); ?>';
                    
                    var newOrder = 'ASC';
                    if (field === currentField) {
                        newOrder = (currentOrder === 'ASC') ? 'DESC' : 'ASC';
                    }
                    
                    var url = new URL(window.location.href);
                    url.searchParams.set('orderby', field);
                    url.searchParams.set('order', newOrder);
                    url.searchParams.set('paged', '1');
                    
                    window.location.href = url.toString();
                });
            },
            
            saveInput: function($input) {
                var $wrapper = $input.closest('.biz-ghost-input-wrapper');
                var $row = $input.closest('tr');
                var productId = $row.data('product-id');
                var field = $input.data('field');
                var value = $input.val();
                
                // Visual Loading State
                $wrapper.removeClass('is-error is-success').addClass('is-saving');
                
                var data = {
                    action: 'bizmart_quick_update_product',
                    nonce: this.nonce,
                    product_id: productId
                };
                data[field] = value;
                
                jQuery.post(ajaxurl, data, function(response) {
                    $wrapper.removeClass('is-saving');
                    if (response.success) {
                        $wrapper.addClass('is-success');
                        setTimeout(function() { $wrapper.removeClass('is-success'); }, 2000);
                        // Refresh the current list and, if the dashboard opened this window, refresh it too
                        setTimeout(function() {
                            location.reload();
                            if (window.opener && !window.opener.closed) {
                                window.opener.location.reload();
                            }
                        }, 500);
                    } else {
                        $wrapper.addClass('is-error');
                        alert('Error: ' + (response.data || 'Unknown error'));
                    }
                }).fail(function(xhr, status, error) {
                    $wrapper.removeClass('is-saving').addClass('is-error');
                    // Try to extract message from JSON response
                    var msg = error;
                    if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                        msg = xhr.responseJSON.data.message;
                    } else if (xhr.responseJSON && xhr.responseJSON.data) {
                        msg = xhr.responseJSON.data;
                    }
                    alert('Save Failed: ' + msg);
                });
            },
            
            // Handle Custom Status Dropdowns
            updateStatus: function(element) {
                var $item = jQuery(element);
                var $dropdown = $item.closest('.biz-status-dropdown');
                var $badge = $dropdown.find('.biz-badge');
                var $row = $item.closest('tr');
                
                var productId = $row.data('product-id');
                var field = $item.data('field');
                var value = $item.data('value');
                var label = $item.text().trim(); // Capture label properly
                
                // Optimistic UI Update
                // 1. Update selection in menu
                $dropdown.find('.biz-dropdown-item').removeClass('selected');
                $item.addClass('selected');
                
                // 2. Update Badge Appearance
                $badge.css('opacity', '0.5'); // dim while saving
                
                // Determine new class (simplified logic for UI feedback)
                var newClass = 'biz-badge-gray';
                if (value === 'instock' || value === 'publish') newClass = 'biz-badge-success';
                else if (value === 'outofstock' || value === 'private') newClass = 'biz-badge-danger'; // or warning
                else if (value === 'onbackorder') newClass = 'biz-badge-warning';
                
                // Specific override for post status colors
                if(value === 'publish') newClass = 'biz-badge-blue';
                if(value === 'draft') newClass = 'biz-badge-gray';
                if(value === 'private') newClass = 'biz-badge-warning';
                
                var data = {
                    action: 'bizmart_quick_update_product',
                    nonce: this.nonce,
                    product_id: productId
                };
                data[field] = value;
                
                jQuery.post(ajaxurl, data, function(response) {
                    $badge.css('opacity', '1');
                    if (response.success) {
                        // Apply final styling from response if needed, or stick to optimistic
                        $badge.removeClass().addClass('biz-badge ' + newClass);
                        $badge.html(label); // Update text
                        $dropdown.blur(); // Close dropdown
                    } else {
                        alert('Error: ' + response.data);
                        // Revert visual state if needed
                    }
                }).fail(function(xhr, status, error) {
                     $badge.css('opacity', '1');
                     var msg = error;
                    if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                        msg = xhr.responseJSON.data.message;
                    } else if (xhr.responseJSON && xhr.responseJSON.data) {
                        msg = xhr.responseJSON.data;
                    }
                    alert('Update Failed: ' + msg);
                });
            }
        };

        jQuery(document).ready(function() {
            BizQuickEdit.initInputs();
            BizQuickEdit.initSorting();
        });
        </script>

        <!-- Pagination (Styled) -->
        <?php if ($total_pages > 1) : ?>
        <div style="margin-top: 24px; display: flex; justify-content: center;">
            <?php
            echo wp_kses_post(paginate_links([
                'base' => add_query_arg('paged', '%#%'),
                'format' => '',
                'current' => $paged,
                'total' => $total_pages,
                'prev_text' => '←',
                'next_text' => '→',
                'type' => 'list',
                'mid_size' => 2,
            ]));
            ?>
        </div>
        <!-- Style 2 moved to assets/products.css -->
        <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Price History Modal for Products List -->
<div id="biz-product-price-history-modal" style="display:none; position:fixed; inset:0; z-index:100000; background:rgba(0,0,0,0.5); backdrop-filter:blur(4px);">
    <div style="position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); background:#fff; border-radius:16px; width:700px; max-width:95vw; max-height:85vh; overflow:hidden; box-shadow:0 25px 50px rgba(0,0,0,0.25);">
        <div style="display:flex; align-items:center; justify-content:space-between; padding:20px 24px; border-bottom:1px solid #f1f5f9; background:#f9fafb;">
            <div>
                <h3 style="margin:0; font-size:18px; font-weight:700; color:#1f2937;">📊 <span id="biz-ph-modal-title"><?php echo esc_html(bizmart_text('Price History', 'Historique des Prix', 'سجل الأسعار')); ?></span></h3>
                <p id="biz-ph-modal-product" style="margin:4px 0 0; font-size:13px; color:#6b7280;"></p>
            </div>
            <button onclick="BizPriceHistory.close()" style="background:none; border:none; font-size:22px; cursor:pointer; color:#9ca3af; padding:4px 8px; border-radius:8px;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='none'">✕</button>
        </div>
        <div id="biz-ph-modal-body" style="padding:20px 24px; overflow-y:auto; max-height:calc(85vh - 80px);">
            <div style="text-align:center; padding:40px; color:#9ca3af;">
                <span class="biz-loading" style="width:24px; height:24px; display:inline-block;"></span>
            </div>
        </div>
    </div>
</div>

<script>
window.BizPriceHistory = {
    nonce: '<?php echo esc_attr(wp_create_nonce('bizmart-analytics-nonce')); ?>',

    open: function(productId) {
        var modal = document.getElementById('biz-product-price-history-modal');
        modal.style.display = 'block';
        document.getElementById('biz-ph-modal-product').textContent = '';
        document.getElementById('biz-ph-modal-body').innerHTML = '<div style="text-align:center; padding:40px; color:#9ca3af;"><span class="biz-loading" style="width:24px; height:24px; display:inline-block;"></span></div>';

        jQuery.post(ajaxurl, {
            action: 'bizmart_get_product_price_history',
            nonce: this.nonce,
            product_id: productId,
            limit: 50,
            offset: 0
        }, function(res) {
            if (!res.success) {
                document.getElementById('biz-ph-modal-body').innerHTML = '<div style="padding:20px; text-align:center; color:#ef4444;">Error loading data</div>';
                return;
            }

            var data = res.data;
            document.getElementById('biz-ph-modal-product').textContent = data.product_name || ('Product #' + productId);

            var html = '';

            // Stats summary
            if (data.stats && data.stats.count > 0) {
                var cs = '<?php echo esc_js(get_woocommerce_currency_symbol()); ?>';
                html += '<div style="display:grid; grid-template-columns:repeat(4, 1fr); gap:12px; margin-bottom:20px;">';
                html += '<div style="background:#f0f9ff; padding:14px; border-radius:10px; text-align:center;"><div style="font-size:11px; color:#6b7280; text-transform:uppercase; letter-spacing:0.5px; font-weight:600;"><?php echo esc_js(bizmart_text('Entries', 'Entrées', 'إدخالات')); ?></div><div style="font-size:20px; font-weight:700; color:#0369a1;">' + data.stats.count + '</div></div>';
                html += '<div style="background:#ecfdf5; padding:14px; border-radius:10px; text-align:center;"><div style="font-size:11px; color:#6b7280; text-transform:uppercase; letter-spacing:0.5px; font-weight:600;"><?php echo esc_js(bizmart_text('Min PP', 'Min PA', 'أدنى سعر شراء')); ?></div><div style="font-size:20px; font-weight:700; color:#059669;">' + cs + ' ' + data.stats.min_pp + '</div></div>';
                html += '<div style="background:#fef2f2; padding:14px; border-radius:10px; text-align:center;"><div style="font-size:11px; color:#6b7280; text-transform:uppercase; letter-spacing:0.5px; font-weight:600;"><?php echo esc_js(bizmart_text('Max PP', 'Max PA', 'أعلى سعر شراء')); ?></div><div style="font-size:20px; font-weight:700; color:#dc2626;">' + cs + ' ' + data.stats.max_pp + '</div></div>';
                html += '<div style="background:#fffbeb; padding:14px; border-radius:10px; text-align:center;"><div style="font-size:11px; color:#6b7280; text-transform:uppercase; letter-spacing:0.5px; font-weight:600;"><?php echo esc_js(bizmart_text('Avg PP', 'Moy PA', 'متوسط سعر شراء')); ?></div><div style="font-size:20px; font-weight:700; color:#d97706;">' + cs + ' ' + data.stats.avg_pp + '</div></div>';
                html += '</div>';
            }

            // WAC Banner
            if (data.wac && data.wac > 0) {
                html += '<div style="background:linear-gradient(135deg, #f0f9ff, #e0f2fe); border:1px solid #bae6fd; border-radius:10px; padding:12px 16px; margin-bottom:16px; display:flex; align-items:center; justify-content:space-between;">';
                html += '<span style="font-weight:600; color:#0369a1; font-size:13px;">WAC (CUMP)</span>';
                html += '<span style="font-weight:700; font-size:16px; color:#0c4a6e;">' + cs + ' ' + parseFloat(data.wac).toFixed(2) + '</span>';
                html += '</div>';
            }

            // History table
            if (data.history && data.history.length > 0) {
                html += '<table style="width:100%; border-collapse:collapse; font-size:13px;">';
                html += '<thead><tr style="border-bottom:2px solid #e5e7eb;">';
                html += '<th style="padding:10px 12px; text-align:left; color:#6b7280; font-size:11px; text-transform:uppercase; font-weight:600;"><?php echo esc_js(bizmart_text('Date', 'Date', 'التاريخ')); ?></th>';
                html += '<th style="padding:10px 12px; text-align:left; color:#6b7280; font-size:11px; text-transform:uppercase; font-weight:600;"><?php echo esc_js(bizmart_text('Supplier', 'Fournisseur', 'المورد')); ?></th>';
                html += '<th style="padding:10px 12px; text-align:right; color:#6b7280; font-size:11px; text-transform:uppercase; font-weight:600;"><?php echo esc_js(bizmart_text('Purchase', 'Achat', 'الشراء')); ?></th>';
                html += '<th style="padding:10px 12px; text-align:right; color:#6b7280; font-size:11px; text-transform:uppercase; font-weight:600;"><?php echo esc_js(bizmart_text('Selling', 'Vente', 'البيع')); ?></th>';
                html += '<th style="padding:10px 12px; text-align:right; color:#6b7280; font-size:11px; text-transform:uppercase; font-weight:600;"><?php echo esc_js(bizmart_text('Margin', 'Marge', 'الهامش')); ?></th>';
                html += '<th style="padding:10px 12px; text-align:center; color:#6b7280; font-size:11px; text-transform:uppercase; font-weight:600;">Qty</th>';
                html += '</tr></thead><tbody>';

                data.history.forEach(function(h) {
                    var date = h.created_at ? h.created_at.substring(0, 10) : '—';
                    var supplier = h.supplier_name || '—';
                    var pp = parseFloat(h.purchase_price) || 0;
                    var sp = parseFloat(h.selling_price) || 0;
                    var marginColor = (h.margin_pct !== null && h.margin_pct < 10) ? '#dc2626' : '#059669';

                    html += '<tr style="border-bottom:1px solid #f3f4f6;">';
                    html += '<td style="padding:10px 12px; color:#374151;">' + date + '</td>';
                    html += '<td style="padding:10px 12px; color:#6b7280;">' + supplier + '</td>';
                    html += '<td style="padding:10px 12px; text-align:right; font-weight:600; color:#1f2937;">' + cs + ' ' + pp.toFixed(2) + '</td>';
                    html += '<td style="padding:10px 12px; text-align:right; font-weight:600; color:#4f46e5;">' + cs + ' ' + sp.toFixed(2) + '</td>';
                    html += '<td style="padding:10px 12px; text-align:right; font-weight:600; color:' + marginColor + ';">' + (h.margin_pct !== null ? h.margin_pct + '%' : '—') + '</td>';
                    html += '<td style="padding:10px 12px; text-align:center; color:#6b7280;">' + (h.quantity || 1) + '</td>';
                    html += '</tr>';
                });

                html += '</tbody></table>';
            } else {
                html += '<div style="padding:40px; text-align:center; color:#9ca3af; font-size:14px;"><?php echo esc_js(bizmart_text('No price history available for this product', 'Aucun historique de prix disponible pour ce produit', 'لا يوجد سجل أسعار لهذا المنتج')); ?></div>';
            }

            document.getElementById('biz-ph-modal-body').innerHTML = html;
        }).fail(function() {
            document.getElementById('biz-ph-modal-body').innerHTML = '<div style="padding:20px; text-align:center; color:#ef4444;">Connection error</div>';
        });
    },

    close: function() {
        document.getElementById('biz-product-price-history-modal').style.display = 'none';
    }
};

// Close modal on backdrop click
document.getElementById('biz-product-price-history-modal').addEventListener('click', function(e) {
    if (e.target === this) BizPriceHistory.close();
});

// Close on Escape
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') BizPriceHistory.close();
});
</script>
<?php })(); ?>
