/**
 * Fichier  : assets/js/pages/warehouse-manager.js
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-02-21
 * Description : JS — Gestionnaire magasin : catégories, emplacements, racks
 *
 * Changelog :
 *   v2.1.0 (2026-02-21) — Version initiale auditée et sécurisée
 *   v2.1.1 (2026-02-21) — Corrections sécurité, utils.js centralisé
 *   v2.2.0 (2026-02-21) — Permissions magasins, bons de commande, rapport d'écart,
 *                      import CSV, historique prix, bon de livraison multi-lignes
 */
// ================================================================
// warehouse-manager.js — Manage warehouses with categories
// ================================================================
const WarehouseManagerPage = {
    warehouses: [],
    products: [],
    
    async init() {
        document.getElementById('btnNewWarehouse').onclick = () => this.openWarehouseModal();
        await this.load();
    },
    
    async load() {
        const [whs, prods] = await Promise.all([
            Api.warehouses(),
            Api.products()
        ]);
        
        this.warehouses = whs || [];
        this.products = prods || [];
        
        this.render();
    },
    
    render() {
        const grid = document.querySelector('.warehouse-manager-grid');
        
        if(!this.warehouses.length) {
            grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:40px;color:var(--text-muted)">Aucun magasin</div>';
            return;
        }
        
        grid.innerHTML = this.warehouses.map(wh => this.renderWarehouseCard(wh)).join('');
    },
    
    renderWarehouseCard(wh) {
        const categories = JSON.parse(wh.categories || '[]');
        
        // Count products in this warehouse
        const productsInWarehouse = this.products.filter(p => {
            const allowed = JSON.parse(p.allowedWarehouses || '[]');
            return allowed.includes(wh.id);
        });
        
        const productCount = productsInWarehouse.length;
        const categoryCount = categories.length;
        
        return `
            <div class="warehouse-card">
                <div class="warehouse-header">
                    <div class="warehouse-name">${wh.name}</div>
                    <button class="btn btn-sm btn-secondary" onclick="WarehouseManagerPage.openWarehouseModal(${wh.id})">${Icons.edit}</button>
                </div>
                
                <div class="warehouse-stats">
                    <div class="warehouse-stat">
                        <div class="warehouse-stat-value">${productCount}</div>
                        <div class="warehouse-stat-label">Produits</div>
                    </div>
                    <div class="warehouse-stat">
                        <div class="warehouse-stat-value">${categoryCount}</div>
                        <div class="warehouse-stat-label">Catégories</div>
                    </div>
                </div>
                
                <div class="warehouse-categories">
                    <div class="warehouse-categories-header">
                        <div class="warehouse-categories-title">Catégories</div>
                        <button class="btn btn-sm btn-primary" onclick="WarehouseManagerPage.addCategory(${wh.id})">
                            <span data-icon="plus"></span> Ajouter
                        </button>
                    </div>
                    <div class="category-list" id="categoryList${wh.id}">
                        ${categories.map(cat => `
                            <span class="category-tag">
                                ${cat}
                                <button class="category-tag-remove" onclick="WarehouseManagerPage.removeCategory(${wh.id}, '${cat.replace(/'/g, "\\'")}')">×</button>
                            </span>
                        `).join('')}
                    </div>
                </div>
            </div>
        `;
    },
    
    async addCategory(warehouseId) {
        const wh = this.warehouses.find(w => w.id === warehouseId);
        if(!wh) return;
        
        const category = prompt(`Nouvelle catégorie pour "${wh.name}"`);
        if(!category || !category.trim()) return;
        
        try {
            const res = await fetch('api/warehouse-categories.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    warehouseId,
                    category: category.trim()
                })
            });
            
            const data = await res.json();
            
            if(!res.ok) {
                toast(data.error || 'Erreur', 'error');
                return;
            }
            
            toast('Catégorie ajoutée', 'success');
            await this.load();
            
        } catch(e) {
            toast(e.message, 'error');
        }
    },
    
    async removeCategory(warehouseId, category) {
        const wh = this.warehouses.find(w => w.id === warehouseId);
        if(!wh) return;
        
        if(!confirm(`Supprimer la catégorie "${category}" ?\n\nLes produits garderont cette catégorie mais elle n'apparaîtra plus dans la liste.`)) {
            return;
        }
        
        try {
            const res = await fetch('api/warehouse-categories.php', {
                method: 'DELETE',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    warehouseId,
                    category
                })
            });
            
            const data = await res.json();
            
            if(!res.ok) {
                toast(data.error || 'Erreur', 'error');
                return;
            }
            
            toast('Catégorie supprimée', 'success');
            await this.load();
            
        } catch(e) {
            toast(e.message, 'error');
        }
    },
    
    openWarehouseModal(id) {
        const wh = id ? this.warehouses.find(w => w.id === id) : null;
        const isEdit = !!id;
        
        Modal.show(
            isEdit ? 'Modifier magasin' : 'Nouveau magasin',
            `
                <label class="lbl">Nom *</label>
                <input type="text" class="inp" id="whName" value="${wh?.name || ''}" placeholder="Ex: Nancy - Atelier Principal">
                
                <label class="lbl">Adresse</label>
                <input type="text" class="inp" id="whAddress" value="${wh?.address || ''}" placeholder="Adresse complète">
                
                <label class="lbl">Capacité maximale (optionnel)</label>
                <input type="number" class="inp" id="whCapacity" min="0" value="${wh?.capacity || ''}" placeholder="Ex: 10000">
                
                <label class="lbl">Contact</label>
                <input type="text" class="inp" id="whContact" value="${wh?.contact || ''}" placeholder="Nom du responsable">
                
                <label class="lbl">Notes</label>
                <textarea class="inp" id="whNotes" rows="3">${wh?.notes || ''}</textarea>
            `,
            [
                {label: 'Annuler', cls: 'btn-secondary', onclick: () => Modal.close()},
                {label: isEdit ? 'Sauvegarder' : 'Créer', cls: 'btn-primary', onclick: () => this.saveWarehouse(id)},
                ...(isEdit ? [{label: 'Supprimer', cls: 'btn-danger', onclick: () => this.deleteWarehouse(id)}] : [])
            ],
            isEdit ? 'info' : 'success'
        );
    },
    
    async saveWarehouse(id) {
        const name = document.getElementById('whName').value.trim();
        
        if(!name) {
            toast('Nom obligatoire', 'error');
            return;
        }
        
        const data = {
            name,
            address: document.getElementById('whAddress').value.trim(),
            capacity: parseInt(document.getElementById('whCapacity').value) || null,
            contact: document.getElementById('whContact').value.trim(),
            notes: document.getElementById('whNotes').value.trim()
        };
        
        if(id) {
            data.id = id;
        }
        
        try {
            if(id) {
                await Api.warehouseEdit(data);
                toast('Magasin mis à jour', 'success');
            } else {
                await Api.warehouseAdd(data);
                toast('Magasin créé', 'success');
            }
            
            Modal.close();
            await this.load();
            
        } catch(e) {
            toast(e.message, 'error');
        }
    },
    
    async deleteWarehouse(id) {
        const wh = this.warehouses.find(w => w.id === id);
        if(!wh) return;
        
        if(!confirm(`Supprimer le magasin "${wh.name}" ?\n\nCette action est irréversible.`)) {
            return;
        }
        
        try {
            await Api.warehouseDel(id);
            toast('Magasin supprimé', 'success');
            Modal.close();
            await this.load();
        } catch(e) {
            toast(e.message, 'error');
        }
    }
};

if(window.SM_PAGE === 'warehouse-manager') {
    document.addEventListener('DOMContentLoaded', () => WarehouseManagerPage.init());
}
