<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>TOGOLA GESTION V5</title>
    <meta name="theme-color" content="#1428A0">
    <meta name="mobile-web-app-capable" content="yes">
    <style>
        :root {
            --samsung-blue: #1428A0;
            --samsung-dark: #0B1654;
            --bg: #F4F6F9;
            --card: #FFFFFF;
            --text: #1C1C1C;
            --success: #10B981;
            --warning: #EF4444;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Roboto', -apple-system, sans-serif; }
        body { background: var(--bg); color: var(--text); padding-bottom: 90px; }
        header { background: linear-gradient(135deg, var(--samsung-blue), var(--samsung-dark)); color: white; padding: 18px 15px; text-align: center; box-shadow: 0 4px 12px rgba(0,0,0,0.15); position: sticky; top: 0; z-index: 100; }
        header h1 { font-size: 19px; font-weight: 700; letter-spacing: 0.5px; }
        header p { font-size: 12px; opacity: 0.85; margin-top: 3px; }
        
        .container { padding: 12px; max-width: 600px; margin: 0 auto; }
        .card { background: var(--card); border-radius: 14px; padding: 16px; margin-bottom: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
        .card h2 { font-size: 16px; color: var(--samsung-blue); margin-bottom: 12px; font-weight: 700; display: flex; justify-content: space-between; align-items: center; }
        
        label { font-size: 12px; font-weight: 600; color: #555; display: block; margin-top: 10px; margin-bottom: 4px; }
        input, select { width: 100%; padding: 12px; border: 1px solid #E0E0E0; border-radius: 10px; font-size: 14px; background: #FAFAFA; outline: none; -webkit-appearance: none; }
        input:focus, select:focus { border-color: var(--samsung-blue); background: #FFF; }
        
        .row { display: flex; gap: 10px; }
        .col { flex: 1; }
        
        .btn { width: 100%; background: var(--samsung-blue); color: white; border: none; padding: 14px; border-radius: 10px; font-size: 14px; font-weight: 700; margin-top: 12px; cursor: pointer; box-shadow: 0 4px 10px rgba(20,40,160,0.2); touch-action: manipulation; }
        .btn:active { transform: scale(0.98); opacity: 0.9; }
        .btn-green { background: #2E7D32; box-shadow: 0 4px 10px rgba(46,125,50,0.2); }
        .btn-red { background: var(--warning); box-shadow: 0 4px 10px rgba(239,68,68,0.2); }
        .btn-outline { background: transparent; color: var(--samsung-blue); border: 1px solid var(--samsung-blue); box-shadow: none; }

        .nav-bar { position: fixed; bottom: 0; left: 0; right: 0; background: white; border-top: 1px solid #E0E0E0; display: flex; justify-content: space-around; padding: 8px 0; z-index: 99; }
        .nav-item { border: none; background: none; font-size: 10px; color: #777; display: flex; flex-direction: column; align-items: center; gap: 3px; width: 25%; cursor: pointer; touch-action: manipulation; }
        .nav-item.active { color: var(--samsung-blue); font-weight: bold; }
        .nav-item span { font-size: 20px; }

        .table-item { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #F0F0F0; font-size: 13px; }
        .total-box { background: #E8EAF6; color: var(--samsung-dark); padding: 14px; border-radius: 10px; font-weight: bold; text-align: right; font-size: 15px; margin-top: 12px; }
        
        .badge { background: #E8F5E9; color: #1B5E20; padding: 3px 8px; border-radius: 12px; font-size: 11px; font-weight: 700; }
        .badge-warn { background: #FFEBEE; color: #C62828; }
        .badge-out { background: #FFF3E0; color: #E65100; }
        
        .search-box { margin-bottom: 10px; }
        .kpi-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px; }
        .kpi-card { background: #F1F5F9; padding: 12px; border-radius: 10px; text-align: center; }
        .kpi-card .val { font-size: 16px; font-weight: bold; color: var(--samsung-blue); margin-top: 4px; }
        .kpi-card .lbl { font-size: 11px; color: #64748B; }

        .alert-toast { display: none; background: #323232; color: #fff; padding: 12px 16px; border-radius: 8px; position: fixed; bottom: 70px; left: 50%; transform: translateX(-50%); z-index: 200; font-size: 13px; box-shadow: 0 4px 10px rgba(0,0,0,0.3); }

        .invoice-header { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; border-bottom: 2px dashed #E0E0E0; padding-bottom: 10px; }
        .invoice-logo { width: 75px; height: 75px; border-radius: 8px; object-fit: contain; background: #f9f9f9; border: 1px solid #ddd; }
        .invoice-logo-placeholder { width: 75px; height: 75px; border-radius: 8px; background: #E8EAF6; display: flex; align-items: center; justify-content: center; font-size: 10px; color: #555; text-align: center; border: 1px dashed #1428A0; }

        .invoice-items-container { max-height: 450px; overflow-y: auto; padding-right: 5px; }

        @media print {
            body { padding-bottom: 0; background: white; }
            header, .nav-bar, .no-print { display: none !important; }
            .card { box-shadow: none; border: none; padding: 0; }
            .container { max-width: 100%; padding: 0; }
            .invoice-items-container { max-height: none; overflow: visible; }
        }
    </style>
</head>
<body>

    <header class="no-print">
        <h1 id="headerCompany">TOGOLA GESTION</h1>
        <p id="headerPhone">Facturation • Stock & Hors Stock • Ventes</p>
    </header>

    <div id="toast" class="alert-toast"></div>

    <div class="container">

        <!-- 1. ONGLET VENTES -->
        <div id="tab-vente" class="tab-content">
            <div class="card no-print">
                <h2>📄 Nouvelle Vente</h2>
                <label>Nom du Client</label>
                <input type="text" id="clientName" placeholder="Client passage / Entreprise">
                
                <label>Mode de Vente</label>
                <select id="saleMode" onchange="toggleSaleMode()">
                    <option value="stock">📦 Produit en Stock</option>
                    <option value="out">🚀 Produit Hors Stock (Libre)</option>
                </select>

                <!-- Si En Stock -->
                <div id="stockSection">
                    <label>Sélectionner le Produit</label>
                    <select id="prodSelect" onchange="autoFillPrice()">
                        <option value="">-- Choisir un produit --</option>
                    </select>
                </div>

                <!-- Si Hors Stock -->
                <div id="outStockSection" style="display:none;">
                    <label>Nom du Produit (Hors Stock)</label>
                    <input type="text" id="outProdName" placeholder="ex: Service / Article non stocké">
                </div>

                <div class="row">
                    <div class="col">
                        <label>Quantité</label>
                        <input type="number" id="qty" value="1" min="1" oninput="calculateTotal()">
                    </div>
                    <div class="col">
                        <label>Prix Unitaire (FCFA)</label>
                        <input type="number" id="unitPrice" placeholder="0" oninput="calculateTotal()">
                    </div>
                </div>

                <div class="total-box">
                    Sous-Total Ligne : <span id="lineTotal">0</span> FCFA
                </div>

                <button class="btn" type="button" onclick="addItem()">+ Ajouter l'Article à la Facture</button>
            </div>

            <!-- APERÇU FACTURE -->
            <div class="card">
                <div class="invoice-header">
                    <div id="invoiceLogoBox">
                        <div class="invoice-logo-placeholder">Aucun Logo</div>
                    </div>
                    <div>
                        <h3 id="invCompanyTitle" style="color:var(--samsung-blue); font-size:16px;">TOGOLA GESTION</h3>
                        <p id="invModelBadge" style="font-size:11px; font-weight:bold; color:#1428A0; margin-top:2px;"></p>
                        <p id="invCompanyPhone" style="font-size:12px; color:#555;"></p>
                        <p style="font-size:11px; color:#888;">Date : <span id="invDate"></span></p>
                    </div>
                </div>

                <h2>🛒 Facture Client</h2>
                <p id="invClientInfo" style="font-size:13px; font-weight:bold; margin-bottom:10px; color:#333;"></p>
                
                <div id="invoiceItems" class="invoice-items-container"></div>
                
                <div class="total-box" style="background:var(--samsung-dark); color:white;">
                    NET À PAYER : <span id="grandTotal">0</span> FCFA
                </div>

                <div class="no-print">
                    <button class="btn btn-green" type="button" onclick="checkoutSale()">✅ Valider la Vente</button>
                    <button class="btn btn-outline" type="button" style="margin-top:8px;" onclick="window.print()">🖨️ Imprimer / PDF</button>
                </div>
            </div>
        </div>

        <!-- 2. ONGLET HISTORIQUE DES VENTES -->
        <div id="tab-history" class="tab-content" style="display:none;">
            <div class="kpi-grid">
                <div class="kpi-card">
                    <div class="lbl">Total Ventes Réalisées</div>
                    <div class="val" id="kpiTotalSales">0 FCFA</div>
                </div>
                <div class="kpi-card">
                    <div class="lbl">Nombre de Factures</div>
                    <div class="val" id="kpiCountSales">0</div>
                </div>
            </div>

            <div class="card">
                <h2>📜 Historique des Transactions</h2>
                <div class="search-box">
                    <input type="text" id="searchHistory" placeholder="🔎 Rechercher un client..." onkeyup="filterHistory()">
                </div>
                <div id="historyList"></div>
                <button class="btn btn-red" type="button" style="margin-top:15px; font-size:12px;" onclick="clearHistory()">Effacer tout l'historique</button>
            </div>
        </div>

        <!-- 3. ONGLET GESTION DU STOCK -->
        <div id="tab-stock" class="tab-content" style="display:none;">
            <div class="card no-print">
                <h2>📦 Ajouter un Produit au Stock</h2>
                <label>Nom du Produit</label>
                <input type="text" id="stockName" placeholder="ex: Samsung Galaxy A54">
                <div class="row">
                    <div class="col">
                        <label>Prix Unitaire (FCFA)</label>
                        <input type="number" id="stockPrice" placeholder="0">
                    </div>
                    <div class="col">
                        <label>Stock initial</label>
                        <input type="number" id="stockQty" placeholder="0">
                    </div>
                </div>
                <button class="btn" type="button" onclick="addStockItem()">Enregistrer le Produit</button>
            </div>

            <div class="card">
                <h2>📋 Inventaire du Stock (<span id="stockCountHeader">0</span> produits)</h2>
                <div class="search-box">
                    <input type="text" id="searchStock" placeholder="🔎 Rechercher parmi les produits..." onkeyup="renderStock()">
                </div>
                <div id="stockList"></div>
            </div>
        </div>

        <!-- 4. ONGLET REGLAGES -->
        <div id="tab-param" class="tab-content" style="display:none;">
            <div class="card">
                <h2>📋 Modèle de Facture</h2>
                <label>Sélectionner le type de facture par défaut</label>
                <select id="invoiceTypeSelect" onchange="saveSettings()">
                    <option value="Facture Standard">1. Facture Standard</option>
                    <option value="Facture Proforma">2. Facture Proforma</option>
                    <option value="Facture avec Remise">3. Facture avec Remise</option>
                    <option value="Facture VIP">4. Facture VIP</option>
                    <option value="Facture Express">5. Facture Express</option>
                    <option value="Facture Gros / Demi-Gros">6. Facture Gros / Demi-Gros</option>
                    <option value="Facture d'Avoir">7. Facture d'Avoir</option>
                    <option value="Facture Comptoir">8. Facture Comptoir</option>
                    <option value="Bon de Livraison">9. Bon de Livraison</option>
                    <option value="Facture Export / International">10. Facture Export / International</option>
                </select>
            </div>

            <div class="card">
                <h2>🖼️ Logo sur la Facture</h2>
                <label>Choisir une image depuis la Galerie</label>
                <input type="file" id="logoInput" accept="image/*" onchange="uploadLogo(event)">
                <div id="logoPreviewContainer" style="margin-top:10px; text-align:center;"></div>
                <button class="btn btn-red" type="button" style="margin-top:8px; font-size:11px;" onclick="removeLogo()">❌ Supprimer le Logo</button>
            </div>

            <div class="card">
                <h2>⚙️ Coordonnées Société</h2>
                <label>Nom de l'Entreprise</label>
                <input type="text" id="companyInput" placeholder="ex: TOGOLA GESTION">
                
                <label>Téléphone / WhatsApp</label>
                <input type="text" id="phoneInput" placeholder="ex: +223 70 00 00 00">
                
                <button class="btn" type="button" onclick="saveSettings()">Mettre à Jour les Paramètres</button>
            </div>

            <div class="card">
                <h2>💾 Sauvegarde & Restauration</h2>
                <p style="font-size:12px; color:#666; margin-bottom:10px;">Vos données restent enregistrées sur votre téléphone.</p>
                <button class="btn btn-outline" type="button" onclick="exportBackup()">📥 Télécharger Sauvegarde (JSON)</button>
                <label style="margin-top:15px;">Importer un fichier de sauvegarde</label>
                <input type="file" id="importFile" onchange="importBackup(event)" accept=".json">
            </div>
        </div>

    </div>

    <!-- Navigation du Bas -->
    <div class="nav-bar no-print">
        <button type="button" class="nav-item active" onclick="switchTab('vente', this)">
            <span>📄</span> Vente
        </button>
        <button type="button" class="nav-item" onclick="switchTab('history', this)">
            <span>📜</span> Ventes
        </button>
        <button type="button" class="nav-item" onclick="switchTab('stock', this)">
            <span>📦</span> Stock
        </button>
        <button type="button" class="nav-item" onclick="switchTab('param', this)">
            <span>⚙️</span> Réglages
        </button>
    </div>

    <script>
        let companyData = { name: "TOGOLA GESTION", phone: "+223 70 00 00 00", logo: "", invoiceType: "Facture Standard" };
        let stockData = [
            { id: 1, name: "Samsung Galaxy A54 128Go", price: 210000, qty: 10 },
            { id: 2, name: "Samsung Galaxy S23 Ultra", price: 650000, qty: 5 },
            { id: 3, name: "Chargeur Rapide 25W", price: 15000, qty: 30 }
        ];
        let salesHistory = [];
        let currentInvoice = [];

        function showToast(msg) {
            let t = document.getElementById('toast');
            t.innerText = msg;
            t.style.display = 'block';
            setTimeout(() => { t.style.display = 'none'; }, 2500);
        }

        function loadStorageData() {
            try {
                let savedCompany = localStorage.getItem('companyData');
                if(savedCompany) companyData = JSON.parse(savedCompany);

                let savedStock = localStorage.getItem('stockData');
                if(savedStock) stockData = JSON.parse(savedStock);

                let savedSales = localStorage.getItem('salesHistory');
                if(savedSales) salesHistory = JSON.parse(savedSales);
            } catch(e) {
                console.log("Erreur chargement storage", e);
            }
        }

        function saveAllData() {
            try {
                localStorage.setItem('companyData', JSON.stringify(companyData));
                localStorage.setItem('stockData', JSON.stringify(stockData));
                localStorage.setItem('salesHistory', JSON.stringify(salesHistory));
            } catch(e) {
                console.log("Erreur sauvegarde storage", e);
            }
        }

        function init() {
            loadStorageData();
            
            document.getElementById('headerCompany').innerText = companyData.name || "TOGOLA GESTION";
            document.getElementById('headerPhone').innerText = companyData.phone || "Facturation • Stock • Ventes";
            
            document.getElementById('invCompanyTitle').innerText = companyData.name || "TOGOLA GESTION";
            document.getElementById('invCompanyPhone').innerText = companyData.phone || "";
            document.getElementById('invModelBadge').innerText = companyData.invoiceType || "Facture Standard";

            document.getElementById('companyInput').value = companyData.name || "";
            document.getElementById('phoneInput').value = companyData.phone || "";
            document.getElementById('invoiceTypeSelect').value = companyData.invoiceType || "Facture Standard";
            
            document.getElementById('invDate').innerText = new Date().toLocaleDateString('fr-FR');
            
            renderLogo();
            renderStock();
            updateSelect();
            renderHistory();
        }

        function switchTab(tabName, el) {
            document.querySelectorAll('.tab-content').forEach(t => t.style.display = 'none');
            document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
            document.getElementById('tab-' + tabName).style.display = 'block';
            if(el) el.classList.add('active');
        }

        function toggleSaleMode() {
            let mode = document.getElementById('saleMode').value;
            if(mode === 'stock') {
                document.getElementById('stockSection').style.display = 'block';
                document.getElementById('outStockSection').style.display = 'none';
            } else {
                document.getElementById('stockSection').style.display = 'none';
                document.getElementById('outStockSection').style.display = 'block';
                document.getElementById('unitPrice').value = '';
                calculateTotal();
            }
        }

        function uploadLogo(e) {
            let file = e.target.files[0];
            if(!file) return;

            let reader = new FileReader();
            reader.onload = function(evt) {
                companyData.logo = evt.target.result;
                saveAllData();
                renderLogo();
                showToast("✅ Logo enregistré avec succès !");
            };
            reader.readAsDataURL(file);
        }

        function removeLogo() {
            companyData.logo = "";
            saveAllData();
            renderLogo();
            showToast("Logo supprimé.");
        }

        function renderLogo() {
            let box = document.getElementById('invoiceLogoBox');
            let prevContainer = document.getElementById('logoPreviewContainer');
            
            if(companyData.logo) {
                box.innerHTML = `<img src="${companyData.logo}" class="invoice-logo" alt="Logo">`;
                prevContainer.innerHTML = `<img src="${companyData.logo}" style="max-height:80px; border-radius:8px; border:1px solid #ccc;">`;
            } else {
                box.innerHTML = `<div class="invoice-logo-placeholder">Aucun Logo</div>`;
                prevContainer.innerHTML = `<p style="font-size:12px; color:#888;">Aucun logo sélectionné</p>`;
            }
        }

        function saveSettings() {
            let nameVal = document.getElementById('companyInput').value.trim();
            let phoneVal = document.getElementById('phoneInput').value.trim();
            let typeVal = document.getElementById('invoiceTypeSelect').value;
            
            if(!nameVal) {
                showToast('Veuillez entrer le nom de entreprise.');
                return;
            }

            companyData.name = nameVal;
            companyData.phone = phoneVal;
            companyData.invoiceType = typeVal;
            saveAllData();

            document.getElementById('headerCompany').innerText = companyData.name;
            document.getElementById('headerPhone').innerText = companyData.phone;
            document.getElementById('invCompanyTitle').innerText = companyData.name;
            document.getElementById('invCompanyPhone').innerText = companyData.phone;
            document.getElementById('invModelBadge').innerText = companyData.invoiceType;

            showToast('✅ Paramètres sauvegardés !');
        }

        function renderStock() {
            let filter = (document.getElementById('searchStock')?.value || '').toLowerCase();
            let filtered = stockData.filter(i => i.name.toLowerCase().includes(filter));
            document.getElementById('stockCountHeader').innerText = stockData.length;

            let html = '';
            filtered.slice(0, 100).forEach(item => {
                let badge = item.qty <= 5 ? '<span class="badge badge-warn">⚠️ Stock Bas</span>' : '<span class="badge">✅ En Stock</span>';
                html += `<div class="table-item">
                    <div>
                        <strong>${item.name}</strong><br>
                        <small color="#666">${item.price.toLocaleString()} FCFA</small>
                    </div>
                    <div style="text-align:right;">
                        <strong>${item.qty} dispo</strong> ${badge}
                        <div style="margin-top:4px;">
                            <button type="button" onclick="deleteStockItem(${item.id})" class="no-print" style="border:none; background:none; color:red; font-size:11px; cursor:pointer;">❌ Supprimer</button>
                        </div>
                    </div>
                </div>`;
            });
            document.getElementById('stockList').innerHTML = html || '<p style="font-size:12px; color:#888;">Aucun produit trouvé.</p>';
        }

        function updateSelect() {
            let select = document.getElementById('prodSelect');
            select.innerHTML = '<option value="">-- Choisir un produit --</option>';
            stockData.forEach(item => {
                select.innerHTML += `<option value="${item.id}">${item.name} (${item.qty} dispo)</option>`;
            });
        }

        function addStockItem() {
            let name = document.getElementById('stockName').value.trim();
            let price = parseFloat(document.getElementById('stockPrice').value) || 0;
            let qty = parseInt(document.getElementById('stockQty').value) || 0;

            if(!name || price <= 0) {
                showToast('Remplissez le nom et le prix.');
                return;
            }
            stockData.push({ id: Date.now(), name, price, qty });
            saveAllData();
            renderStock();
            updateSelect();
            document.getElementById('stockName').value = '';
            document.getElementById('stockPrice').value = '';
            document.getElementById('stockQty').value = '';
            showToast('Produit ajouté au stock !');
        }

        function deleteStockItem(id) {
            if(confirm("Supprimer ce produit ?")) {
                stockData = stockData.filter(i => i.id !== id);
                saveAllData();
                renderStock();
                updateSelect();
                showToast('Produit supprimé.');
            }
        }

        function autoFillPrice() {
            let id = document.getElementById('prodSelect').value;
            let prod = stockData.find(p => p.id == id);
            if (prod) {
                document.getElementById('unitPrice').value = prod.price;
                calculateTotal();
            }
        }

        function calculateTotal() {
            let q = parseFloat(document.getElementById('qty').value) || 0;
            let p = parseFloat(document.getElementById('unitPrice').value) || 0;
            document.getElementById('lineTotal').innerText = (q * p).toLocaleString();
        }

        function addItem() {
            let mode = document.getElementById('saleMode').value;
            let q = parseFloat(document.getElementById('qty').value) || 0;
            let p = parseFloat(document.getElementById('unitPrice').value) || 0;

            if(q <= 0 || p <= 0) { showToast('Quantité ou prix invalide.'); return; }

            if(mode === 'stock') {
                let id = document.getElementById('prodSelect').value;
                let prod = stockData.find(p => p.id == id);
                if(!prod) { showToast('Sélectionnez un produit en stock.'); return; }
                if(q > prod.qty) { showToast(`Stock insuffisant (${prod.qty} dispo).`); return; }

                currentInvoice.push({ type: 'stock', prodId: prod.id, name: prod.name, qty: q, price: p, total: q * p });
            } else {
                let outName = document.getElementById('outProdName').value.trim();
                if(!outName) { showToast('Entrez le nom du produit hors stock.'); return; }

                currentInvoice.push({ type: 'out', prodId: null, name: outName + ' (Hors Stock)', qty: q, price: p, total: q * p });
                document.getElementById('outProdName').value = '';
            }

            renderInvoice();
            showToast(`Article ajouté à la facture.`);
        }

        function renderInvoice() {
            let client = document.getElementById('clientName').value || 'Client Passage';
            document.getElementById('invClientInfo').innerText = "Client : " + client;
            let html = '';
            let grand = 0;
            currentInvoice.forEach((item, index) => {
                grand += item.total;
                let badgeType = item.type === 'out' ? '<span class="badge badge-out">Hors Stock</span>' : '';
                html += `<div class="table-item">
                    <div><strong>${index + 1}. ${item.name}</strong> ${badgeType} <br><small>${item.qty} x ${item.price.toLocaleString()} FCFA</small></div>
                    <div>${item.total.toLocaleString()} FCFA <button type="button" class="no-print" onclick="removeItem(${index})" style="background:none; border:none; color:red; margin-left:8px; cursor:pointer;">✕</button></div>
                </div>`;
            });
            document.getElementById('invoiceItems').innerHTML = html || '<p style="font-size:12px; color:#888;">Aucun article sur la facture.</p>';
            document.getElementById('grandTotal').innerText = grand.toLocaleString();
        }

        function removeItem(index) {
            currentInvoice.splice(index, 1);
            renderInvoice();
        }

        function checkoutSale() {
            if(currentInvoice.length === 0) { showToast('La facture est vide !'); return; }

            // Déduire uniquement les articles en stock
            currentInvoice.forEach(item => {
                if(item.type === 'stock' && item.prodId) {
                    let st = stockData.find(s => s.id === item.prodId);
                    if(st) st.qty -= item.qty;
                }
            });

            let totalVal = currentInvoice.reduce((acc, curr) => acc + curr.total, 0);
            let client = document.getElementById('clientName').value || 'Client Passage';

            salesHistory.unshift({
                id: "FAC-" + Date.now().toString().slice(-6),
                date: new Date().toLocaleDateString('fr-FR') + ' à ' + new Date().toLocaleTimeString('fr-FR', {hour:'2-digit', minute:'2-digit'}),
                client: client,
                items: [...currentInvoice],
                total: totalVal
            });

            saveAllData();
            renderStock();
            updateSelect();
            renderHistory();

            showToast('✅ Vente enregistrée avec succès !');
            currentInvoice = [];
            document.getElementById('clientName').value = '';
            renderInvoice();
        }

        function renderHistory() {
            let html = '';
            let grandTotalSales = 0;

            salesHistory.forEach(sale => {
                grandTotalSales += sale.total;
                html += `<div class="table-item" style="flex-direction:column; align-items:flex-start;">
                    <div style="width:100%; display:flex; justify-content:space-between;">
                        <strong>${sale.id} - ${sale.client}</strong>
                        <span style="color:var(--samsung-blue); font-weight:bold;">${sale.total.toLocaleString()} FCFA</span>
                    </div>
                    <small style="color:#666;">📅 ${sale.date} (${sale.items ? sale.items.length : 0} articles)</small>
                </div>`;
            });

            document.getElementById('kpiTotalSales').innerText = grandTotalSales.toLocaleString() + " FCFA";
            document.getElementById('kpiCountSales').innerText = salesHistory.length;
            document.getElementById('historyList').innerHTML = html || '<p style="font-size:12px; color:#888;">Aucune vente enregistrée.</p>';
        }

        function filterHistory() {
            let filter = document.getElementById('searchHistory').value.toLowerCase();
            let items = document.querySelectorAll('#historyList .table-item');
            items.forEach(it => {
                it.style.display = it.innerText.toLowerCase().includes(filter) ? 'flex' : 'none';
            });
        }

        function clearHistory() {
            if(confirm("Effacer tout l'historique ?")) {
                salesHistory = [];
                saveAllData();
                renderHistory();
                showToast('Historique effacé.');
            }
        }

        function exportBackup() {
            let dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify({ companyData, stockData, salesHistory }));
            let downloadAnchor = document.createElement('a');
            downloadAnchor.setAttribute("href", dataStr);
            downloadAnchor.setAttribute("download", `sauvegarde_togola_${Date.now()}.json`);
            document.body.appendChild(downloadAnchor);
            downloadAnchor.click();
            downloadAnchor.remove();
        }

        function importBackup(event) {
            let file = event.target.files[0];
            if(!file) return;
            let reader = new FileReader();
            reader.onload = function(e) {
                try {
                    let imported = JSON.parse(e.target.result);
                    if(imported.stockData && imported.salesHistory) {
                        stockData = imported.stockData;
                        salesHistory = imported.salesHistory;
                        if(imported.companyData) companyData = imported.companyData;
                        saveAllData();
                        init();
                        showToast('Restauration réussie !');
                    }
                } catch(err) {
                    showToast('Fichier invalide.');
                }
            };
            reader.readAsText(file);
        }

        init();
    </script>
</body>
</html>