<?php
/**
 * Bizmart — Stock Alerts admin page.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */

if (!defined('ABSPATH')) {
    exit;
}

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals

// Group by Category helper defined globally
if (!function_exists('bizmart_group_by_category')) {
    function bizmart_group_by_category($bizmart_items) {
        $bizmart_grouped = [];
        foreach ($bizmart_items as $bizmart_item) {
            $bizmart_target_item = $bizmart_item;
            // If it's a variation, get categories from parent
            if ($bizmart_item->is_type('variation')) {
                $bizmart_parent_id = $bizmart_item->get_parent_id();
                $bizmart_target_item = wc_get_product($bizmart_parent_id);
            }
            
            $bizmart_cats = $bizmart_target_item ? $bizmart_target_item->get_category_ids() : [];
            $bizmart_cat_name = !empty($bizmart_cats) ? get_term($bizmart_cats[0], 'product_cat')->name : bizmart_text('Uncategorized', 'Sans catégorie');
            $bizmart_grouped[$bizmart_cat_name][] = $bizmart_item;
        }
        return $bizmart_grouped;
    }
}

// Fetch all items that manage stock: Simple products and Variations
// Exclude auto-draft to keep the board clean
$bizmart_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,
);

$bizmart_all_items = wc_get_products($bizmart_args);
$bizmart_low_stock_threshold = 5;

$bizmart_crisis_items = []; // 0 stock
$bizmart_low_stock_items = []; // 1 to threshold

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

    $bizmart_qty = $bizmart_item->get_stock_quantity();
    $bizmart_status = $bizmart_item->get_stock_status();

    // Crisis: Exactly 0 or explicitly out of stock
    if ($bizmart_qty === 0 || $bizmart_status === 'outofstock') {
        $bizmart_crisis_items[] = $bizmart_item;
    } 
    // Low Stock: More than 0 but less than threshold
    elseif ($bizmart_qty !== null && $bizmart_qty > 0 && $bizmart_qty <= $bizmart_low_stock_threshold) {
        $bizmart_low_stock_items[] = $bizmart_item;
    }
}

$bizmart_crisis_grouped = bizmart_group_by_category($bizmart_crisis_items);
$bizmart_low_grouped = bizmart_group_by_category($bizmart_low_stock_items);

$bizmart_total_alerts = count($bizmart_crisis_items) + count($bizmart_low_stock_items);
?>

