<?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();
}

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

$stmt = $pdo->prepare("SELECT * FROM utilisateurs WHERE id = ?");
$stmt->execute([$utilisateur_id]);
$user = $stmt->fetch();

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

$stmt_prets = $pdo->prepare("
    SELECT p.*, m.nom as nom_materiel 
    FROM prets_materiel p 
    JOIN materiel_pret m ON p.materiel_id = m.id 
    WHERE p.utilisateur_id = ? 
    ORDER BY p.statut = 'En cours' DESC, p.date_pret DESC
");
$stmt_prets->execute([$utilisateur_id]);
$prets = $stmt_prets->fetchAll();

$nb_partiel = 0;
foreach ($prets as $p) {
    if ($p['statut'] == 'Restit. Partielle') {
        $nb_partiel++;
    }
}

// Variables pour le nom complet
$prenom_affiche = isset($user['prenom']) ? htmlspecialchars($user['prenom']) : '';
$nom_affiche = htmlspecialchars($user['nom']);
$nom_complet = trim($prenom_affiche . ' ' . $nom_affiche);
$lettre_avatar = strtoupper(substr($prenom_affiche ? $prenom_affiche : $nom_affiche, 0, 1));
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fiche Habitant : <?= $nom_complet ?></title>
    <link rel="stylesheet" href="css/global.css">
    <style>
        .content-area { background-color: #ffffff; border-radius: 10px; padding: 30px; width: 100%; min-height: 500px; box-sizing: border-box; box-shadow: 0 2px 5px rgba(0,0,0,0.05); border: 1px solid #e0e0e0; }
        .user-card { background-color: #f8f9fa; border: 1px solid #e0e0e0; border-radius: 10px; padding: 20px; margin-bottom: 30px; display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start; }
        .user-avatar { width: 80px; height: 80px; background-color: var(--nature-vert, #28a745); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 2em; font-weight: bold; }
        .user-details { flex: 1; min-width: 250px; }
        .user-details h1 { margin: 0 0 10px 0; color: #333; }
        .user-details p { margin: 5px 0; color: #555; }
        .alert-box { background-color: #fff3cd; color: #856404; padding: 15px; border-radius: 8px; border: 1px solid #ffeeba; text-align: center; font-weight: bold; }
        .table-prets { width: 100%; border-collapse: collapse; margin-top: 15px; }
        .table-prets th, .table-prets td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
        .table-prets th { background-color: #f8f9fa; color: #555; }
        .status-badge { padding: 4px 10px; border-radius: 15px; font-size: 0.8em; font-weight: bold; }
        .s-cours { background: #cce5ff; color: #004085; }
        .s-rendu { background: #d4edda; color: #155724; }
        .s-partielle { background: #f8d7da; color: #721c24; }
        .btn-retour { background-color: #6c757d; color: white; text-decoration: none; padding: 10px 20px; border-radius: 8px; font-weight: bold; display: inline-block; margin-bottom: 20px; }
    </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="javascript:history.back()" class="btn-retour">← Retour</a>

            <div class="user-card">
                <div class="user-avatar">
                    <?= $lettre_avatar ?>
                </div>
                <div class="user-details">
                    <h1><?= $nom_complet ?></h1>
                    <?php if (isset($user['adresse'])): ?><p>📍 <?= htmlspecialchars($user['adresse']) ?></p><?php endif; ?>
                    <?php if (isset($user['email'])): ?><p>✉️ <?= htmlspecialchars($user['email']) ?></p><?php endif; ?>
                    <p>📅 Inscrit depuis le : <?= date('d/m/Y', strtotime($user['date_inscription'])) ?></p>
                </div>
                
                <?php if ($nb_partiel > 0): ?>
                <div class="alert-box">
                    ⚠️ Attention : Cet habitant a eu<br>
                    <span style="font-size: 1.5em;"><?= $nb_partiel ?></span><br>
                    restitution(s) avec incident.
                </div>
                <?php endif; ?>
            </div>

            <h2>Historique des prêts</h2>
            
            <?php if (count($prets) > 0): ?>
            <table class="table-prets">
                <thead>
                    <tr>
                        <th>Matériel</th>
                        <th>Date de prêt</th>
                        <th>Statut</th>
                        <th>Notes de retour</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($prets as $p): ?>
                        <?php 
                        $class = '';
                        if ($p['statut'] == 'En cours') $class = 's-cours';
                        elseif ($p['statut'] == 'Rendu') $class = 's-rendu';
                        else $class = 's-partielle';
                        ?>
                        <tr>
                            <td>
                                <strong><?= htmlspecialchars($p['nom_materiel']) ?></strong><br>
                                <small>Quantité : <?= $p['quantite'] ?></small>
                            </td>
                            <td><?= date('d/m/Y', strtotime($p['date_pret'])) ?></td>
                            <td><span class="status-badge <?= $class ?>"><?= $p['statut'] ?></span></td>
                            <td>
                                <?php if ($p['date_restitution']): ?>
                                    Rendu le <?= date('d/m/y', strtotime($p['date_restitution'])) ?><br>
                                    <small><?= htmlspecialchars($p['notes_restitution']) ?></small>
                                <?php else: ?>
                                    <span style="color: #aaa; font-style: italic;">En attente de retour...</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
                <p style="color: #777;">Cet habitant n'a jamais emprunté de matériel.</p>
            <?php endif; ?>

        </div>
    </main>
</div>

</body>
</html>