<?php
// On récupère les données
$materiels = $pdo->query("
    SELECT m.*, 
    (SELECT COALESCE(SUM(quantite), 0) FROM prets_materiel WHERE materiel_id = m.id AND statut = 'En cours') as total_emprunte
    FROM materiel_pret m 
    ORDER BY m.nom ASC
")->fetchAll();
?>

<div class="header-section">
    <h1 style="margin: 0; color: #333; font-size: 1.5em;">Matériel disponible au prêt</h1>
    <?php if ($est_privilegie): ?>
        <button class="btn-ajouter" onclick="document.getElementById('addMaterielModal').style.display='flex'">+ Nouveau matériel</button>
    <?php endif; ?>
</div>

<?php if (!$est_privilegie): ?>
    <div class="msg-avertissement">
        ℹ️ Pour tout besoin de prêt, merci de vous rapprocher de la mairie.
    </div>
<?php endif; ?>

<div class="grille-cartes">
    <?php foreach ($materiels as $mat): ?>
    <?php 
    $stock_dispo = $mat['quantite_totale'] - $mat['total_emprunte'];
    $badge_class = ($stock_dispo > 0) ? 'bg-vert' : 'bg-rouge'; 
    ?>
    
    <div class="carte">
        <?php if ($est_privilegie): ?>
            <a href="gestion_pret.php?id=<?= $mat['id'] ?>" class="carte-lien">
        <?php else: ?>
            <div class="carte-lien carte-lien-inactif">
        <?php endif; ?>

                <img src="images/pret/<?= htmlspecialchars($mat['image']) ?>" alt="<?= htmlspecialchars($mat['nom']) ?>" onerror="this.src='images/placeholder.jpg'">
                <div class="carte-contenu">
                    <h3><?= htmlspecialchars($mat['nom']) ?></h3>
                    <span class="badge <?= $badge_class ?>">Dispo : <?= $stock_dispo ?> / <?= $mat['quantite_totale'] ?></span>
                </div>
        
        <?php if ($est_privilegie): ?>
            </a>
        <?php else: ?>
            </div>
        <?php endif; ?>

        <?php if ($est_privilegie): ?>
        <?php $conseils_js = htmlspecialchars(addslashes(str_replace(["\r", "\n"], ["", "\\n"], $mat['conseils'] ?? ''))); ?>
        <div class="carte-actions">
            <button onclick="openEditModal(<?= $mat['id'] ?>, '<?= htmlspecialchars(addslashes($mat['nom'])) ?>', <?= $mat['quantite_totale'] ?>, '<?= $conseils_js ?>')" style="padding: 6px 12px; background: #607d8b; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 0.85em;">Modifier</button>
            
            <form method="POST" onsubmit="return confirm('Supprimer ce matériel ?');" style="margin: 0;">
                <input type="hidden" name="delete_materiel_id" value="<?= $mat['id'] ?>">
                <button type="submit" style="padding: 6px 12px; background: #e74c3c; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 0.85em;">Supprimer</button>
            </form>
        </div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
    
    <?php if (empty($materiels)): ?>
        <p style="grid-column: 1 / -1; text-align: center; color: #777; padding: 20px;">Aucun matériel n'est encore enregistré.</p>
    <?php endif; ?>
</div>

<?php if ($est_privilegie): ?>
<div id="addMaterielModal" class="modal">
    <div class="modal-content">
        <span class="close-btn" onclick="document.getElementById('addMaterielModal').style.display='none'">&times;</span>
        <h2>Ajouter un matériel</h2>
        <form method="POST" enctype="multipart/form-data">
            <div class="form-grid-2">
                <div class="form-group"><label>Nom :</label><input type="text" name="nom_materiel" required></div>
                <div class="form-group"><label>Qté totale :</label><input type="number" name="quantite_materiel" min="1" value="1" required></div>
            </div>
            <div class="form-group">
                <label>Conseils d'utilisation :</label>
                <textarea name="conseils_materiel" rows="4"></textarea>
            </div>
            <div class="form-group"><label>Image (Optionnel) :</label><input type="file" name="image_materiel" accept="image/png, image/jpeg, image/jpg, image/webp"></div>
            <button type="submit" name="add_materiel" class="btn-submit">Créer la fiche</button>
        </form>
    </div>
</div>

<div id="editMaterielModal" class="modal">
    <div class="modal-content">
        <span class="close-btn" onclick="document.getElementById('editMaterielModal').style.display='none'">&times;</span>
        <h2>Modifier le matériel</h2>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" id="edit_materiel_id" name="edit_materiel_id">
            <div class="form-grid-2">
                <div class="form-group"><label>Nom :</label><input type="text" id="edit_nom_materiel" name="edit_nom_materiel" required></div>
                <div class="form-group"><label>Qté totale :</label><input type="number" id="edit_quantite_materiel" name="edit_quantite_materiel" min="1" required></div>
            </div>
            <div class="form-group">
                <label>Conseils d'utilisation :</label>
                <textarea id="edit_conseils_materiel" name="edit_conseils_materiel" rows="4"></textarea>
            </div>
            <div class="form-group"><label>Remplacer l'image :</label><input type="file" name="edit_image_materiel" accept="image/png, image/jpeg, image/jpg, image/webp"></div>
            <button type="submit" class="btn-submit">Enregistrer</button>
        </form>
    </div>
</div>

<script>
    function openEditModal(id, nom, quantite, conseils) {
        document.getElementById('edit_materiel_id').value = id;
        document.getElementById('edit_nom_materiel').value = nom;
        document.getElementById('edit_quantite_materiel').value = quantite;
        document.getElementById('edit_conseils_materiel').value = conseils.replace(/\\n/g, '\n');
        document.getElementById('editMaterielModal').style.display = 'flex';
    }
</script>
<?php endif; ?>