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

// Pagination
$paged = isset($_GET['paged']) ? max(1, intval(wp_unslash($_GET['paged']))) : 1;
$limit = 20;
$offset = ($paged - 1) * $limit;

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

// Handle Search
$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;
?>

<style>
/* --- PREMIUM "GHOST" UI STYLES --- */

/* Table Reset & Layout */
.biz-table-wrapper {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
    overflow: visible !important; /* Force visible */
    font-family: 'Inter', -apple-system, system-ui, sans-serif;
    position: relative;
    z-index: 1;
}

.biz-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
}

.biz-table th {
    background: #f9fafb;
    color: #6b7280;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    padding: 16px 24px;
    border-bottom: 1px solid #f3f4f6;
    text-align: left;
}

.biz-table td {
    padding: 16px 24px;
    border-bottom: 1px solid #f3f4f6;
    vertical-align: middle;
    transition: background 0.2s;
    position: relative;
    overflow: visible;
}

.biz-table tr:hover td {
    background: #f9fafb;
}

.biz-table tr:last-child td {
    border-bottom: none;
}

/* 1. Ghost Inputs (Prices) */
.biz-ghost-input-wrapper {
    position: relative;
    display: inline-flex;
    align-items: center;
    padding: 4px 8px;
    border-radius: 6px;
    transition: all 0.2s;
    border: 1px solid transparent; /* Invisible border by default */
    cursor: text;
}

.biz-ghost-input-wrapper:hover,
.biz-ghost-input-wrapper.focus-within {
    background: #fff;
    border-color: #e5e7eb;
    box-shadow: 0 1px 2px rgba(0,0,0,0.05); /* Subtle lift */
}

