<?php
require_once 'connexion/auth.php'; 

if (!(function_exists('isLogged') && isLogged() && (hasRole('Administrateur') || hasRole('Maire') || hasRole('Adjoint') || hasRole('Secretaire') || hasRole('Conseiller')))) {
    header('Location: index.php');
    exit();
}

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: services.php'); 
    exit();
}

$materiel_id = (int)$_GET['id'];

$stmt = $pdo->prepare("SELECT * FROM materiel_pret WHERE id = ?");
$stmt->execute([$materiel_id]);
$materiel = $stmt->fetch();

if (!$materiel) { header('Location: services.php'); exit(); }

if (isset($_POST['restitution_ok'])) {
    $pret_id = (int)$_POST['pret_id'];
    $stmt = $pdo->prepare("UPDATE prets_materiel SET statut = 'Rendu', date_restitution = NOW(), notes_restitution = 'Restitué en totalité et en bon état' WHERE id = ?");
    $stmt->execute([$pret_id]);
    $message_succes = "Le matériel a été réintégré au stock avec succès.";
}

if (isset($_POST['valider_partielle'])) {
    $pret_id = (int)$_POST['partielle_pret_id'];
    $qte_restituee = (int)$_POST['qte_restituee'];
    $note = trim($_POST['note_partielle']);

    $stmt_pret = $pdo->prepare("SELECT quantite FROM prets_materiel WHERE id = ?");
    $stmt_pret->execute([$pret_id]);
    $pret_info = $stmt_pret->fetch();

    if ($pret_info) {
        $qte_initiale = $pret_info['quantite'];
        $perte = $qte_initiale - $qte_restituee; 
        
        $statut = ($perte > 0) ? 'Restit. Partielle' : 'Rendu (Avec note)';
        $note_finale = "Rendu : $qte_restituee sur $qte_initiale. " . $note;

        $stmt_update = $pdo->prepare("UPDATE prets_materiel SET statut = ?, date_restitution = NOW(), notes_restitution = ? WHERE id = ?");
        $stmt_update->execute([$statut, $note_finale, $pret_id]);

        if ($perte > 0) {
            $stmt_stock = $pdo->prepare("UPDATE materiel_pret SET quantite_totale = GREATEST(0, quantite_totale - ?) WHERE id = ?");
            $stmt_stock->execute([$perte, $materiel_id]);
            $materiel['quantite_totale'] -= $perte; 
            $message_succes = "Le retour est enregistré. Le stock total de la mairie a été réduit de $perte unité(s).";
        } else {
            $message_succes = "Le retour est enregistré.";
        }
    }
}

$stmt_stock = $pdo->prepare("SELECT SUM(quantite) FROM prets_materiel WHERE materiel_id = ? AND statut = 'En cours'");
$stmt_stock->execute([$materiel_id]);
$total_prete = (int)$stmt_stock->fetchColumn();
$stock_disponible = $materiel['quantite_totale'] - $total_prete;

