<?php
/**
 * Bizmart — Stock Alerts admin page.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;

/**
 * Low Stock "Panic" Board - Integrated Version
 */

// Fetch all items that manage stock: Simple products and Variations
// Exclude auto-draft to keep the board clean
$args = array(
    'status' => array('publish', 'draft', 'private'),
    'type' => array('simple', 'variation'),
    'limit' => 2000, // Generous cap to prevent OOM on very large stores
    'stock_status' => array('instock', 'outofstock', 'onbackorder'),
    'paginate' => false,
);

$all_items = wc_get_products($args);
$low_stock_threshold = 5;

$crisis_items = []; // 0 stock
$low_stock_items = []; // 1 to threshold

foreach ($all_items as $item) {
    if (!$item || !$item->managing_stock()) continue;
    
    // STRICT: Skip auto-drafts and items without a name
    $post_status = get_post_status($item->get_id());
    if ($post_status === 'auto-draft') continue;
    if (strpos(strtoupper($item->get_name()), 'AUTO-DRAFT') !== false) continue;

    $qty = $item->get_stock_quantity();
    $status = $item->get_stock_status();

    // Crisis: Exactly 0 or explicitly out of stock
    if ($qty === 0 || $status === 'outofstock') {
        $crisis_items[] = $item;
    } 
    // Low Stock: More than 0 but less than threshold
    elseif ($qty !== null && $qty > 0 && $qty <= $low_stock_threshold) {
        $low_stock_items[] = $item;
    }
}

// Group by Category helper
if (!function_exists('bizmart_group_by_category')) {
    function bizmart_group_by_category($items) {
        $grouped = [];
        foreach ($items as $item) {
            $target_item = $item;
            // If it's a variation, get categories from parent
            if ($item->is_type('variation')) {
                $parent_id = $item->get_parent_id();
                $target_item = wc_get_product($parent_id);
            }
            
            $cats = $target_item ? $target_item->get_category_ids() : [];
            $cat_name = !empty($cats) ? get_term($cats[0], 'product_cat')->name : bizmart_text('Uncategorized', 'Sans catégorie');
            $grouped[$cat_name][] = $item;
        }
        return $grouped;
    }
}

$crisis_grouped = bizmart_group_by_category($crisis_items);
$low_grouped = bizmart_group_by_category($low_stock_items);

$total_alerts = count($crisis_items) + count($low_stock_items);
?>