<div class="biz-panic-integrated-container" style="margin-top: 10px;">
    <!-- Stock Alerts CSS moved to assets/products.css -->

    <div class="biz-alert-stats-grid">
        <div class="biz-alert-stat-card crisis" data-filter="crisis">
            <div class="biz-alert-icon-wrapper">🚨</div>
            <div class="biz-alert-info-wrapper">
                <div class="biz-alert-label"><?php echo esc_html(bizmart_text('Crisis: Out of Stock', 'Crise : Rupture')); ?></div>
                <div class="biz-alert-value"><?php echo count($bizmart_crisis_items); ?></div>
                <div class="biz-alert-desc"><?php echo esc_html(bizmart_text('Immediate replenishment required', 'Réapprovisionnement immédiat requis')); ?></div>
            </div>
        </div>
        <div class="biz-alert-stat-card warning" data-filter="low">
            <div class="biz-alert-icon-wrapper">⚠️</div>
            <div class="biz-alert-info-wrapper">
                <div class="biz-alert-label"><?php echo esc_html(bizmart_text('Low Stock Threshold', 'Seuil critique')); ?></div>
                <div class="biz-alert-value"><?php echo count($bizmart_low_stock_items); ?></div>
                <div class="biz-alert-desc"><?php echo esc_html(bizmart_text('Items approaching zero limit', 'Articles approchant la limite')); ?></div>
            </div>
        </div>
        <div class="biz-alert-stat-card info active" data-filter="all">
            <div class="biz-alert-icon-wrapper">📦</div>
            <div class="biz-alert-info-wrapper">
                <div class="biz-alert-label"><?php echo esc_html(bizmart_text('Total Alerts', 'Total Alertes')); ?></div>
                <div class="biz-alert-value"><?php echo intval($bizmart_total_alerts); ?></div>
                <div class="biz-alert-desc"><?php echo esc_html(bizmart_text('Items being actively tracked', 'Articles suivis activement')); ?></div>
            </div>
        </div>
    </div>

    <?php if ($bizmart_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 else: ?>
        <!-- Interactive Controls -->
        <div class="biz-alerts-controls" style="display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center; gap:16px; margin:24px 0; background:white; padding:16px 20px; border-radius:16px; box-shadow:0 4px 6px -1px rgba(0,0,0,0.05);">
            <div style="font-weight: 700; color: #475569; font-size: 14px; display: flex; align-items: center; gap: 8px;">
                📊 <?php echo esc_html(bizmart_text('Filter Products', 'Filtrer les produits')); ?>
            </div>
            
            <!-- Filters -->
            <div style="display:flex; flex:1; justify-content:flex-end; gap:12px; min-width:300px;">
                <input type="text" id="biz-alert-search" placeholder="<?php echo esc_attr(bizmart_text('Search name or SKU...', 'Rechercher nom ou SKU...')); ?>" style="padding:8px 14px; border:1px solid #e2e8f0; border-radius:10px; width:220px; font-size:13px; outline:none;">
                
                <?php
                $all_categories = array_unique(array_merge(array_keys($bizmart_crisis_grouped), array_keys($bizmart_low_grouped)));
                ?>
                <select id="biz-alert-cat-filter" style="padding:8px 14px; border:1px solid #e2e8f0; border-radius:10px; font-size:13px; outline:none; background:white;">
                    <option value="all"><?php echo esc_html(bizmart_text('All Categories', 'Toutes les catégories')); ?></option>
                    <?php foreach ($all_categories as $cat): ?>
                        <option value="<?php echo esc_attr($cat); ?>"><?php echo esc_html($cat); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <!-- Premium Table Card -->
        <div class="biz-card" style="padding:0; overflow:hidden; border-radius:16px; box-shadow:0 4px 6px -1px rgba(0,0,0,0.05); margin-bottom:48px; background:white;">
            <table class="biz-alerts-table" style="width:100%; border-collapse:collapse; text-align:left; font-size:14px;">
                <thead>
                    <tr style="background:#f8fafc; border-bottom:1px solid #e2e8f0;">
                        <th style="padding:16px 20px; font-weight:700; color:#475569;"><?php echo esc_html(bizmart_text('Product', 'Produit')); ?></th>
                        <th style="padding:16px 20px; font-weight:700; color:#475569;"><?php echo esc_html(bizmart_text('Category', 'Catégorie')); ?></th>
                        <th style="padding:16px 20px; font-weight:700; color:#475569;"><?php echo esc_html(bizmart_text('Stock Level', 'Niveau de Stock')); ?></th>
                        <th style="padding:16px 20px; font-weight:700; color:#475569;"><?php echo esc_html(bizmart_text('Status / Runway', 'Statut / Autonomie')); ?></th>
                        <th style="padding:16px 20px; font-weight:700; color:#475569;"><?php echo esc_html(bizmart_text('Price', 'Prix')); ?></th>
                        <th style="padding:16px 20px; font-weight:700; color:#475569; text-align:center;"><?php echo esc_html(bizmart_text('Quick Update', 'Corriger Stock')); ?></th>
                        <th style="padding:16px 20px; font-weight:700; color:#475569; text-align:right;"><?php echo esc_html(bizmart_text('Actions', 'Actions')); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Combine and render all items sorted
                    $bizmart_render_list = array_merge(
                        array_map(fn($item) => ['status' => 'crisis', 'item' => $item], $bizmart_crisis_items),
                        array_map(fn($item) => ['status' => 'low', 'item' => $item], $bizmart_low_stock_items)
                    );
                    
                    // Sort alphabetically by name
                    usort($bizmart_render_list, fn($a, $b) => strcmp($a['item']->get_name(), $b['item']->get_name()));

                    foreach ($bizmart_render_list as $row):
                        $item = $row['item'];
                        $status = $row['status'];
                        $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);
                        
                        // Category resolving
                        $cats = $item->is_type('variation') ? wc_get_product($item->get_parent_id())->get_category_ids() : $item->get_category_ids();
                        $cat_name = !empty($cats) ? get_term($cats[0], 'product_cat')->name : bizmart_text('Uncategorized', 'Sans catégorie');
                        
                        // Calculate runway
                        global $wpdb;
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                        $last_30_sales = $wpdb->get_var(
                            $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'))
                            )
                        ) ?: 0;
                        $daily_vel = $last_30_sales / 30;
                        $qty = $item->get_stock_quantity();
                        $runway = ($daily_vel > 0) ? floor($qty / $daily_vel) : 999;
                        ?>
                        <tr class="biz-alert-row" data-status="<?php echo esc_attr($status); ?>" data-category="<?php echo esc_attr($cat_name); ?>" data-search="<?php echo esc_attr(strtolower($item->get_name() . ' ' . $item->get_sku())); ?>" style="border-bottom:1px solid #f1f5f9; transition:0.2s;">
                            <!-- Product -->
                            <td style="padding:16px 20px;">
                                <a href="<?php echo esc_url($edit_link); ?>" class="biz-alert-product-link" style="text-decoration:none; font-weight:600; color:#1e293b; display:inline-block;" title="<?php echo esc_attr(bizmart_text('Edit Product', 'Modifier le produit')); ?>">
                                    <?php echo esc_html($item->get_name()); ?>
                                </a>
                                <div style="font-family:monospace; font-size:11px; color:#94a3b8; margin-top:2px;">SKU: <?php echo esc_html($item->get_sku() ?: '—'); ?></div>
                            </td>
                            
                            <!-- Category -->
                            <td style="padding:16px 20px; color:#64748b; font-weight:500;">
                                📂 <?php echo esc_html($cat_name); ?>
                            </td>
                            
                            <!-- Stock Level Gauge -->
                            <td style="padding:16px 20px; min-width:140px;">
                                <div style="display:flex; justify-content:space-between; font-size:12px; font-weight:600; color:#475569; margin-bottom:4px;">
                                    <span><strong class="biz-current-qty"><?php echo intval($qty); ?></strong> / 5</span>
                                </div>
                                <?php
                                $percentage = min(100, max(0, ($qty / 5) * 100));
                                $bar_color = ($qty === 0) ? '#ef4444' : (($qty <= 2) ? '#f97316' : '#f59e0b');
                                ?>
                                <div style="width:100%; background:#f1f5f9; height:6px; border-radius:10px; overflow:hidden;">
                                    <div style="width:<?php echo esc_attr($percentage); ?>%; background:<?php echo esc_attr($bar_color); ?>; height:100%; border-radius:10px;"></div>
                                </div>
                            </td>
                            
                            <!-- Status / Runway -->
                            <td style="padding:16px 20px;">
                                <?php if ($qty === 0 || $item->get_stock_status() === 'outofstock'): ?>
                                    <span style="background:#fee2e2; color:#ef4444; padding:4px 10px; border-radius:20px; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:0.02em;">🚨 <?php echo esc_html(bizmart_text('Out Of Stock', 'Rupture')); ?></span>
                                <?php else: ?>
                                    <span style="background:#fef3c7; color:#d97706; padding:4px 10px; border-radius:20px; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:0.02em;">⚠️ <?php echo esc_html(bizmart_text('Low Stock', 'Stock faible')); ?></span>
                                    <div style="font-size:11px; color:#64748b; margin-top:4px;">
                                        ⏳ <?php echo ($runway >= 999) ? esc_html(bizmart_text('Stable (no sales)', 'Stable (pas de vente)')) : esc_html(sprintf(bizmart_text('%d Days Runway', 'Autonomie : %d jours'), $runway)); ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Price -->
                            <td style="padding:16px 20px; font-weight:700; color:#1e293b;">
                                <?php echo wp_kses_post(wc_price($item->get_price())); ?>
                            </td>
                            
                            <!-- Quick Update -->
                            <td style="padding:16px 20px; text-align:center;">
                                <div style="display:inline-flex; align-items:center; gap:8px;">
                                    <input type="number" class="biz-quick-qty-input" value="<?php echo intval($qty); ?>" style="width:65px; height:32px; border:1px solid #cbd5e1; border-radius:8px; font-size:13px; font-weight:700; text-align:center; outline:none;" title="<?php echo esc_attr(bizmart_text('Enter new stock quantity', 'Saisir la nouvelle quantité')); ?>">
                                    <button onclick="BizmartQuickUpdateStock(this, <?php echo intval($item->get_id()); ?>)" class="biz-btn" style="padding:6px 12px; font-size:12px; font-weight:700; display:inline-flex; align-items:center; gap:4px; border-radius:8px; background:#3b82f6; color:white; border:none; cursor:pointer;" title="<?php echo esc_attr(bizmart_text('Correct stock count immediately in WooCommerce', 'Corriger le stock immédiatement dans WooCommerce')); ?>">
                                        💾 <?php echo esc_html(bizmart_text('Save', 'Sauver')); ?>
                                    </button>
                                </div>
                            </td>
                            
                            <!-- Actions -->
                            <td style="padding:16px 20px; text-align:right;">
                                <div style="display:inline-flex; gap:6px;">
                                    <a href="<?php echo esc_url($edit_link); ?>" class="biz-btn biz-btn-secondary" style="padding:6px 12px; font-size:12px; font-weight:700; display:inline-flex; align-items:center; gap:4px; border-radius:8px;" title="<?php echo esc_attr(bizmart_text('Edit product details, prices, and options', 'Modifier les détails et prix du produit')); ?>">
                                        ✏️ <?php echo esc_html(bizmart_text('Edit', 'Modifier')); ?>
                                    </a>
                                    <?php if (defined('BIZMART_ADDON_VERSION')) : ?>
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=bizmart-invoices&action=new&add_product=' . intval($item->get_id()))); ?>" class="biz-btn" style="padding:6px 12px; font-size:12px; font-weight:700; display:inline-flex; align-items:center; gap:4px; border-radius:8px; background:#1e293b; color:white; text-decoration:none;" title="<?php echo esc_attr(bizmart_text('Create supplier purchase invoice to restock and record purchase costs', 'Créer une facture d\'achat fournisseur pour réapprovisionner et suivre les coûts')); ?>">
                                            ➕ <?php echo esc_html(bizmart_text('Restock', 'Saisir facture')); ?>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- JavaScript for Interactive Controls -->
        <script>
            jQuery(document).ready(function($) {
                // Card filtering
                $('.biz-alert-stat-card').on('click', function() {
                    $('.biz-alert-stat-card').removeClass('active');
                    $(this).addClass('active');
                    applyFilters();
                });
                
                // Search and Category input
                $('#biz-alert-search').on('input', applyFilters);
                $('#biz-alert-cat-filter').on('change', applyFilters);
                
                function applyFilters() {
                    var filter = $('.biz-alert-stat-card.active').data('filter') || 'all';
                    var search = $('#biz-alert-search').val().toLowerCase().trim();
                    var category = $('#biz-alert-cat-filter').val();
                    
                    $('.biz-alert-row').each(function() {
                        var rowStatus = $(this).data('status');
                        var rowCat = $(this).data('category');
                        var rowSearch = $(this).data('search');
                        
                        var showByTab = (filter === 'all' || rowStatus === filter);
                        var showByCategory = (category === 'all' || rowCat === category);
                        var showBySearch = (search === '' || rowSearch.indexOf(search) !== -1);
                        
                        if (showByTab && showByCategory && showBySearch) {
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                    });
                }
            });
        </script>
    <?php endif; ?>

<!-- Stock Alerts JS script moved to assets/products.js -->
