<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ouagadou Distribution - Stock & Facturation</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 20px; background-color: #f0f2f5; color: #333; }
        .container { max-width: 1000px; margin: auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        h1, h2 { color: #0056b3; }
        .hidden { display: none !important; }
        input, select, button { padding: 10px; margin: 5px 0; font-size: 14px; border: 1px solid #ccc; border-radius: 5px; width: 100%; box-sizing: border-box; }
        button { background-color: #007BFF; color: white; border: none; cursor: pointer; font-weight: bold; }
        button:hover { background-color: #0056b3; }
        .btn-success { background-color: #28a745; }
        .btn-success:hover { background-color: #218838; }
        .btn-danger { background-color: #dc3545; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
        th { background-color: #007BFF; color: white; }
        .badge-instock { background-color: #d4edda; color: #155724; padding: 4px 8px; border-radius: 4px; font-size: 12px; }
        .badge-outstock { background-color: #f8d7da; color: #721c24; padding: 4px 8px; border-radius: 4px; font-size: 12px; }
        
        /* Style Facture A4 */
        #invoiceA4Modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); display: flex; justify-content: center; align-items: center; z-index: 1000; }
        .a4-sheet { background: white; width: 210mm; min-height: 297mm; padding: 20mm; box-shadow: 0 0 10px rgba(0,0,0,0.3); box-sizing: border-box; position: relative; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; }
        .a4-header { display: flex; justify-content: space-between; border-bottom: 2px solid #0056b3; padding-bottom: 15px; margin-bottom: 20px; }
        .modal-buttons { margin-top: 20px; display: flex; gap: 10px; }
    </style>
</head>
<body>

<div class="container">
    <!-- ÉCRAN DE CONNEXION -->
    <div id="loginScreen">
        <h2>🔐 Connexion - OUAGADOU DISTRIBUTION</h2>
        <p>Utilisateurs par défaut : <b>admin / admin123</b> ou <b>vendeur / vendeur123</b></p>
        <label>Identifiant :</label>
        <input type="text" id="loginUser" placeholder="Entrez votre identifiant">
        <label>Mot de passe :</label>
        <input type="password" id="loginPass" placeholder="Entrez votre mot de passe">
        <button onclick="login()">Se connecter</button>
    </div>

    <!-- APPLICATION PRINCIPALE -->
    <div id="appScreen" class="hidden">
        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #eee; padding-bottom: 10px;">
            <h1>📦 OUAGADOU DISTRIBUTION - Stock & Facturation</h1>
            <div>
                <span>Connecté : <b id="currentUserRole"></b></span>
                <button onclick="logout()" class="btn-danger" style="width: auto; padding: 5px 15px; margin-left: 15px;">Déconnexion</button>
            </div>
        </div>

        <!-- SECTION 1 : GESTION DES STOCKS -->
        <section id="stockSection" style="margin-top: 20px;">
            <h2>1. Gestion des Produits & Stocks</h2>
            <div style="display: grid; grid-template-columns: 2fr 1fr 1fr 1fr; gap: 10px;">
                <input type="text" id="prodName" placeholder="Nom du produit">
                <input type="number" id="prodPrice" placeholder="Prix (€)" min="0">
                <input type="number" id="prodStock" placeholder="Quantité" min="0">
                <button onclick="addProduct()">Ajouter Produit</button>
            </div>

            <table>
                <thead>
                    <tr>
                        <th>Produit</th>
                        <th>Prix Unitaire</th>
                        <th>Quantité</th>
                        <th>Statut</th>
                    </tr>
                </thead>
                <tbody id="stockTableBody"></tbody>
            </table>
        </section>

        <!-- SECTION 2 : CRÉATION DE FACTURE -->
        <section style="margin-top: 40px;">
            <h2>2. Créer une Facture / Vente</h2>
            <input type="text" id="clientName" placeholder="Nom du client (ex: Entreprise ABC ou Particulier)">
            
            <div style="display: grid; grid-template-columns: 3fr 1fr 1fr; gap: 10px; margin-top: 10px;">
                <select id="invoiceProductSelect">
                    <option value="">Sélectionner un produit disponible</option>
                </select>
                <input type="number" id="invoiceQty" placeholder="Quantité" min="1" value="1">
                <button onclick="addToInvoice()">Ajouter à la facture</button>
            </div>

            <h3 style="margin-top: 20px;">Articles de la facture en cours</h3>
            <table>
                <thead>
                    <tr>
                        <th>Produit</th>
                        <th>Quantité</th>
                        <th>Prix Unitaire</th>
                        <th>Total Ligne</th>
                    </tr>
                </thead>
                <tbody id="invoiceTableBody"></tbody>
            </table>
            <h3>Total Général : <span id="invoiceTotal">0</span> €</h3>
            <button onclick="openA4Invoice()" class="btn-success">Générer la Facture A4 & Valider le Stock</button>
        </section>
    </div>
</div>

<!-- MODAL APERCU FACTURE A4 -->
<div id="invoiceA4Modal" class="hidden">
    <div>
        <div class="a4-sheet" id="printableA4">
            <div class="a4-header">
                <div>
                    <h2>FACTURE</h2>
                    <p><b>Date :</b> <span id="a4Date"></span></p>
                    <p><b>Client :</b> <span id="a4Client"></span></p>
                </div>
                <div style="text-align: right;">
                    <h3 style="color: #0056b3; margin: 0;">OUAGADOU DISTRIBUTION</h3>
                    <p style="margin: 5px 0;">Service Commercial & Logistique</p>
                    <p style="margin: 0;">contact@ouagadoudistribution.com</p>
                </div>
            </div>
            <h3>Détails des articles :</h3>
            <table>
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Quantité</th>
                        <th>Prix U.</th>
                        <th>Total</th>
                    </tr>
                </thead>
                <tbody id="a4TableBody"></tbody>
            </table>
            <h3 style="text-align: right; margin-top: 30px;">Total à payer : <span id="a4Total"></span> €</h3>
            <p style="margin-top: 50px; text-align: center; font-size: 12px; color: #666;">Merci pour votre confiance - OUAGADOU DISTRIBUTION !</p>
        </div>
        <div class="modal-buttons">
            <button onclick="window.print()" class="btn-success">Imprimer / Sauvegarder en PDF</button>
            <button onclick="closeA4Invoice()" class="btn-danger">Fermer & Finaliser</button>
        </div>
    </div>
</div>

<script>
    const users = [
        { user: "admin", pass: "admin123", role: "Administrateur" },
        { user: "vendeur", pass: "vendeur123", role: "Vendeur" }
    ];

    let stock = [
        { name: "Produit Exemple 1", price: 10.0, qty: 15 },
        { name: "Produit Exemple 2", price: 25.0, qty: 0 }
    ];
    let currentInvoiceItems = [];

    function login() {
        const u = document.getElementById('loginUser').value;
        const p = document.getElementById('loginPass').value;
        const found = users.find(x => x.user === u && x.pass === p);

        if (found) {
            document.getElementById('loginScreen').classList.add('hidden');
            document.getElementById('appScreen').classList.remove('hidden');
            document.getElementById('currentUserRole').innerText = `${found.user} (${found.role})`;
            updateUI();
        } else {
            alert("Identifiant ou mot de passe incorrect.");
        }
    }

    function logout() {
        document.getElementById('appScreen').classList.add('hidden');
        document.getElementById('loginScreen').classList.remove('hidden');
        document.getElementById('loginUser').value = '';
        document.getElementById('loginPass').value = '';
    }

    function addProduct() {
        const name = document.getElementById('prodName').value;
        const price = parseFloat(document.getElementById('prodPrice').value);
        const qty = parseInt(document.getElementById('prodStock').value);

        if (!name || isNaN(price) || isNaN(qty)) {
            alert("Veuillez remplir tous les champs correctement.");
            return;
        }

        stock.push({ name, price, qty });
        document.getElementById('prodName').value = '';
        document.getElementById('prodPrice').value = '';
        document.getElementById('prodStock').value = '';
        updateUI();
    }

    function updateUI() {
        const stockBody = document.getElementById('stockTableBody');
        stockBody.innerHTML = '';
        const selectProd = document.getElementById('invoiceProductSelect');
        selectProd.innerHTML = '<option value="">Sélectionner un produit disponible</option>';

        stock.forEach((item, index) => {
            const isOutOfStock = item.qty <= 0;
            const badge = isOutOfStock 
                ? '<span class="badge-outstock">Hors Stock</span>' 
                : '<span class="badge-instock">En Stock</span>';

            stockBody.innerHTML += `
                <tr>
                    <td>${item.name}</td>
                    <td>${item.price} €</td>
                    <td>${item.qty}</td>
                    <td>${badge}</td>
                </tr>`;

            if (!isOutOfStock) {
                selectProd.innerHTML += `<option value="${index}">${item.name} (Dispo : ${item.qty})</option>`;
            }
        });
    }

    function addToInvoice() {
        const index = document.getElementById('invoiceProductSelect').value;
        const qty = parseInt(document.getElementById('invoiceQty').value);

        if (index === "" || isNaN(qty) || qty <= 0) {
            alert("Sélectionnez un produit valide et une quantité supérieure à 0.");
            return;
        }

        const selectedProduct = stock[index];
        if (qty > selectedProduct.qty) {
            alert("Quantité demandée supérieure au stock disponible !");
            return;
        }

        currentInvoiceItems.push({
            index: index,
            name: selectedProduct.name,
            qty: qty,
            price: selectedProduct.price,
            total: qty * selectedProduct.price
        });

        updateInvoiceUI();
    }

    function updateInvoiceUI() {
        const invoiceBody = document.getElementById('invoiceTableBody');
        invoiceBody.innerHTML = '';
        let grandTotal = 0;

        currentInvoiceItems.forEach(item => {
            invoiceBody.innerHTML += `
                <tr>
                    <td>${item.name}</td>
                    <td>${item.qty}</td>
                    <td>${item.price} €</td>
                    <td>${item.total} €</td>
                </tr>`;
            grandTotal += item.total;
        });

        document.getElementById('invoiceTotal').innerText = grandTotal;
    }

    function openA4Invoice() {
        if (currentInvoiceItems.length === 0) {
            alert("Impossible de générer une facture vide.");
            return;
        }

        const client = document.getElementById('clientName').value || "Client Divers";
        document.getElementById('a4Client').innerText = client;
        document.getElementById('a4Date').innerText = new Date().toLocaleDateString();

        const a4TableBody = document.getElementById('a4TableBody');
        a4TableBody.innerHTML = '';
        let grandTotal = 0;

        currentInvoiceItems.forEach(item => {
            a4TableBody.innerHTML += `
                <tr>
                    <td>${item.name}</td>
                    <td>${item.qty}</td>
                    <td>${item.price} €</td>
                    <td>${item.total} €</td>
                </tr>`;
            grandTotal += item.total;
        });

        document.getElementById('a4Total').innerText = grandTotal;
        document.getElementById('invoiceA4Modal').classList.remove('hidden');
    }

    function closeA4Invoice() {
        currentInvoiceItems.forEach(item => {
            stock[item.index].qty -= item.qty;
        });

        currentInvoiceItems = [];
        document.getElementById('invoiceTableBody').innerHTML = '';
        document.getElementById('invoiceTotal').innerText = '0';
        document.getElementById('clientName').value = '';
        document.getElementById('invoiceA4Modal').classList.add('hidden');
        
        updateUI();
        alert("Facture validée et stock mis à jour avec succès !");
    }
</script>

</body>
</html>