/**
 * Fichier  : assets/js/pages/warehouses.js
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-02-21
 * Description : JS — Magasins : CRUD, liste, détails
 *
 * 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
 */
// ================================================================
// warehouses.js — Manage warehouses (table view like brands)
// ================================================================
const WarehousesPage = {
    warehouses: [],
    products: [],
    stock: [],
    
    async init() {
        
        const btnNew = document.getElementById('btnNewWh');
        const search = document.getElementById('whSearch');
        
        if(btnNew) {
            btnNew.onclick = () => this.openModal();
        }
        if(search) {
            search.addEventListener('input', () => this.renderTable());
        }
        
        await this.load();
    },
    
    async load() {
        try {
            const [whs, prods, stock] = await Promise.all([
                Api.warehouses(),
                Api.products(),
                Api.stock()
            ]);
            
            this.warehouses = whs || [];
            this.products = prods || [];
            this.stock = stock || [];
            
            // Update count
            const countEl = document.getElementById('whCount');
            if(countEl) countEl.textContent = this.warehouses.length + ' magasin(s)';
            
            this.renderTable();
        } catch(e) {
            console.error('[WarehousesPage] Error loading:', e);
            toast('Erreur chargement magasins', 'error');
        }
    },
    
    renderTable() {
        const tbody = document.getElementById('whBody');
        if(!tbody) {
            console.warn('[WarehousesPage] #whBody not found');
            return;
        }
        
        // Filter by search
        const q = (document.getElementById('whSearch')?.value || '').toLowerCase();
        let filtered = this.warehouses;
        if(q) {
            filtered = this.warehouses.filter(wh => 
                (wh.name || '').toLowerCase().includes(q) ||
                (wh.address || '').toLowerCase().includes(q)
            );
        }
        
        if(!filtered.length) {
            tbody.innerHTML = '<tr><td colspan="6" class="tbl-empty">Aucun magasin</td></tr>';
            return;
        }
        
        tbody.innerHTML = filtered.map(wh => {
            const categories = JSON.parse(wh.categories || '[]');
            
            // Count products allowed in this warehouse
            const productsInWarehouse = this.products.filter(p => {
                let allowed = p.allowedWarehouses;
                if(typeof allowed === 'string') {
                    try { allowed = JSON.parse(allowed || '[]'); } catch(e) { allowed = []; }
                }
                return Array.isArray(allowed) && allowed.includes(wh.id);
            });
            
            // Count total stock in warehouse
            const totalStock = this.stock
                .filter(s => String(s.warehouseId) === String(wh.id))
                .reduce((sum, s) => sum + (parseFloat(s.quantity) || 0), 0);
            
            const categoriesDisplay = categories.length > 0
                ? categories.slice(0, 3).map(c => `<span class="badge">${c}</span>`).join(' ') +
                  (categories.length > 3 ? ` <span class="badge badge-gray">+${categories.length - 3}</span>` : '')
                : '<span class="text-muted">—</span>';
            
            return `
                <tr>
                    <td><strong>${wh.name}</strong></td>
                    <td>${wh.address || '—'}</td>
                    <td>${categoriesDisplay}</td>
                    <td>${productsInWarehouse.length} produit(s)</td>
                    <td>${wh.contact || '—'}</td>
                    <td class="cell-actions">
                        <div style="display:flex;gap:4px">
                            <button class="btn btn-sm btn-secondary" onclick="WarehousesPage.openModal(${wh.id})" title="Modifier">${Icons.edit}</button>
                            <button class="btn btn-sm btn-primary" onclick="WarehousesPage.manageCategories(${wh.id})" title="Catégories">
                                <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z"/>
                                    <line x1="7" y1="7" x2="7.01" y2="7"/>
                                </svg>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="WarehousesPage.deleteWarehouse(${wh.id})" title="Supprimer">${Icons.trash}</button>
                        </div>
                    </td>
                </tr>
            `;
        }).join('');
    },
    
    openModal(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">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'
        );
        
        document.getElementById('whName').focus();
    },
    
    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(),
            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;
        
        // Count products in this warehouse
        const productsCount = this.products.filter(p => {
            let allowed = p.allowedWarehouses;
            if(typeof allowed === 'string') {
                try { allowed = JSON.parse(allowed || '[]'); } catch(e) { allowed = []; }
            }
            return Array.isArray(allowed) && allowed.includes(wh.id);
        }).length;
        
        let msg = `Supprimer le magasin "${wh.name}" ?`;
        if(productsCount > 0) {
            msg += `\n\n⚠️ ${productsCount} produit(s) sont assignés à ce magasin.`;
        }
        
        if(!confirm(msg)) return;
        
        try {
            await Api.warehouseDel(id);
            toast('Magasin supprimé', 'success');
            Modal.close();
            await this.load();
        } catch(e) {
            toast(e.message, 'error');
        }
    },
    
    manageCategories(id) {
        const wh = this.warehouses.find(w => w.id === id);
        if(!wh) return;
        
        const categories = JSON.parse(wh.categories || '[]');
        
        // Get all unique categories from products
        const allCategories = window.StockCascade
            ? StockCascade.getWarehouseCategories(this.rows || [], '', this.products || [], [])
            : [...new Set(this.products.map(p => p.category).filter(Boolean))];
        
        const categoriesHtml = categories.length > 0
            ? categories.map(cat => `
                <div class="category-item" style="display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background:var(--bg-card);border-radius:8px;margin-bottom:4px">
                    <span>${cat}</span>
                    <button class="btn btn-sm btn-danger" onclick="WarehousesPage.removeCategory(${id}, '${cat.replace(/'/g, "\\'")}')">×</button>
                </div>
            `).join('')
            : '<p class="text-muted">Aucune catégorie</p>';
        
        // Options for adding
        const availableCategories = allCategories.filter(c => !categories.includes(c));
        const addOptions = availableCategories.length > 0
            ? `<select class="sel" id="whNewCat" style="flex:1">
                <option value="">Sélectionner...</option>
                ${availableCategories.map(c => `<option value="${c}">${c}</option>`).join('')}
               </select>`
            : '<input type="text" class="inp" id="whNewCatInput" placeholder="Nouvelle catégorie..." style="flex:1">';
        
        Modal.show(
            `Catégories — ${wh.name}`,
            `
                <div id="whCatList" style="margin-bottom:16px">
                    ${categoriesHtml}
                </div>
                
                <div style="display:flex;gap:8px;align-items:center">
                    ${addOptions}
                    <button class="btn btn-primary" onclick="WarehousesPage.addCategory(${id})">Ajouter</button>
                </div>
                
                <div style="margin-top:16px">
                    <label class="lbl">Ou créer une nouvelle catégorie</label>
                    <div style="display:flex;gap:8px">
                        <input type="text" class="inp" id="whNewCatCustom" placeholder="Nom de la catégorie..." style="flex:1">
                        <button class="btn btn-secondary" onclick="WarehousesPage.addCategory(${id}, true)">Créer</button>
                    </div>
                </div>
            `,
            [
                {label: 'Fermer', cls: 'btn-secondary', onclick: () => Modal.close()}
            ],
            'info'
        );
    },
    
    async addCategory(warehouseId, isCustom = false) {
        let category;
        
        if(isCustom) {
            category = document.getElementById('whNewCatCustom')?.value?.trim();
        } else {
            category = document.getElementById('whNewCat')?.value || document.getElementById('whNewCatInput')?.value?.trim();
        }
        
        if(!category) {
            toast('Sélectionnez ou saisissez une catégorie', 'warning');
            return;
        }
        
        try {
            const data = await Api.post('api/warehouse-categories.php', { warehouseId, category });
            toast('Catégorie ajoutée', 'success');
            Modal.close();
            await this.load();
            // Reopen modal to continue adding
            this.manageCategories(warehouseId);
            
        } catch(e) {
            toast(e.message, 'error');
        }
    },
    
    async removeCategory(warehouseId, category) {
        if(!confirm(`Retirer la catégorie "${category}" de ce magasin ?`)) return;
        
        try {
            const data = await Api.delete('api/warehouse-categories.php', { warehouseId, category });
            toast('Catégorie retirée', 'success');
            Modal.close();
            await this.load();
            this.manageCategories(warehouseId);
            
        } catch(e) {
            toast(e.message, 'error');
        }
    }
};