<div class="biz-panic-integrated-container" style="margin-top: 10px;">
    <style>
        .biz-panic-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 24px;
            margin-bottom: 40px;
        }
        .biz-panic-stat-card {
            background: white;
            padding: 24px;
            border-radius: 20px;
            border: 1px solid #f1f5f9;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
            display: flex;
            align-items: center;
            gap: 20px;
        }
        .biz-panic-stat-icon {
            width: 56px;
            height: 56px;
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }
        .biz-panic-stat-info h3 {
            margin: 0;
            font-size: 14px;
            font-weight: 700;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        .biz-panic-stat-info .value {
            font-size: 28px;
            font-weight: 800;
            color: #1e293b;
        }

        .biz-panic-section-title {
            font-size: 18px;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .biz-panic-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 700;
        }
        
        .biz-panic-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 20px;
            margin-bottom: 48px;
        }
        
        .biz-panic-card {
            background: white;
            border-radius: 20px;
            padding: 20px;
            border: 2px solid transparent;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        .biz-panic-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 20px -5px rgba(0, 0, 0, 0.1);
        }
        
        .biz-panic-card.crisis {
            border-color: #fee2e2;
        }
        .biz-panic-card.crisis:hover {
            border-color: #ef4444;
        }
        
        @keyframes bizPulse {
            0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); }
            70% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); }
            100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
        }
        .biz-pulse-indicator {
            width: 12px;
            height: 12px;
            background: #ef4444;
            border-radius: 50%;
            display: inline-block;
            animation: bizPulse 2s infinite;
            margin-right: 8px;
        }
        
        .biz-product-meta {
            margin-top: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .biz-qty-tag {
            font-size: 14px;
            font-weight: 700;
            padding: 6px 12px;
            border-radius: 10px;
        }
        .biz-qty-tag.zero { background: #fee2e2; color: #b91c1c; }
        .biz-qty-tag.low { background: #fef3c7; color: #b45309; }
        
        .biz-panic-actions {
            margin-top: 20px;
            padding-top: 16px;
            border-top: 1px solid #f1f5f9;
            display: flex;
            gap: 10px;
        }
        .biz-panic-btn {
            flex: 1;
            padding: 10px;
            border-radius: 10px;
            text-align: center;
            font-weight: 700;
            font-size: 13px;
            text-decoration: none;
            transition: all 0.2s;
            cursor: pointer;
        }
        .btn-edit { background: #f8fafc; color: #475569; border: 1px solid #e2e8f0; }
        .btn-edit:hover { background: #f1f5f9; border-color: #cbd5e1; }
        .btn-restock { background: #1e293b; color: white; border: none; }
        .btn-restock:hover { background: #0f172a; transform: translateY(-1px); }
        
        .biz-no-data {
            padding: 80px;
            text-align: center;
            background: white;
            border-radius: 20px;
            border: 2px dashed #e2e8f0;
        }
    </style>

    <div class="biz-panic-stats">
        <div class="biz-panic-stat-card">
            <div class="biz-panic-stat-icon" style="background: #fee2e2; color: #ef4444;">🚨</div>
            <div class="biz-panic-stat-info">
                <h3><?php echo esc_html(bizmart_text('Crisis: Out of Stock', 'Crise : Rupture')); ?></h3>
                <div class="value"><?php echo count($crisis_items); ?></div>
            </div>
        </div>
        <div class="biz-panic-stat-card">
            <div class="biz-panic-stat-icon" style="background: #fef3c7; color: #f59e0b;">⚠️</div>
            <div class="biz-panic-stat-info">
                <h3><?php echo esc_html(bizmart_text('Low Stock Threshold', 'Seuil critique')); ?></h3>
                <div class="value"><?php echo count($low_stock_items); ?></div>
            </div>
        </div>
        <div class="biz-panic-stat-card">
            <div class="biz-panic-stat-icon" style="background: #eff6ff; color: #3b82f6;">📦</div>
            <div class="biz-panic-stat-info">
                <h3><?php echo esc_html(bizmart_text('Total Alerts', 'Total Alertes')); ?></h3>
                <div class="value"><?php echo intval($total_alerts); ?></div>
            </div>
        </div>
    </div>

    <?php if ($total_alerts === 0): ?>
        <div class="biz-no-data">
            <div style="font-size: 48px; margin-bottom: 16px;">✨</div>
            <h2 style="font-weight: 800; color: #1e293b;"><?php echo esc_html(bizmart_text('Everything is under control!', 'Tout est sous contrôle !')); ?></h2>
            <p style="color: #64748b; margin: 0;"><?php echo esc_html(bizmart_text('No products are currently in low stock levels.', 'Aucun produit n\'est actuellement en rupture ou en stock faible.')); ?></p>
        </div>
    <?php endif; ?>

    <!-- Crisis Section -->
    <?php if (!empty($crisis_items)): ?>
        <h2 class="biz-panic-section-title">
            <span class="biz-pulse-indicator"></span>
            <?php echo esc_html(bizmart_text('Crisis Management', 'Gestion de Crise')); ?>
            <span class="biz-panic-badge" style="background: #ef4444; color: white;"><?php echo count($crisis_items); ?></span>
        </h2>
        
        <?php foreach ($crisis_grouped as $cat => $items): ?>
            <div style="margin-bottom: 32px;">
                <h3 style="font-size:14px; color:#64748b; font-weight:700; margin-bottom:16px; border-bottom:1px solid #f1f5f9; padding-bottom:10px;">
                    📂 <?php echo esc_html($cat); ?>
                </h3>
                <div class="biz-panic-grid">
                    <?php foreach ($items as $item): 
                        $p_id = ($item->is_type('variation') ? $item->get_parent_id() : $item->get_id());
                        $edit_link = admin_url('admin.php?page=bizmart-products&view=create&action=edit&id=' . $p_id);
                        ?>
                        <div class="biz-panic-card crisis">
                            <div>
                                <h4 style="margin:0; font-size:16px; font-weight:700; color:#1e293b;"><?php echo esc_html($item->get_name()); ?></h4>
                                <p style="font-family:monospace; font-size:12px; color:#94a3b8; margin:4px 0 0 0;">SKU: <?php echo esc_html($item->get_sku() ?: 'N/A'); ?></p>
                            </div>
                            
                            <div class="biz-product-meta">
                                <span class="biz-qty-tag zero"><?php echo esc_html(bizmart_text('OUT OF STOCK', 'RUPTURE')); ?></span>
                                <span style="font-weight:800; color:#1e293b;"><?php echo wc_price($item->get_price()); ?></span>
                            </div>
                            
                            <div class="biz-panic-actions">
                                <a href="<?php echo esc_url($edit_link); ?>" class="biz-panic-btn btn-edit"><?php echo esc_html(bizmart_text('Edit', 'Modifier')); ?></a>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=bizmart-invoices&action=new')); ?>" class="biz-panic-btn btn-restock"><?php echo esc_html(bizmart_text('Restock', 'Saisir facture')); ?></a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <!-- Low Stock Section -->
    <?php if (!empty($low_stock_items)): ?>
        <h2 class="biz-panic-section-title" style="margin-top: 40px;">
            ⚠️ <?php echo esc_html(bizmart_text('Low Stock Alert', 'Alerte Stock Faible')); ?>
            <span class="biz-panic-badge" style="background: #f59e0b; color: white;"><?php echo count($low_stock_items); ?></span>
        </h2>
        
        <?php foreach ($low_grouped as $cat => $items): ?>
            <div style="margin-bottom: 32px;">
                <h3 style="font-size:14px; color:#64748b; font-weight:700; margin-bottom:16px; border-bottom:1px solid #f1f5f9; padding-bottom:10px;">
                    📂 <?php echo esc_html($cat); ?>
                </h3>
                <div class="biz-panic-grid">
                    <?php foreach ($items as $item): 
                        $p_id = ($item->is_type('variation') ? $item->get_parent_id() : $item->get_id());
                        $edit_link = admin_url('admin.php?page=bizmart-products&view=create&action=edit&id=' . $p_id);
                        
                        // Premium Intelligence: Calculate "Stock Runway" (Days Remaining)
                        // Simple logic: Get sales of last 30 days / 30 = daily velocity
                        global $wpdb;
                        $velocity_query = $wpdb->prepare("
                            SELECT SUM(items.product_qty) 
                            FROM {$wpdb->prefix}wc_order_product_lookup as items
                            JOIN {$wpdb->prefix}posts as orders ON items.order_id = orders.ID
                            WHERE items.product_id = %d 
                            AND orders.post_type = 'shop_order' 
                            AND orders.post_date > %s", 
                            $item->get_id(), wp_date('Y-m-d', strtotime('-30 days'))
                        );
                        $last_30_days_sales = $wpdb->get_var($velocity_query) ?: 0;
                        $daily_velocity = $last_30_days_sales / 30;
                        $stock_runway = ($daily_velocity > 0) ? floor($item->get_stock_quantity() / $daily_velocity) : 999;
                        ?>
                        <div class="biz-panic-card <?php echo ($stock_runway < 3) ? 'crisis' : ''; ?>">
                            <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:12px;">
                                <div style="flex:1;">
                                    <h4 style="margin:0; font-size:16px; font-weight:700; color:#1e293b;"><?php echo esc_html($item->get_name()); ?></h4>
                                    <p style="font-family:monospace; font-size:12px; color:#94a3b8; margin:4px 0 0 0;">SKU: <?php echo esc_html($item->get_sku() ?: 'N/A'); ?></p>
                                </div>
                                <div class="biz-runway-badge" style="background:#f1f5f9; padding:4px 10px; border-radius:12px; text-align:right;">
                                    <div style="font-size:10px; color:#64748b; font-weight:700; text-transform:uppercase;"><?php echo esc_html(bizmart_text('Runway', 'Autonomie')); ?></div>
                                    <div style="font-size:14px; color:#1e293b; font-weight:800;"><?php echo ($stock_runway >= 999) ? '∞' : sprintf(bizmart_text('%d Days', '%d Jours'), $stock_runway); ?></div>
                                </div>
                            </div>
                            
                            <div class="biz-product-meta">
                                <span class="biz-qty-tag low"><?php echo sprintf(bizmart_text('%s in stock', '%s en stock'), '<strong class="biz-current-qty">' . (int)$item->get_stock_quantity() . '</strong>'); ?></span>
                                <span style="font-weight:800; color:#1e293b;"><?php echo wc_price($item->get_price()); ?></span>
                            </div>

                            <div style="margin:12px 0; padding:10px; background:#f8fafc; border-radius:10px; display:flex; align-items:center; gap:10px;">
                                <label style="font-size:11px; color:#64748b; font-weight:600;"><?php echo esc_html(bizmart_text('Correct stock:', 'Corriger stock:')); ?></label>
                                <input type="number" class="biz-quick-qty-input" value="<?php echo (int)$item->get_stock_quantity(); ?>" style="width:60px; height:28px; border:1px solid #e2e8f0; border-radius:6px; font-size:13px; font-weight:600; text-align:center;">
                                <button onclick="BizmartQuickUpdateStock(this, <?php echo intval($item->get_id()); ?>)" class="biz-quick-save-btn" style="background:#3b82f6; color:#fff; border:none; border-radius:6px; width:28px; height:28px; display:flex; align-items:center; justify-content:center; cursor:pointer; transition:0.2s;">
                                    <span style="font-size:14px;">💾</span>
                                </button>
                            </div>
                            
                            <div class="biz-panic-actions">
                                <a href="<?php echo esc_url($edit_link); ?>" class="biz-panic-btn btn-edit"><?php echo esc_html(bizmart_text('Edit', 'Modifier')); ?></a>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=bizmart-invoices&action=new')); ?>" class="biz-panic-btn btn-restock"><?php echo esc_html(bizmart_text('Restock', 'Saisir facture')); ?></a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

</div>

<script>
function BizmartQuickUpdateStock(btn, productId) {
    const $btn = jQuery(btn);
    const $card = $btn.closest('.biz-panic-card');
    const $input = $card.find('.biz-quick-qty-input');
    const newQty = $input.val();
    
    const originalContent = $btn.html();
    $btn.prop('disabled', true).html('<span class="biz-loading" style="width:12px; height:12px; border-width:2px;"></span>');

    jQuery.post(BizmartAnalytics.ajax_url, {
        action: 'bizmart_quick_update_stock',
        nonce: BizmartAnalytics.nonce,
        id: productId,
        qty: newQty
    }, function(response) {
        $btn.prop('disabled', false).html(originalContent);
        if (response.success) {
            $card.find('.biz-current-qty').text(response.data.qty);
            $btn.css('background', '#22c55e');
            setTimeout(() => {
                $btn.css('background', '#3b82f6');
                if (response.data.qty > 5) { // Assuming 5 is a threshold for alert removal, though backend handles the query
                    $card.fadeOut(500, function() { $(this).remove(); });
                }
            }, 1000);
        } else {
            alert('Error: ' + (response.data || 'Unknown error'));
        }
    });
}
</script>
