<!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 V12 - Sécurité Multi-Appareils</title>
    <meta name="theme-color" content="#133880">
    <style>
        :root {
            --primary: #133880;
            --bg: #F0F2F5;
            --card: #FFFFFF;
            --text: #111111;
            --warning: #EF4444;
            --success: #15803D;
            --google: #DB4437;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Roboto', Arial, sans-serif; }
        body { background: var(--bg); color: var(--text); padding-bottom: 90px; }
        
        header { background: var(--primary); color: white; padding: 14px; text-align: center; position: sticky; top: 0; z-index: 100; box-shadow: 0 2px 6px rgba(0,0,0,0.15); }
        header h1 { font-size: 17px; font-weight: 700; }
        header p { font-size: 11px; opacity: 0.85; }

        .container { padding: 10px; max-width: 650px; margin: 0 auto; }
        .card { background: var(--card); border-radius: 10px; padding: 12px; margin-bottom: 12px; box-shadow: 0 2px 6px rgba(0,0,0,0.05); }
        .card h2 { font-size: 14px; color: var(--primary); margin-bottom: 10px; font-weight: 700; display: flex; justify-content: space-between; align-items: center; }

        label { font-size: 11px; font-weight: 600; color: #444; display: block; margin-top: 8px; margin-bottom: 3px; }
        input, select { width: 100%; padding: 10px; border: 1px solid #CCC; border-radius: 8px; font-size: 13px; background: #FAFAFA; outline: none; }
        input:focus, select:focus { border-color: var(--primary); background: #FFF; }
        
        .row { display: flex; gap: 8px; }
        .col { flex: 1; }

        .btn { width: 100%; background: var(--primary); color: white; border: none; padding: 12px; border-radius: 8px; font-size: 13px; font-weight: 700; margin-top: 10px; cursor: pointer; }
        .btn:active { opacity: 0.9; }
        .btn-green { background: var(--success); }
        .btn-red { background: var(--warning); }
        .btn-google { background: var(--google); display: flex; align-items: center; justify-content: center; gap: 8px; }
        .btn-outline { background: transparent; color: var(--primary); border: 1px solid var(--primary); }

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

        .table-item { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #EEE; font-size: 12px; }
        .alert-toast { display: none; background: #222; color: #fff; padding: 10px 14px; border-radius: 6px; position: fixed; bottom: 70px; left: 50%; transform: translateX(-50%); z-index: 200; font-size: 12px; }

        /* ÉCRAN AUTHENTIFICATION AMÉLIORÉ */
        #authScreen { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: var(--bg); z-index: 1000; display: flex; align-items: center; justify-content: center; padding: 15px; overflow-y: auto; }
        .auth-box { background: white; width: 100%; max-width: 400px; padding: 20px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .auth-box h2 { color: var(--primary); font-size: 18px; text-align: center; margin-bottom: 15px; }

        /* DESIGN FACTURE V12 */
        .custom-invoice-sheet {
            background: #FFFFFF;
            border: 2px solid var(--primary);
            border-radius: 6px;
            padding: 10px;
            color: #000;
            margin-bottom: 15px;
        }
        .page-break-container { display: none; }
        .page-break-container.active { display: block; }

        .sheet-header {
            border: 1.5px solid var(--primary);
            padding: 8px;
            background: #FAFBFC;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .sheet-logo-area {
            width: 65px;
            height: 65px;
            border-radius: 6px;
            border: 1px dashed var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            background: #FFF;
            overflow: hidden;
            flex-shrink: 0;
        }
        .sheet-logo-area img { width: 100%; height: 100%; object-fit: contain; }
        .sheet-logo-placeholder { font-size: 9px; color: #666; text-align: center; }
        
        .sheet-company-info { flex: 1; text-align: center; }
        .sheet-company-info h3 { color: var(--primary); font-size: 14px; font-weight: 900; }
        .sheet-company-info p { font-size: 9.5px; color: #333; line-height: 1.25; margin-top: 2px; }
        
        .sheet-meta {
            font-size: 11px;
            margin-bottom: 8px;
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid var(--primary);
            padding-bottom: 6px;
        }

        .fixed-17-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 11px;
        }
        .fixed-17-table th, .fixed-17-table td {
            border: 1px solid var(--primary);
            padding: 4px 5px;
        }
        .fixed-17-table th {
            background-color: var(--primary);
            color: white;
            text-align: center;
            font-weight: bold;
            font-size: 11px;
        }
        .fixed-17-table input {
            width: 100%;
            border: none;
            background: transparent;
            font-size: 11px;
            padding: 1px;
            outline: none;
        }
        .fixed-17-table input:focus { background: #FFF9C4; }
        
        .col-qte { width: 14%; text-align: center; }
        .col-desc { width: 46%; }
        .col-pu { width: 20%; text-align: right; }
        .col-montant { width: 20%; text-align: right; }

        .sheet-footer {
            font-size: 10px;
            margin-top: 8px;
            border-top: 1px dashed var(--primary);
            padding-top: 6px;
        }

        .sheet-signatures {
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
            font-size: 11px;
            font-weight: bold;
        }
        .sig-block { text-align: center; width: 42%; }
        .sig-box {
            height: 55px;
            border: 1px dashed #999;
            border-radius: 4px;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 9px;
            color: #888;
            background: #FAFAFA;
        }

        .creator-watermark {
            text-align: center;
            font-size: 9px;
            color: #777;
            margin-top: 8px;
            border-top: 1px solid #EEE;
            padding-top: 4px;
        }

        .badge-status {
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 9px;
            font-weight: bold;
            display: inline-block;
        }
        .status-paye { background: #DCFCE7; color: #15803D; }
        .status-impaye { background: #FEE2E2; color: #EF4444; }

        @media print {
            body { padding-bottom: 0; background: white; }
            header, .nav-bar, .no-print { display: none !important; }
            .card { box-shadow: none; border: none; padding: 0; margin: 0; }
            .container { max-width: 100%; padding: 0; }
            .custom-invoice-sheet { border: 1px solid #000; page-break-after: always; display: block !important; }
            .page-break-container { display: block !important; }
        }
    </style>
</head>
<body>

    <!-- ÉCRAN D'AUTHENTIFICATION & SÉCURITÉ MULTI-APPAREILS -->
    <div id="authScreen">
        <div class="auth-box">
            <h2>🔐 SÉCURITÉ CITY WEB V12</h2>
            
            <div id="authFormLogin">
                <p style="font-size: 12px; color: #666; text-align: center; margin-bottom: 12px;">Connexion instantanée (Jusqu'à 10 téléphones en temps réel)</p>
                <label>Nom d'utilisateur ou ID Compte</label>
                <input type="text" id="loginUser" placeholder="ex: issa">
                <label>Mot de passe sécurisé</label>
                <input type="password" id="loginPass" placeholder="••••••••">
                <button class="btn" type="button" onclick="handleLogin()">Connexion Sécurisée</button>
                <button class="btn btn-google" type="button" style="margin-top:8px;" onclick="handleGoogleAuth()">🌐 Connexion Rapide Google</button>
                <button class="btn btn-outline" type="button" style="margin-top:6px;" onclick="toggleAuthMode(true)">Créer un nouveau compte</button>
            </div>

            <div id="authFormRegister" style="display:none;">
                <p style="font-size: 12px; color: #666; text-align: center; margin-bottom: 12px;">Enregistrement multi-appareils (City Web)</p>
                <label>Nom de l'Entreprise</label>
                <input type="text" id="regCompany" placeholder="ex: TOGOLA GESTION">
                <label>Nom d'utilisateur</label>
                <input type="text" id="regUser" placeholder="ex: issa">
                <label>Mot de passe</label>
                <input type="password" id="regPass" placeholder="••••••••">
                <button class="btn btn-green" type="button" onclick="handleRegister()">Créer et Activer la Synchro</button>
                <button class="btn btn-google" type="button" style="margin-top:8px;" onclick="handleGoogleAuth()">🌐 S'inscrire via Google</button>
                <button class="btn btn-outline" type="button" style="margin-top:6px;" onclick="toggleAuthMode(false)">← Retour connexion</button>
            </div>
        </div>
    </div>

    <header class="no-print">
        <h1 id="headerCompany">TOGOLA GESTION</h1>
        <p>Créateur : Issa Togola (Tél : 72 14 88 70) • Appareil connecté : <span id="currentDeviceLabel" style="font-weight:bold; color:#FFD700;">Mobile</span><br>Compte : <span id="currentLoggedUser" style="text-decoration:underline;"></span> <a href="#" onclick="logoutSecure()" style="color:#FFD700; margin-left:4px; font-size:10px;">[Déconnexion Sécurisée]</a></p>
    </header>

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

    <div class="container">

        <!-- 1. ONGLET FACTURE -->
        <div id="tab-vente" class="tab-content">
            <div class="card no-print">
                <h2>✍️ Renseignements Facture</h2>
                <div class="row">
                    <div class="col">
                        <label>Numéro de Facture</label>
                        <input type="text" id="facNumber" value="N° 001" oninput="updateHeaderInfo()">
                    </div>
                    <div class="col">
                        <label>Date</label>
                        <input type="text" id="facDate" oninput="updateHeaderInfo()">
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        <label>DOIT (Client)</label>
                        <input type="text" id="clientName" placeholder="Nom du client" oninput="updateHeaderInfo()">
                    </div>
                    <div class="col">
                        <label>Statut de Paiement</label>
                        <select id="facStatus">
                            <option value="PAYÉ">Payé</option>
                            <option value="NON PAYÉ">Non Payé</option>
                        </select>
                    </div>
                </div>
                
                <label style="margin-top:8px;">Sélection rapide depuis le stock (Synchro Temps Réel)</label>
                <select id="stockPicker" onchange="pickStockItem(this)">
                    <option value="">-- Choisir un produit stocké --</option>
                </select>
            </div>

            <div class="card">
                <div class="no-print" style="margin-bottom: 6px; display:flex; justify-content:space-between; align-items:center;">
                    <span id="badgeInvoiceType" style="font-size: 11px; font-weight:bold; color:var(--primary);">FACTURE STANDARD</span>
                    <div>
                        <button type="button" onclick="toggleSecondPage()" id="btnTogglePage2" class="btn-outline" style="padding:4px 8px; font-size:10px; border-radius:4px; cursor:pointer; margin-right:6px;">📄 Activer 2ème Page</button>
                        <button type="button" onclick="clearTable()" style="background:none; border:none; color:red; font-size:11px; cursor:pointer;">Effacer</button>
                    </div>
                </div>

                <!-- PAGE 1 -->
                <div class="custom-invoice-sheet">
                    <div class="sheet-header">
                        <div class="sheet-logo-area" id="sheetLogoContainer"><div class="sheet-logo-placeholder">Logo</div></div>
                        <div class="sheet-company-info">
                            <h3 id="sheetCompanyTitle">TOGOLA GESTION</h3>
                            <p id="sheetCompanySub">Vente des Produits Alimentation • En Gros et Demi Gros<br>NIF : 025023805J • Cell : (+223) 73 60 51 13 / 77 60 97 00</p>
                        </div>
                    </div>
                    <div class="sheet-meta">
                        <div><span id="lblInvoiceTypeName">FACTURE</span> N° <span id="lblFacNum">001</span> (Page 1/2)</div>
                        <div>Date : <span id="lblFacDate"></span></div>
                    </div>
                    <div style="font-size: 11px; font-weight: bold; margin-bottom: 6px;">
                        DOIT : <span id="lblClient" style="text-decoration: underline;">Client Passage</span>
                    </div>

                    <div style="overflow-x: auto;">
                        <table class="fixed-17-table">
                            <thead>
                                <tr>
                                    <th class="col-qte">Quantité</th>
                                    <th class="col-desc">Description</th>
                                    <th class="col-pu">Prix unitaire</th>
                                    <th class="col-montant">Montant</th>
                                </tr>
                            </thead>
                            <tbody id="invoiceRowsBody1"></tbody>
                            <tfoot>
                                <tr style="background-color: #E8EEF5; font-weight: bold;">
                                    <td colspan="3" style="text-align: right; padding-right: 8px; font-size: 11px;">TOTAL PAGE 1 :</td>
                                    <td id="grandTotalCell1" style="text-align: right; font-size: 12px; color: var(--primary);">0</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    <div class="sheet-footer">
                        Somme Page 1 : <strong id="lblSumWords1" style="font-size: 10px; text-transform: uppercase; color:var(--primary);">Zero Franc CFA</strong>
                    </div>

                    <div class="sheet-signatures">
                        <div class="sig-block"><div class="sig-box">Cachet & Signature</div><u>Pour Acquit</u></div>
                        <div class="sig-block"><div class="sig-box">Cachet & Signature</div><u>Le Fournisseur</u></div>
                    </div>

                    <div class="creator-watermark">Application développée par <strong>ISSA TOGOLA</strong> • Tél : 72 14 88 70</div>
                </div>

                <!-- PAGE 2 -->
                <div id="page2Container" class="page-break-container custom-invoice-sheet">
                    <div class="sheet-header">
                        <div class="sheet-logo-area sheetLogoContainer2"><div class="sheet-logo-placeholder">Logo</div></div>
                        <div class="sheet-company-info">
                            <h3 class="sheetCompanyTitle2">TOGOLA GESTION</h3>
                            <p class="sheetCompanySub2">Vente des Produits Alimentation • En Gros et Demi Gros</p>
                        </div>
                    </div>
                    <div class="sheet-meta">
                        <div><span class="lblInvoiceTypeName2">FACTURE</span> N° <span class="lblFacNum2">001</span> (Suite - Page 2/2)</div>
                        <div>Date : <span class="lblFacDate2"></span></div>
                    </div>
                    <div style="font-size: 11px; font-weight: bold; margin-bottom: 6px;">
                        DOIT : <span class="lblClient2" style="text-decoration: underline;">Client Passage</span>
                    </div>

                    <div style="overflow-x: auto;">
                        <table class="fixed-17-table">
                            <thead>
                                <tr>
                                    <th class="col-qte">Quantité</th>
                                    <th class="col-desc">Description (Suite)</th>
                                    <th class="col-pu">Prix unitaire</th>
                                    <th class="col-montant">Montant</th>
                                </tr>
                            </thead>
                            <tbody id="invoiceRowsBody2"></tbody>
                            <tfoot>
                                <tr style="background-color: #E8EEF5; font-weight: bold;">
                                    <td colspan="3" style="text-align: right; padding-right: 8px; font-size: 11px;">TOTAL GÉNÉRAL CUMULÉ :</td>
                                    <td id="grandTotalCellCumulative" style="text-align: right; font-size: 12px; color: var(--primary);">0</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    <div class="sheet-footer">
                        Arrêtée la présente Facture à la Somme Totale de : <br>
                        <strong id="lblSumWordsCumulative" style="font-size: 10px; text-transform: uppercase; color:var(--primary);">Zero Franc CFA</strong>
                    </div>

                    <div class="sheet-signatures">
                        <div class="sig-block"><div class="sig-box">Cachet & Signature</div><u>Pour Acquit</u></div>
                        <div class="sig-block"><div class="sig-box">Cachet & Signature</div><u>Le Fournisseur</u></div>
                    </div>

                    <div class="creator-watermark">Application développée par <strong>ISSA TOGOLA</strong> • Tél : 72 14 88 70</div>
                </div>

                <div class="no-print" style="margin-top: 12px;">
                    <button class="btn btn-green" type="button" onclick="checkoutSale()">✅ Enregistrer & Diffuser sur les 10 Téléphones</button>
                    <button class="btn btn-outline" type="button" style="margin-top:6px;" onclick="window.print()">🖨️ Télécharger / Imprimer en PDF</button>
                </div>
            </div>
        </div>

        <!-- 2. HISTORIQUE & LECTEUR PDF D'ARCHIVE -->
        <div id="tab-history" class="tab-content" style="display:none;">
            <div class="card no-print">
                <h2>📜 Historique & Synchro Temps Réel</h2>
                <div style="margin-bottom: 8px;">
                    <input type="text" id="searchHistory" placeholder="Rechercher client ou N°..." onkeyup="filterHistory()">
                </div>
                <div id="historyList"></div>
                <button class="btn btn-red" type="button" style="margin-top:10px; font-size:11px;" onclick="clearHistory()">Effacer l'historique global</button>
            </div>

            <div id="archiveReaderCard" class="card" style="display:none; border: 2px dashed var(--primary);">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;" class="no-print">
                    <h2 style="margin:0; font-size:13px;">👁️ Lecteur Facture Archivée</h2>
                    <div>
                        <button type="button" onclick="window.print()" class="btn-outline" style="padding:4px 8px; font-size:10px; border-radius:4px; cursor:pointer; margin-right:6px;">🖨️ Imprimer / PDF</button>
                        <button type="button" onclick="closeArchiveReader()" style="background:none; border:none; color:red; font-size:12px; cursor:pointer; font-weight:bold;">✕ Fermer</button>
                    </div>
                </div>
                <div id="archiveSheetContainer"></div>
            </div>
        </div>

        <!-- 3. STOCK -->
        <div id="tab-stock" class="tab-content" style="display:none;">
            <div class="card no-print">
                <h2>📦 Répertoire Produits (Temps Réel 10 Postes)</h2>
                <label>Nom du Produit</label>
                <input type="text" id="stockName" placeholder="ex: Article standard">
                <div class="row">
                    <div class="col"><label>Prix Unitaire</label><input type="number" id="stockPrice" placeholder="0"></div>
                    <div class="col"><label>Quantité</label><input type="number" id="stockQty" placeholder="0"></div>
                </div>
                <button class="btn" type="button" onclick="addStockItem()">Ajouter et Synchroniser</button>
            </div>
            <div class="card">
                <h2>📋 Stock disponible (<span id="stockCountHeader">0</span>)</h2>
                <div id="stockList"></div>
            </div>
        </div>

        <!-- 4. PARAMÈTRES & SÉCURITÉ DES APPAREILS -->
        <div id="tab-param" class="tab-content" style="display:none;">
            <div class="card" style="border-left: 4px solid var(--primary); background: #F8FAFC;">
                <h2 style="color: var(--primary);">🛡️ Sécurité & Appareils Connectés</h2>
                <p style="font-size: 12px; line-height: 1.5; color: #333; margin-top: 5px;">
                    <strong>Développeur :</strong> Issa Togola (Tél : 72 14 88 70)<br>
                    <strong>Compte Actuel :</strong> <span id="paramUserDisplay" style="font-weight:bold; color:var(--primary);"></span><br>
                    <strong>Postes Actifs (Max 10) :</strong> <span id="activeDevicesCount" style="color:var(--success); font-weight:bold;">1 Appareil actif</span><br>
                    <strong>État Synchro Live :</strong> <span style="color:var(--success); font-weight:bold;">Actif (Mise à jour automatique)</span>
                </p>
                <div style="display:flex; gap:8px; margin-top:10px;">
                    <button class="btn btn-google" type="button" style="margin-top:0; font-size:11px;" onclick="handleGoogleAuth()">🌐 Synchro Compte Google</button>
                    <button class="btn btn-red" type="button" style="margin-top:0; font-size:11px;" onclick="logoutSecure()">Déconnexion Sécurisée</button>
                </div>
            </div>

            <div class="card">
                <h2>🎨 Type de Facture</h2>
                <label>Sélectionner le format de document</label>
                <select id="invoiceTypeSelect" onchange="saveSettings()">
                    <option value="FACTURE">1. Facture Standard</option>
                    <option value="FACTURE PROFORMA">2. Facture Proforma</option>
                    <option value="REÇU DE PAIEMENT">3. Reçu de Paiement</option>
                    <option value="BON DE LIVRAISON">4. Bon de Livraison</option>
                    <option value="FACTURE GROS / DEMI-GROS">5. Facture Gros / Demi-Gros</option>
                </select>
            </div>

            <div class="card">
                <h2>🖼️ Logo de l'Entreprise</h2>
                <label>Importer une image (Synchronisée sur les 10 téléphones)</label>
                <input type="file" id="logoFileInput" accept="image/*" onchange="handleLogoUpload(event)">
                <div id="logoPreviewBox" 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>⚙️ Informations de l'Entreprise</h2>
                <label>Nom de l'Entreprise</label>
                <input type="text" id="companyInput">
                <label>Activité / Sous-titre</label>
                <input type="text" id="subInput">
                <label>Adresse / Contacts</label>
                <input type="text" id="addressInput">
                <button class="btn" type="button" onclick="saveSettings()">Mettre à jour et Diffuser</button>
            </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> Facture</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> Param</button>
    </div>

    <script>
        let currentUser = null;
        let currentDeviceId = "Phone_" + Math.floor(Math.random() * 10000);
        let accounts = [];
        let config = { name: "TOGOLA GESTION", sub: "Vente des Produits Alimentation", address: "Bamako - Mali", invoiceType: "FACTURE", logo: "" };
        let stockData = [];
        let salesHistory = [];
        let isPage2Active = false;

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

        // --- ECOUTEUR TEMPS RÉEL (10 TÉLÉPHONES VIA STORAGE EVENT) ---
        window.addEventListener('storage', function(e) {
            if(!currentUser) return;
            if(e.key === 'tg_cityweb_accounts_v12') {
                loadAllAccounts();
                loadUserData(currentUser);
                showToast("🔄 Données actualisées en temps réel depuis un autre téléphone !");
            }
        });

        function loadAllAccounts() {
            try {
                let accs = localStorage.getItem('tg_cityweb_accounts_v12');
                if(accs) accounts = JSON.parse(accs);
                let cur = localStorage.getItem('tg_cityweb_current_user_v12');
                if(cur) {
                    currentUser = cur;
                    loadUserData(currentUser);
                    document.getElementById('authScreen').style.display = 'none';
                }
            } catch(e) {}
        }

        function toggleAuthMode(isRegister) {
            document.getElementById('authFormLogin').style.display = isRegister ? 'none' : 'block';
            document.getElementById('authFormRegister').style.display = isRegister ? 'block' : 'none';
        }

        function handleRegister() {
            let comp = document.getElementById('regCompany').value.trim();
            let user = document.getElementById('regUser').value.trim().toLowerCase();
            let pass = document.getElementById('regPass').value.trim();

            if(!comp || !user || !pass) {
                showToast("Veuillez remplir tous les champs.");
                return;
            }

            if(accounts.some(a => a.user === user)) {
                showToast("Ce nom d'utilisateur existe déjà !");
                return;
            }

            let newAccount = {
                user: user,
                pass: pass,
                devices: [currentDeviceId],
                config: { name: comp, sub: "Vente en Gros et Demi Gros", address: "Bamako - Mali", invoiceType: "FACTURE", logo: "" },
                stock: [{ id: 1, name: "Article Standard", price: 1500, qty: 20 }],
                sales: []
            };

            accounts.push(newAccount);
            localStorage.setItem('tg_cityweb_accounts_v12', JSON.stringify(accounts));

            currentUser = user;
            localStorage.setItem('tg_cityweb_current_user_v12', currentUser);
            loadUserData(currentUser);
            document.getElementById('authScreen').style.display = 'none';
            showToast("✅ Compte créé avec synchronisation multi-appareils active !");
        }

        function handleLogin() {
            let user = document.getElementById('loginUser').value.trim().toLowerCase();
            let pass = document.getElementById('loginPass').value.trim();

            let found = accounts.find(a => a.user === user && a.pass === pass);
            if(found) {
                // Gestion de la limite des 10 téléphones connectés simultanément
                if(!found.devices) found.devices = [];
                if(!found.devices.includes(currentDeviceId)) {
                    if(found.devices.length >= 10) {
                        found.devices.shift(); // Retire le plus ancien pour laisser place au nouveau (max 10)
                    }
                    found.devices.push(currentDeviceId);
                }

                currentUser = user;
                localStorage.setItem('tg_cityweb_current_user_v12', JSON.stringify(accounts));
                localStorage.setItem('tg_cityweb_current_user_v12_active', currentUser);
                
                loadUserData(currentUser);
                document.getElementById('authScreen').style.display = 'none';
                showToast("✅ Connexion réussie (Synchro temps réel active) !");
            } else {
                showToast("Identifiant ou mot de passe incorrect.");
            }
        }

        function handleGoogleAuth() {
            let googleEmail = prompt("Entrez votre adresse email Google pour synchroniser vos 10 téléphones :");
            if(!googleEmail || !googleEmail.includes("@")) return;

            googleEmail = googleEmail.trim().toLowerCase();
            let found = accounts.find(a => a.user === googleEmail);

            if(!found) {
                let compName = prompt("Nom de votre entreprise pour ce compte Google :") || "TOGOLA GESTION GOOGLE";
                found = {
                    user: googleEmail,
                    pass: "GOOGLE_SECURE_AUTH",
                    devices: [currentDeviceId],
                    config: { name: compName, sub: "Vente en Gros et Demi Gros", address: "Bamako - Mali", invoiceType: "FACTURE", logo: "" },
                    stock: [{ id: 1, name: "Produit Google", price: 2000, qty: 30 }],
                    sales: []
                };
                accounts.push(found);
            } else {
                if(!found.devices) found.devices = [];
                if(!found.devices.includes(currentDeviceId)) {
                    if(found.devices.length >= 10) found.devices.shift();
                    found.devices.push(currentDeviceId);
                }
            }

            localStorage.setItem('tg_cityweb_accounts_v12', JSON.stringify(accounts));
            currentUser = googleEmail;
            localStorage.setItem('tg_cityweb_current_user_v12', currentUser);
            
            loadUserData(currentUser);
            document.getElementById('authScreen').style.display = 'none';
            showToast("✅ Compte Google lié et synchronisé en temps réel !");
        }

        function logoutSecure() {
            if(currentUser) {
                let acc = accounts.find(a => a.user === currentUser);
                if(acc && acc.devices) {
                    acc.devices = acc.devices.filter(d => d !== currentDeviceId);
                    localStorage.setItem('tg_cityweb_accounts_v12', JSON.stringify(accounts));
                }
            }
            currentUser = null;
            localStorage.removeItem('tg_cityweb_current_user_v12');
            document.getElementById('authScreen').style.display = 'flex';
            showToast("🔒 Déconnexion sécurisée effectuée.");
        }

        function loadUserData(username) {
            let acc = accounts.find(a => a.user === username);
            if(acc) {
                config = acc.config || config;
                stockData = acc.stock || [];
                salesHistory = acc.sales || [];
                let devCount = acc.devices ? acc.devices.length : 1;
                document.getElementById('activeDevicesCount').innerText = `${devCount} Appareil(s) connecté(s) en direct`;
            }
            document.getElementById('currentLoggedUser').innerText = username;
            document.getElementById('paramUserDisplay').innerText = username;
            document.getElementById('currentDeviceLabel').innerText = currentDeviceId;
            initAppUI();
        }

        function saveUserData() {
            if(!currentUser) return;
            let accIndex = accounts.findIndex(a => a.user === currentUser);
            if(accIndex !== -1) {
                accounts[accIndex].config = config;
                accounts[accIndex].stock = stockData;
                accounts[accIndex].sales = salesHistory;
                localStorage.setItem('tg_cityweb_accounts_v12', JSON.stringify(accounts));
            }
        }

        function initAppUI() {
            document.getElementById('headerCompany').innerText = config.name;
            document.getElementById('sheetCompanyTitle').innerText = config.name;
            document.getElementById('sheetCompanySub').innerHTML = `${config.sub}<br>NIF : 025023805J • ${config.address}`;
            
            document.querySelectorAll('.sheetCompanyTitle2').forEach(el => el.innerText = config.name);
            document.querySelectorAll('.sheetCompanySub2').forEach(el => el.innerHTML = `${config.sub}<br>NIF : 025023805J • ${config.address}`);

            document.getElementById('companyInput').value = config.name;
            document.getElementById('subInput').value = config.sub;
            document.getElementById('addressInput').value = config.address;
            document.getElementById('invoiceTypeSelect').value = config.invoiceType || "FACTURE";

            document.getElementById('badgeInvoiceType').innerText = config.invoiceType;
            let shortType = config.invoiceType.split(' ')[0];
            document.getElementById('lblInvoiceTypeName').innerText = shortType;
            document.querySelectorAll('.lblInvoiceTypeName2').forEach(el => el.innerText = shortType);

            let today = new Date().toLocaleDateString('fr-FR');
            document.getElementById('facDate').value = today;
            document.getElementById('lblFacDate').innerText = today;
            document.querySelectorAll('.lblFacDate2').forEach(el => el.innerText = today);

            buildTables();
            renderLogoInSheet();
            renderStock();
            updatePicker();
            renderHistory();
        }

        function handleLogoUpload(event) {
            let file = event.target.files[0];
            if(!file) return;
            let reader = new FileReader();
            reader.onload = function(e) {
                config.logo = e.target.result;
                saveUserData();
                renderLogoInSheet();
                showToast("✅ Logo mis à jour et diffusé sur tous les téléphones !");
            };
            reader.readAsDataURL(file);
        }

        function removeLogo() {
            config.logo = "";
            saveUserData();
            renderLogoInSheet();
            showToast("Logo supprimé.");
        }

        function renderLogoInSheet() {
            let containers = [document.getElementById('sheetLogoContainer'), ...document.querySelectorAll('.sheetLogoContainer2')];
            let preview = document.getElementById('logoPreviewBox');
            
            containers.forEach(container => {
                if(!container) return;
                if(config.logo) {
                    container.innerHTML = `<img src="${config.logo}" alt="Logo">`;
                } else {
                    container.innerHTML = `<div class="sheet-logo-placeholder">Logo</div>`;
                }
            });

            if(config.logo) {
                preview.innerHTML = `<img src="${config.logo}" style="max-height:70px; border-radius:6px; border:1px solid #ccc;">`;
            } else {
                preview.innerHTML = `<p style="font-size:11px; color:#777;">Aucun logo</p>`;
            }
        }

        function buildTables() {
            let body1 = document.getElementById('invoiceRowsBody1');
            let body2 = document.getElementById('invoiceRowsBody2');
            let html1 = '', html2 = '';

            for(let i = 1; i <= 16; i++) {
                html1 += `<tr>
                    <td class="col-qte"><input type="number" id="q1_${i}" min="0" oninput="calcTotals()"></td>
                    <td class="col-desc"><input type="text" id="d1_${i}" placeholder="..."></td>
                    <td class="col-pu"><input type="number" id="p1_${i}" min="0" oninput="calcTotals()" placeholder="0"></td>
                    <td class="col-montant" id="m1_${i}" style="text-align: right;">0</td>
                </tr>`;
            }
            for(let i = 1; i <= 16; i++) {
                html2 += `<tr>
                    <td class="col-qte"><input type="number" id="q2_${i}" min="0" oninput="calcTotals()"></td>
                    <td class="col-desc"><input type="text" id="d2_${i}" placeholder="..."></td>
                    <td class="col-pu"><input type="number" id="p2_${i}" min="0" oninput="calcTotals()" placeholder="0"></td>
                    <td class="col-montant" id="m2_${i}" style="text-align: right;">0</td>
                </tr>`;
            }
            body1.innerHTML = html1;
            body2.innerHTML = html2;
        }

        function calcTotals() {
            let total1 = 0;
            let hasDataInPage2 = false;

            for(let i = 1; i <= 16; i++) {
                let q = parseFloat(document.getElementById(`q1_${i}`).value) || 0;
                let p = parseFloat(document.getElementById(`p1_${i}`).value) || 0;
                let m = q * p;
                document.getElementById(`m1_${i}`).innerText = m ? m.toLocaleString() : '0';
                total1 += m;
            }
            document.getElementById('grandTotalCell1').innerText = total1.toLocaleString() + " FCFA";
            document.getElementById('lblSumWords1').innerText = total1.toLocaleString() + " Francs CFA";

            let total2 = 0;
            for(let i = 1; i <= 16; i++) {
                let q = parseFloat(document.getElementById(`q2_${i}`).value) || 0;
                let desc = document.getElementById(`d2_${i}`).value.trim();
                let p = parseFloat(document.getElementById(`p2_${i}`).value) || 0;
                let m = q * p;
                document.getElementById(`m2_${i}`).innerText = m ? m.toLocaleString() : '0';
                total2 += m;
                if(desc || m > 0 || q > 0) hasDataInPage2 = true;
            }

            let lastRowPage1Q = parseFloat(document.getElementById(`q1_16`).value) || 0;
            let lastRowPage1Desc = document.getElementById(`d1_16`).value.trim();
            if((lastRowPage1Q > 0 || lastRowPage1Desc) && !isPage2Active) {
                isPage2Active = true;
                document.getElementById('page2Container').classList.add('active');
                document.getElementById('btnTogglePage2').innerText = "📄 Masquer 2ème Page";
            } else if(hasDataInPage2 && !isPage2Active) {
                isPage2Active = true;
                document.getElementById('page2Container').classList.add('active');
                document.getElementById('btnTogglePage2').innerText = "📄 Masquer 2ème Page";
            }

            let grandTotal = total1 + total2;
            document.getElementById('grandTotalCellCumulative').innerText = grandTotal.toLocaleString() + " FCFA";
            document.getElementById('lblSumWordsCumulative').innerText = grandTotal.toLocaleString() + " Francs CFA";
        }

        function toggleSecondPage() {
            isPage2Active = !isPage2Active;
            let p2 = document.getElementById('page2Container');
            let btn = document.getElementById('btnTogglePage2');
            if(isPage2Active) {
                p2.classList.add('active');
                btn.innerText = "📄 Masquer 2ème Page";
            } else {
                p2.classList.remove('active');
                btn.innerText = "📄 Activer 2ème Page";
            }
        }

        function clearTable() {
            for(let i = 1; i <= 16; i++) {
                document.getElementById(`q1_${i}`).value = '';
                document.getElementById(`d1_${i}`).value = '';
                document.getElementById(`p1_${i}`).value = '';
                document.getElementById(`m1_${i}`).innerText = '0';
                
                document.getElementById(`q2_${i}`).value = '';
                document.getElementById(`d2_${i}`).value = '';
                document.getElementById(`p2_${i}`).value = '';
                document.getElementById(`m2_${i}`).innerText = '0';
            }
            isPage2Active = false;
            document.getElementById('page2Container').classList.remove('active');
            document.getElementById('btnTogglePage2').innerText = "📄 Activer 2ème Page";
            calcTotals();
            showToast('Tableau réinitialisé.');
        }

        function updateHeaderInfo() {
            let name = document.getElementById('clientName').value || 'Client Passage';
            let num = document.getElementById('facNumber').value || 'N° 001';
            let date = document.getElementById('facDate').value || '';

            document.getElementById('lblClient').innerText = name;
            document.querySelectorAll('.lblClient2').forEach(el => el.innerText = name);
            document.getElementById('lblFacNum').innerText = num;
            document.querySelectorAll('.lblFacNum2').forEach(el => el.innerText = num);
            document.getElementById('lblFacDate').innerText = date;
            document.querySelectorAll('.lblFacDate2').forEach(el => el.innerText = date);
        }

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

        function saveSettings() {
            config.name = document.getElementById('companyInput').value.trim() || "TOGOLA GESTION";
            config.sub = document.getElementById('subInput').value.trim();
            config.address = document.getElementById('addressInput').value.trim();
            config.invoiceType = document.getElementById('invoiceTypeSelect').value;
            saveUserData();
            initAppUI();
            showToast('Paramètres mis à jour et synchronisés sur les 10 téléphones !');
        }

        function renderStock() {
            let html = '';
            stockData.forEach(item => {
                html += `<div class="table-item">
                    <div><strong>${item.name}</strong><br><small>${item.price.toLocaleString()} FCFA</small></div>
                    <div><strong>${item.qty} dispo</strong> <button type="button" onclick="deleteStock(${item.id})" style="border:none;background:none;color:red;margin-left:6px;cursor:pointer;">✕</button></div>
                </div>`;
            });
            document.getElementById('stockCountHeader').innerText = stockData.length;
            document.getElementById('stockList').innerHTML = html || '<p style="font-size:11px; color:#777;">Aucun stock.</p>';
        }

        function updatePicker() {
            let p = document.getElementById('stockPicker');
            p.innerHTML = '<option value="">-- Choisir un produit stocké --</option>';
            stockData.forEach(item => {
                p.innerHTML += `<option value="${item.id}">${item.name} (${item.price} FCFA)</option>`;
            });
        }

        function pickStockItem(sel) {
            let id = sel.value;
            if(!id) return;
            let prod = stockData.find(x => x.id == id);
            if(!prod) return;

            for(let i = 1; i <= 16; i++) {
                if(!document.getElementById(`d1_${i}`).value) {
                    document.getElementById(`q1_${i}`).value = 1;
                    document.getElementById(`d1_${i}`).value = prod.name;
                    document.getElementById(`p1_${i}`).value = prod.price;
                    calcTotals();
                    sel.value = "";
                    return;
                }
            }

            isPage2Active = true;
            document.getElementById('page2Container').classList.add('active');
            document.getElementById('btnTogglePage2').innerText = "📄 Masquer 2ème Page";

            for(let i = 1; i <= 16; i++) {
                if(!document.getElementById(`d2_${i}`).value) {
                    document.getElementById(`q2_${i}`).value = 1;
                    document.getElementById(`d2_${i}`).value = prod.name;
                    document.getElementById(`p2_${i}`).value = prod.price;
                    calcTotals();
                    sel.value = "";
                    return;
                }
            }
            showToast('Toutes les lignes sont occupées.');
            sel.value = "";
        }

        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('Nom et prix requis.'); return; }
            stockData.push({ id: Date.now(), name, price, qty });
            saveUserData();
            renderStock();
            updatePicker();
            document.getElementById('stockName').value = '';
            document.getElementById('stockPrice').value = '';
            document.getElementById('stockQty').value = '';
            showToast('Produit ajouté et diffusé en temps réel !');
        }

        function deleteStock(id) {
            stockData = stockData.filter(s => s.id !== id);
            saveUserData();
            renderStock();
            updatePicker();
            showToast('Supprimé.');
        }

        function checkoutSale() {
            let client = document.getElementById('clientName').value || 'Client Passage';
            let num = document.getElementById('facNumber').value || 'N° 001';
            let status = document.getElementById('facStatus').value;
            let activeItems = [];
            let totalVal = 0;

            for(let i = 1; i <= 16; i++) {
                let q = parseFloat(document.getElementById(`q1_${i}`).value) || 0;
                let d = document.getElementById(`d1_${i}`).value.trim();
                let p = parseFloat(document.getElementById(`p1_${i}`).value) || 0;
                let m = q * p;
                if(d && m > 0) {
                    activeItems.push({ qte: q, desc: d, pu: p, montant: m });
                    totalVal += m;
                }
            }

            if(isPage2Active) {
                for(let i = 1; i <= 16; i++) {
                    let q = parseFloat(document.getElementById(`q2_${i}`).value) || 0;
                    let d = document.getElementById(`d2_${i}`).value.trim();
                    let p = parseFloat(document.getElementById(`p2_${i}`).value) || 0;
                    let m = q * p;
                    if(d && m > 0) {
                        activeItems.push({ qte: q, desc: d, pu: p, montant: m });
                        totalVal += m;
                    }
                }
            }

            if(activeItems.length === 0) { showToast('Remplissez au moins une ligne.'); return; }

            salesHistory.unshift({
                id: num,
                type: config.invoiceType,
                date: document.getElementById('facDate').value,
                client: client,
                status: status,
                items: activeItems,
                total: totalVal
            });

            saveUserData();
            renderHistory();
            showToast('✅ Facture enregistrée et synchronisée sur les 10 téléphones !');
            clearTable();
            document.getElementById('clientName').value = '';
            updateHeaderInfo();
        }

        function renderHistory() {
            let html = '';
            salesHistory.forEach((s, index) => {
                let statusClass = s.status === 'PAYÉ' ? 'status-paye' : 'status-impaye';
                html += `<div class="table-item" style="flex-direction:column; align-items:flex-start; background:#FAFAFA; padding:10px; margin-bottom:6px; border-radius:6px; border:1px solid #E5E7EB;">
                    <div style="width:100%; display:flex; justify-content:space-between; align-items:center;">
                        <strong>${s.id} (${s.type})</strong>
                        <span class="badge-status ${statusClass}">${s.status || 'PAYÉ'}</span>
                    </div>
                    <div style="width:100%; display:flex; justify-content:space-between; align-items:center; margin-top:4px;">
                        <span style="font-size:11px; color:#444;">👤 ${s.client} • 📅 ${s.date}</span>
                        <strong style="color:var(--primary); font-size:12px;">${s.total.toLocaleString()} FCFA</strong>
                    </div>
                    <div style="width:100%; display:flex; justify-content:flex-end; gap:8px; margin-top:8px;" class="no-print">
                        <button type="button" onclick="openArchiveReader(${index})" class="btn-outline" style="padding:4px 10px; font-size:10px; border-radius:4px; cursor:pointer;">👁️ Ouvrir (PDF)</button>
                        <button type="button" onclick="deleteHistoryItem(${index})" style="background:none; border:none; color:red; font-size:11px; cursor:pointer;">Supprimer</button>
                    </div>
                </div>`;
            });
            document.getElementById('historyList').innerHTML = html || '<p style="font-size:11px; color:#777;">Aucune facture.</p>';
        }

        function openArchiveReader(index) {
            let s = salesHistory[index];
            if(!s) return;

            let shortType = s.type.split(' ')[0];
            let page1Items = s.items.slice(0, 16);
            let page2Items = s.items.slice(16, 32);
            let hasPage2 = page2Items.length > 0;
            let totalPage1 = page1Items.reduce((acc, curr) => acc + curr.montant, 0);

            let html = `<div class="custom-invoice-sheet" style="display:block !important;">
                <div class="sheet-header">
                    <div class="sheet-logo-area">${config.logo ? `<img src="${config.logo}">` : '<div class="sheet-logo-placeholder">Logo</div>'}</div>
                    <div class="sheet-company-info">
                        <h3>${config.name}</h3>
                        <p>${config.sub}<br>NIF : 025023805J • ${config.address}</p>
                    </div>
                </div>
                <div class="sheet-meta">
                    <div>${shortType} N° ${s.id} ${hasPage2 ? '(Page 1/2)' : ''}</div>
                    <div>Date : ${s.date}</div>
                </div>
                <div style="font-size: 11px; font-weight: bold; margin-bottom: 6px;">
                    DOIT : <span style="text-decoration: underline;">${s.client}</span> • Statut : <span class="badge-status ${s.status === 'PAYÉ' ? 'status-paye' : 'status-impaye'}">${s.status}</span>
                </div>
                <table class="fixed-17-table">
                    <thead><tr><th class="col-qte">Quantité</th><th class="col-desc">Description</th><th class="col-pu">Prix unitaire</th><th class="col-montant">Montant</th></tr></thead>
                    <tbody>`;

            page1Items.forEach(it => {
                html += `<tr><td class="col-qte" style="text-align:center;">${it.qte}</td><td class="col-desc">${it.desc}</td><td class="col-pu" style="text-align:right;">${it.pu.toLocaleString()}</td><td class="col-montant" style="text-align:right;">${it.montant.toLocaleString()}</td></tr>`;
            });
            for(let i = page1Items.length; i < 16; i++) {
                html += `<tr><td class="col-qte">&nbsp;</td><td class="col-desc">&nbsp;</td><td class="col-pu">&nbsp;</td><td class="col-montant">&nbsp;</td></tr>`;
            }

            html += `</tbody>
                    <tfoot>
                        <tr style="background-color: #E8EEF5; font-weight: bold;">
                            <td colspan="3" style="text-align: right; padding-right: 8px; font-size: 11px;">${hasPage2 ? 'TOTAL PAGE 1 :' : 'TOTAL GÉNÉRAL :'}</td>
                            <td style="text-align: right; font-size: 12px; color: var(--primary);">${totalPage1.toLocaleString()} FCFA</td>
                        </tr>
                    </tfoot>
                </table>
                <div class="sheet-footer">Somme : <strong style="text-transform: uppercase; color:var(--primary);">${totalPage1.toLocaleString()} Francs CFA</strong></div>
                <div class="sheet-signatures">
                    <div class="sig-block"><div class="sig-box">Cachet & Signature</div><u>Pour Acquit</u></div>
                    <div class="sig-block"><div class="sig-box">Cachet & Signature</div><u>Le Fournisseur</u></div>
                </div>
                <div class="creator-watermark">Application développée par <strong>ISSA TOGOLA</strong> • Tél : 72 14 88 70</div>
            </div>`;

            if(hasPage2) {
                let totalCumulative = s.total;
                html += `<div class="custom-invoice-sheet" style="display:block !important; page-break-before: always;">
                    <div class="sheet-header">
                        <div class="sheet-logo-area">${config.logo ? `<img src="${config.logo}">` : '<div class="sheet-logo-placeholder">Logo</div>'}</div>
                        <div class="sheet-company-info"><h3>${config.name}</h3><p>${config.sub}</p></div>
                    </div>
                    <div class="sheet-meta"><div>${shortType} N° ${s.id} (Suite - Page 2/2)</div><div>Date : ${s.date}</div></div>
                    <div style="font-size: 11px; font-weight: bold; margin-bottom: 6px;">DOIT : <span style="text-decoration: underline;">${s.client}</span></div>
                    <table class="fixed-17-table">
                        <thead><tr><th class="col-qte">Quantité</th><th class="col-desc">Description (Suite)</th><th class="col-pu">Prix unitaire</th><th class="col-montant">Montant</th></tr></thead>
                        <tbody>`;
                page2Items.forEach(it => {
                    html += `<tr><td class="col-qte" style="text-align:center;">${it.qte}</td><td class="col-desc">${it.desc}</td><td class="col-pu" style="text-align:right;">${it.pu.toLocaleString()}</td><td class="col-montant" style="text-align:right;">${it.montant.toLocaleString()}</td></tr>`;
                });
                for(let i = page2Items.length; i < 16; i++) {
                    html += `<tr><td class="col-qte">&nbsp;</td><td class="col-desc">&nbsp;</td><td class="col-pu">&nbsp;</td><td class="col-montant">&nbsp;</td></tr>`;
                }
                html += `</tbody>
                        <tfoot>
                            <tr style="background-color: #E8EEF5; font-weight: bold;">
                                <td colspan="3" style="text-align: right; padding-right: 8px; font-size: 11px;">TOTAL GÉNÉRAL CUMULÉ :</td>
                                <td style="text-align: right; font-size: 12px; color: var(--primary);">${totalCumulative.toLocaleString()} FCFA</td>
                            </tr>
                        </tfoot>
                    </table>
                    <div class="sheet-footer">Arrêtée la présente Facture à la Somme Totale de :<br><strong style="text-transform: uppercase; color:var(--primary);">${totalCumulative.toLocaleString()} Francs CFA</strong></div>
                    <div class="sheet-signatures">
                        <div class="sig-block"><div class="sig-box">Cachet & Signature</div><u>Pour Acquit</u></div>
                        <div class="sig-block"><div class="sig-box">Cachet & Signature</div><u>Le Fournisseur</u></div>
                    </div>
                    <div class="creator-watermark">Application développée par <strong>ISSA TOGOLA</strong> • Tél : 72 14 88 70</div>
                `;
            }

            document.getElementById('archiveSheetContainer').innerHTML = html;
            let readerCard = document.getElementById('archiveReaderCard');
            readerCard.style.display = 'block';
            readerCard.scrollIntoView({ behavior: 'smooth' });
        }

        function closeArchiveReader() {
            document.getElementById('archiveReaderCard').style.display = 'none';
        }

        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 deleteHistoryItem(index) {
            if(confirm("Supprimer cette facture ?")) {
                salesHistory.splice(index, 1);
                saveUserData();
                renderHistory();
                closeArchiveReader();
                showToast('Facture supprimée et synchronisée.');
            }
        }

        function clearHistory() {
            if(confirm("Effacer tout l'historique sur tous les appareils ?")) {
                salesHistory = [];
                saveUserData();
                renderHistory();
                closeArchiveReader();
                showToast('Historique effacé partout.');
            }
        }

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