if (isset($_POST['valider_pret'])) {
    $quantite = (int)$_POST['quantite'];
    $est_non_inscrit = isset($_POST['non_inscrit']) ? 1 : 0;
    if ($quantite > 0 && $quantite <= $stock_disponible) {
        if ($est_non_inscrit) {
            $stmt_insert = $pdo->prepare("INSERT INTO prets_materiel (materiel_id, nom_externe, prenom_externe, adresse_externe, telephone_externe, mail_externe, quantite) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt_insert->execute([$materiel_id, trim($_POST['nom']), trim($_POST['prenom']), trim($_POST['adresse']), trim($_POST['telephone']), trim($_POST['mail']), $quantite]);
        } else {
            $utilisateur_id = (int)$_POST['utilisateur_id'];
            $stmt_insert = $pdo->prepare("INSERT INTO prets_materiel (materiel_id, utilisateur_id, quantite) VALUES (?, ?, ?)");
            $stmt_insert->execute([$materiel_id, $utilisateur_id, $quantite]);
        }
        $message_succes = "Le prêt a bien été enregistré.";
        $stock_disponible -= $quantite; 
    }
}

// AJOUT DE PRENOM ICI
$utilisateurs = $pdo->query("SELECT id, nom, prenom FROM utilisateurs ORDER BY nom ASC, prenom ASC")->fetchAll();

$prets_en_cours = $pdo->prepare("SELECT p.*, u.nom, u.prenom FROM prets_materiel p LEFT JOIN utilisateurs u ON p.utilisateur_id = u.id WHERE p.materiel_id = ? AND p.statut = 'En cours' ORDER BY p.date_pret DESC");
$prets_en_cours->execute([$materiel_id]);
$liste_prets = $prets_en_cours->fetchAll();

$historique = $pdo->prepare("SELECT p.*, u.nom, u.prenom FROM prets_materiel p LEFT JOIN utilisateurs u ON p.utilisateur_id = u.id WHERE p.materiel_id = ? AND p.statut != 'En cours' ORDER BY p.date_restitution DESC LIMIT 50");
$historique->execute([$materiel_id]);
$liste_historique = $historique->fetchAll();

?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion : <?= htmlspecialchars($materiel['nom']) ?></title>
    <link rel="stylesheet" href="css/global.css">
    <style>
        .content-area { background-color: #ffffff; border-radius: 10px; padding: 20px; width: 100%; min-height: 500px; box-sizing: border-box; box-shadow: 0 2px 5px rgba(0,0,0,0.05); border: 1px solid #e0e0e0; }
        .entete-pret { display: flex; flex-wrap: wrap; align-items: stretch; gap: 15px; border-bottom: 2px solid #f0f2f5; padding-bottom: 15px; margin-bottom: 20px; }
        .entete-pret img { width: 120px; height: 120px; object-fit: contain; background-color: #ffffff; border-radius: 8px; border: 1px solid #e0e0e0; padding: 5px; box-sizing: border-box; }
        .infos-stock { flex: 1; min-width: 200px; }
        .infos-stock h1 { margin: 0 0 5px 0; font-size: 1.6em; color: #333; }
        .conseils-box { flex: 1.5; min-width: 250px; background-color: #fffde7; border-left: 4px solid #fbc02d; padding: 12px; border-radius: 8px; color: #555; font-size: 0.9em; }
        .conseils-box h3 { margin-top: 0; margin-bottom: 5px; font-size: 1.05em; }
        .badge-stock { display: inline-block; padding: 6px 12px; border-radius: 20px; font-weight: bold; font-size: 1em; }
        .stock-ok { background-color: #e1ede0; color: #28a745; border: 1px solid #c8e6c9; }
        .stock-vide { background-color: #fdeaea; color: #dc3545; border: 1px solid #f5c6cb; }
        .bloc-formulaire { background-color: #fdfdfd; border: 1px solid #eee; padding: 20px; border-radius: 10px; margin-bottom: 30px; }
        .form-control { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 6px; box-sizing: border-box; font-size: 0.95em; }
        .table-prets { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 0.9em; }
        .table-prets th, .table-prets td { padding: 10px; text-align: left; border-bottom: 1px solid #eee; }
        .table-prets th { background-color: #f8f9fa; color: #555; }
        .btn-action { padding: 5px 10px; border-radius: 4px; border: none; cursor: pointer; font-weight: bold; font-size: 0.85em; display: inline-block; }
        .btn-ok { background-color: #28a745; color: white; }
        .btn-warning { background-color: #e67e22; color: white; }
        .btn-link { color: #0066cc; text-decoration: underline; font-weight: bold; }
        .status-badge { padding: 3px 8px; border-radius: 10px; font-size: 0.8em; font-weight: bold; }
        .status-rendu { background: #d4edda; color: #155724; }
        .status-partielle { background: #fff3cd; color: #856404; }
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); align-items: center; justify-content: center; }
        .modal-content { background: white; padding: 20px; border-radius: 10px; width: 400px; }
    </style>
</head>
<body>

<div class="site-container">
    <img src="images/banniere.png" alt="Bannière" class="banner-img">
    <nav><?php include 'includes/menu.php'; ?></nav>

    <main class="main-wrapper">
        <div class="content-area">
            <a href="services.php" style="text-decoration: none; color: #666; font-weight: bold; display: inline-block; margin-bottom: 15px;">← Retour aux services</a>

            <?php if (isset($message_succes)): ?><div style="background:#d4edda; color:#155724; padding:12px; border-radius:6px; margin-bottom:15px;"><?= $message_succes ?></div><?php endif; ?>
            <?php if (isset($message_erreur)): ?><div style="background:#f8d7da; color:#721c24; padding:12px; border-radius:6px; margin-bottom:15px;"><?= $message_erreur ?></div><?php endif; ?>

            <div class="entete-pret">
                <img src="images/pret/<?= htmlspecialchars($materiel['image']) ?>" onerror="this.src='images/placeholder.jpg'">
                <div class="infos-stock">
                    <h1><?= htmlspecialchars($materiel['nom']) ?></h1>
                    <p style="margin-bottom: 10px;">Stock total (Mairie) : <strong><?= $materiel['quantite_totale'] ?></strong></p>
                    <span class="badge-stock <?= ($stock_disponible > 0) ? 'stock-ok' : 'stock-vide' ?>">Dispo : <?= $stock_disponible ?></span>
                </div>
                <?php if (!empty($materiel['conseils'])): ?>
                <div class="conseils-box">
                    <h3>💡 Conseils d'utilisation</h3>
                    <p style="margin: 0;"><?= nl2br(htmlspecialchars($materiel['conseils'])) ?></p>
                </div>
                <?php endif; ?>
            </div>

            <?php if ($stock_disponible > 0): ?>
            <div class="bloc-formulaire">
                <h3 style="margin-top: 0;">Enregistrer un nouveau prêt</h3>
                <form method="POST">
                    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 15px; align-items: end;">
                        <div>
                            <label style="font-size: 0.9em; font-weight: bold;">Quantité :</label>
                            <input type="number" name="quantite" class="form-control" min="1" max="<?= $stock_disponible ?>" value="1" required>
                        </div>
                        <div id="bloc_user">
                            <label style="font-size: 0.9em; font-weight: bold;">Habitant inscrit :</label>
                            <select name="utilisateur_id" id="utilisateur_id" class="form-control">
                                <option value="">-- Sélectionner --</option>
                                <?php foreach ($utilisateurs as $u): ?>
                                    <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['nom'] . ' ' . $u['prenom']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div style="margin-top: 10px;">
                        <label style="font-size: 0.9em;"><input type="checkbox" id="non_inscrit" name="non_inscrit" onchange="toggleForm()"> Emprunteur non inscrit</label>
                    </div>
                    
                    <div id="form_manuel" style="display:none; margin-top: 10px; border-top: 1px dashed #ccc; padding-top: 10px;">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px;">
                            <input type="text" id="nom" name="nom" placeholder="Nom" class="form-control">
                            <input type="text" id="prenom" name="prenom" placeholder="Prénom" class="form-control">
                        </div>
                        <input type="text" name="adresse" placeholder="Adresse postale" class="form-control" style="margin-bottom: 10px;">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px;">
                            <input type="text" name="telephone" placeholder="Téléphone" class="form-control">
                            <input type="email" name="mail" placeholder="Email" class="form-control">
                        </div>
                    </div>

                    <button type="submit" name="valider_pret" class="btn-action btn-ok" style="margin-top: 10px; width: 100%; padding: 10px; font-size: 1em;">Valider le prêt</button>
                </form>
            </div>
            <?php endif; ?>

            <h2 style="font-size: 1.3em;">Prêts en cours</h2>
            <table class="table-prets">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Emprunteur</th>
                        <th>Qté</th>
                        <th>Actions (Restitution)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($liste_prets as $p): ?>
                    <tr>
                        <td><?= date('d/m/y', strtotime($p['date_pret'])) ?></td>
                        <td>
                            <?php if ($p['utilisateur_id']): ?>
                                <a href="fiche_utilisateur.php?id=<?= $p['utilisateur_id'] ?>" class="btn-link" title="Voir la fiche"><?= htmlspecialchars($p['prenom'] . ' ' . $p['nom']) ?></a>
                            <?php else: ?>
                                <?= htmlspecialchars($p['prenom_externe'] . ' ' . $p['nom_externe']) ?> (Ext.)
                            <?php endif; ?>
                        </td>
                        <td><strong><?= $p['quantite'] ?></strong></td>
                        <td>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="pret_id" value="<?= $p['id'] ?>">
                                <button type="submit" name="restitution_ok" class="btn-action btn-ok" onclick="return confirm('Confirmer la restitution totale ?');">Total</button>
                            </form>
                            <button onclick="openPartielle(<?= $p['id'] ?>, <?= $p['quantite'] ?>)" class="btn-action btn-warning">Partielle</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <h2 style="margin-top: 40px; color: #888; font-size: 1.2em;">Historique des restitutions</h2>
            <table class="table-prets" style="opacity: 0.8;">
                <thead><tr><th>Dates</th><th>Emprunteur</th><th>État / Notes</th></tr></thead>
                <tbody>
                    <?php foreach ($liste_historique as $h): ?>
                    <tr>
                        <td style="font-size: 0.8em;">Du <?= date('d/m', strtotime($h['date_pret'])) ?><br>Au <?= date('d/m', strtotime($h['date_restitution'])) ?></td>
                        <td>
                            <?php if ($h['utilisateur_id']): ?>
                                <a href="fiche_utilisateur.php?id=<?= $h['utilisateur_id'] ?>" class="btn-link"><?= htmlspecialchars($h['prenom'] . ' ' . $h['nom']) ?></a>
                            <?php else: ?>
                                <?= htmlspecialchars($h['prenom_externe'] . ' ' . $h['nom_externe']) ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="status-badge <?= ($h['statut'] == 'Rendu') ? 'status-rendu' : 'status-partielle' ?>"><?= $h['statut'] ?></span><br>
                            <small><?= htmlspecialchars($h['notes_restitution']) ?></small>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </main>
</div>

<div id="modalPartielle" class="modal">
    <div class="modal-content">
        <h3 style="margin-top:0; color:#e67e22; font-size: 1.2em;">Restitution partielle ou avec incident</h3>
        <p style="font-size: 0.85em; color: #666; margin-bottom: 15px;">Indiquez le nombre d'objets rendus. Les objets manquants seront automatiquement déduits du stock.</p>
        
        <form method="POST">
            <input type="hidden" name="partielle_pret_id" id="partielle_pret_id">
            
            <div style="margin-bottom: 10px;">
                <label style="font-weight: bold; font-size: 0.9em;">Quantité ramenée (sur <span id="max_qte_text"></span>) :</label>
                <input type="number" name="qte_restituee" id="qte_restituee" class="form-control" min="0" required>
            </div>
            
            <div style="margin-bottom: 15px;">
                <label style="font-weight: bold; font-size: 0.9em;">Note explicative (obligatoire) :</label>
                <textarea name="note_partielle" class="form-control" rows="3" placeholder="Ex: 1 pièce perdue..." required></textarea>
            </div>
            
            <div style="display:flex; gap:10px;">
                <button type="submit" name="valider_partielle" class="btn-action btn-warning" style="flex:1; padding: 8px;">Valider le retour</button>
                <button type="button" onclick="document.getElementById('modalPartielle').style.display='none'" class="btn-action" style="background:#eee; flex:1; padding: 8px; color: #333;">Annuler</button>
            </div>
        </form>
    </div>
</div>

<script>
    function toggleForm() {
        var isChecked = document.getElementById('non_inscrit').checked;
        document.getElementById('bloc_user').style.display = isChecked ? 'none' : 'block';
        document.getElementById('form_manuel').style.display = isChecked ? 'block' : 'none';
        
        document.getElementById('utilisateur_id').required = !isChecked;
        document.getElementById('nom').required = isChecked;
        document.getElementById('prenom').required = isChecked;
    }

    function openPartielle(id, maxQte) {
        document.getElementById('partielle_pret_id').value = id;
        document.getElementById('qte_restituee').max = maxQte;
        document.getElementById('qte_restituee').value = maxQte - 1; 
        document.getElementById('max_qte_text').innerText = maxQte;
        document.getElementById('modalPartielle').style.display = 'flex';
    }
</script>

</body>
</html>