/**
 * Fichier  : assets/js/pages/brands.js
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-02-21
 * Description : JS — Page marques : CRUD et association produits
 *
 * 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
 */
// ================================================================
// brands.js — Global brands management
// ================================================================
const BrandPage = {
    brands: [],
    suppliers: [],
    products: [],
    
    async init() {
        const searchInput = document.getElementById('brandSearch');
        const newBtn = document.getElementById('btnNewBrand');
        
        if(!searchInput || !newBtn) {
            console.error('[BrandPage] Elements not found!');
            return;
        }
        
        searchInput.addEventListener('input', () => this.load());
        newBtn.onclick = () => this.openModal();
        
        // Load all data
        await Promise.all([
            this.loadSuppliers(),
            this.loadProducts()
        ]);
        
        await this.load();
    },
    
    async loadSuppliers() {
        this.suppliers = await Api.suppliers();
    },
    
    async loadProducts() {
        this.products = await Api.products();
    },
    
    async load() {
        const q = document.getElementById('brandSearch').value;
        const brands = await Api.brands(q);
        this.brands = brands;
        
        document.getElementById('brandCount').textContent = brands.length + ' marque(s)';
        this.renderTable(brands);
    },
    
    renderTable(brands) {
        const tbody = document.getElementById('brandBody');
        
        if(!brands.length) {
            tbody.innerHTML = '<tr><td colspan="5" class="tbl-empty">Aucune marque</td></tr>';
            return;
        }
        
        tbody.innerHTML = brands.map(b => {
            // Count linked suppliers
            const linkedSuppliers = this.suppliers.filter(s => {
                const linked = (()=>{try{const v=s.linkedBrands; if(Array.isArray(v)) return v; return JSON.parse(v||'[]');}catch(e){return [];}})();
                return Array.isArray(linked) && linked.includes(b.id);
            });
            
            // Count products
            const productCount = this.products.filter(p => p.brand === b.name).length;
            
            return `
                <tr>
                    <td><strong>${b.name}</strong></td>
                    <td>${linkedSuppliers.length > 0 ? linkedSuppliers.map(s => s.name).join(', ') : '—'}</td>
                    <td>${productCount} produit(s)</td>
                    <td>${b.createdAt ? new Date(b.createdAt).toLocaleDateString('fr-FR') : '—'}</td>
                    <td style="display:flex;gap:4px">
                        <button class="btn btn-sm btn-secondary" onclick="BrandPage.openModal(${b.id})">${Icons.edit}</button>
                        <button class="btn btn-sm btn-danger" onclick="BrandPage.deleteBrand(${b.id})">${Icons.trash}</button>
                    </td>
                </tr>
            `;
        }).join('');
    },
    
    openModal(id) {
        const brand = id ? this.brands.find(b => b.id === id) || {} : {};
        const isEdit = !!id;
        
        Modal.show(
            isEdit ? 'Modifier marque' : 'Nouvelle marque',
            `
                <label class="lbl">Nom de la marque *</label>
                <input type="text" class="inp" id="bmName" value="${brand.name || ''}" placeholder="Ex: DULUX, LEVIS, V33...">
            `,
            [
                { label: 'Annuler', cls: 'btn-secondary', onclick: () => Modal.close() },
                { label: isEdit ? 'Sauvegarder' : 'Créer', cls: 'btn-primary', onclick: () => this.saveBrand(id) },
                ...(isEdit ? [{ label: 'Supprimer', cls: 'btn-danger', onclick: () => this.deleteBrand(id) }] : [])
            ],
            isEdit ? 'info' : 'success'
        );
        
        document.getElementById('bmName').focus();
    },
    
    async saveBrand(id) {
        const name = document.getElementById('bmName').value.trim();
        
        if(!name) {
            toast('Nom obligatoire', 'error');
            return;
        }
        
        try {
            if(id) {
                await Api.brandEdit({ id, name });
                toast('Marque mise à jour', 'success');
            } else {
                await Api.brandAdd({ name });
                toast('Marque créée', 'success');
            }
            
            Modal.close();
            await this.load();
        } catch(e) {
            toast(e.message, 'error');
        }
    },
    
    async deleteBrand(id) {
        const brand = this.brands.find(b => b.id === id);
        if(!brand) return;
        
        // Count products using this brand
        const productCount = this.products.filter(p => p.brand === brand.name).length;
        
        let confirmMsg = `Supprimer la marque "${brand.name}" ?`;
        if(productCount > 0) {
            confirmMsg += `\n\n⚠️ ${productCount} produit(s) utilise(nt) cette marque.\nLa marque sera retirée de ces produits.`;
        }
        
        if(!confirm(confirmMsg)) return;
        
        try {
            await Api.brandDel(id);
            toast('Marque supprimée', 'success');
            Modal.close();
            await this.load();
            await this.loadProducts(); // Refresh product list
        } catch(e) {
            toast(e.message, 'error');
        }
    }
};