/* State colors for feedback (applied via JS) */
.biz-ghost-input-wrapper.is-saving { background: #fffbeb !important; border-color: #fcd34d !important; } /* Yellow */
.biz-ghost-input-wrapper.is-success { background: #ecfdf5 !important; border-color: #10b981 !important; } /* Green */
.biz-ghost-input-wrapper.is-error { background: #fef2f2 !important; border-color: #ef4444 !important; }   /* Red */

.biz-currency-symbol {
    color: #9ca3af;
    font-size: 13px;
    margin-right: 2px;
    font-weight: 500;
}

.biz-ghost-input {
    border: none !important;
    background: transparent !important;
    box-shadow: none !important;
    padding: 0 !important;
    margin: 0 !important;
    font-size: 14px;
    font-weight: 500;
    color: #1f2937;
    width: 60px;
    outline: none !important;
    font-family: inherit;
}

/* Hide Spinners */
.biz-ghost-input::-webkit-inner-spin-button, 
.biz-ghost-input::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
  margin: 0; 
}

/* 2. Custom Status Badges (Dropdowns) */
.biz-status-dropdown {
    position: relative;
    display: inline-block;
    outline: none;
    z-index: auto;
}

.biz-status-dropdown:hover,
.biz-status-dropdown:focus-within,
.biz-status-dropdown.active {
    z-index: 1000;
}

.biz-table tr:hover {
    position: relative;
    z-index: 50;
}

.biz-table tr:focus-within {
    position: relative;
    z-index: 60;
}

.biz-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    user-select: none;
    border: 1px solid transparent;
}

.biz-badge:hover {
    filter: brightness(0.95);
    transform: translateY(-1px);
}

.biz-badge::after {
    content: "▼";
    font-size: 8px;
    opacity: 0.6;
}

/* Colors */
.biz-badge-success { background: #ecfdf5; color: #059669; border-color: #d1fae5; }
.biz-badge-danger  { background: #fef2f2; color: #dc2626; border-color: #fee2e2; }
.biz-badge-warning { background: #fffbeb; color: #d97706; border-color: #fef3c7; }
.biz-badge-gray    { background: #f3f4f6; color: #4b5563; border-color: #e5e7eb; }
.biz-badge-blue    { background: #eff6ff; color: #3b82f6; border-color: #dbeafe; }

/* Dropdown Menu */
.biz-dropdown-menu {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 9999;
    min-width: 160px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); /* Heavy shadow for floating */
    border: 1px solid #f3f4f6;
    padding: 4px;
    opacity: 0;
    visibility: hidden;
    transform: translateY(10px);
    transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}

.biz-status-dropdown:focus-within .biz-dropdown-menu,
.biz-status-dropdown.active .biz-dropdown-menu {
    opacity: 1;
    visibility: visible;
    transform: translateY(4px);
}

.biz-dropdown-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    font-size: 13px;
    color: #374151;
    border-radius: 6px;
    cursor: pointer;
    transition: background 0.15s;
}

.biz-dropdown-item:hover {
    background: #f3f4f6;
    color: #111827;
}

.biz-dropdown-item.selected {
    background: #eff6ff;
    color: #2563eb;
    font-weight: 500;
}

.biz-product-image {
    width: 48px;
    height: 48px;
    border-radius: 10px; /* Modern rounding */
    object-fit: cover;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.biz-product-name {
    font-size: 14px;
    font-weight: 600;
    color: #111827;
    text-decoration: none;
    display: block;
    margin-bottom: 2px;
}
.biz-product-name:hover {
    color: #4f46e5;
}

</style>

<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: 10px; align-items: center; background: white; padding: 6px; border-radius: 10px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
            <input type="hidden" name="page" value="<?php echo esc_attr(wp_unslash($_GET['page'])); ?>">
            <input type="hidden" name="view" value="list">
            <span style="padding-left: 10px; font-size: 16px;">🔍</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: 250px; border:none; padding: 8px; outline: none; background: transparent;">
        </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 style="width: 80px;"><?php echo esc_html(bizmart_text('Preview', 'Aperçu', 'معاينة')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Product', 'Produit', 'المنتج')); ?></th>
                        <th style="width: 140px;"><?php echo esc_html(bizmart_text('SKU', 'UGS', 'SKU')); ?></th>
                        <th style="width: 180px;"><?php echo esc_html(bizmart_text('Pricing', 'Tarification', 'التسعير')); ?></th>
                        <th style="width: 140px;"><?php echo esc_html(bizmart_text('Cost', 'Coût', 'التكلفة')); ?></th>
                        <th style="width: 150px;"><?php echo esc_html(bizmart_text('Stock', 'Stock', 'المخزون')); ?></th>
                        <th style="width: 150px;"><?php echo esc_html(bizmart_text('Status', 'Statut', 'الحالة')); ?></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&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); ?>">
                        <!-- 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 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 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', function() {
                    jQuery(this).parent().addClass('focus-within');
                }).on('blur', function() {
                    jQuery(this).parent().removeClass('focus-within');
                }).on('change', function() {
                    self.saveInput(jQuery(this));
                });
            },
            
            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();
        });
        </script>

        <!-- Pagination (Styled) -->
        <?php if ($total_pages > 1) : ?>
        <div style="margin-top: 24px; display: flex; justify-content: center;">
            <?php
            echo paginate_links([
                'base' => add_query_arg('paged', '%#%'),
                'format' => '',
                'current' => $paged,
                'total' => $total_pages,
                'prev_text' => '←',
                'next_text' => '→',
                'type' => 'list',
                'mid_size' => 2,
            ]);
            ?>
        </div>
        <style>
            .page-numbers {
                display: flex;
                gap: 8px;
                list-style: none;
                padding: 0;
                margin: 0;
            }
            .page-numbers li span.current,
            .page-numbers li a {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 36px;
                height: 36px;
                border-radius: 8px;
                background: white;
                border: 1px solid #e5e7eb;
                color: #374151;
                text-decoration: none;
                transition: all 0.2s;
                font-weight: 500;
                box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            }
            .page-numbers li a:hover {
                border-color: #d1d5db;
                background: #f9fafb;
            }
            .page-numbers li span.current {
                background: #4f46e5;
                color: white;
                border-color: #4f46e5;
                box-shadow: 0 2px 4px rgba(79, 70, 229, 0.2);
            }
        </style>
        <?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 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>
