<?php
/**
 * Détail d'un compte utilisateur — réservé au super admin
 * Affiche : infos, permissions effectives, stats, liens (élève/enfants)
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

checkRole(['super_admin', 'school_admin']);
requirePermission('users', 'view');

try { $pdo->exec("ALTER TABLE users ADD COLUMN last_login DATETIME DEFAULT NULL AFTER created_at"); } catch (PDOException $e) {}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) { flashMessage('error', 'Identifiant manquant.'); header('Location: users.php'); exit; }

// Charger l'utilisateur
$stmt = $pdo->prepare("
    SELECT u.*, s.name AS school_name
    FROM users u LEFT JOIN schools s ON u.school_id = s.id
    WHERE u.id = ?
");
$stmt->execute([$id]); $user = $stmt->fetch();
if (!$user) { flashMessage('error', 'Utilisateur introuvable.'); header('Location: users.php'); exit; }

// Infos enseignant lié
$teacherInfo = null;
if ($user['role'] === 'teacher') {
    $st = $pdo->prepare("SELECT diploma, subject FROM teachers WHERE user_id=? OR (email=? AND email IS NOT NULL) LIMIT 1");
    $st->execute([$id, $user['email'] ?? '']); $teacherInfo = $st->fetch();
}

// Vérifier les droits de gestion
if (!canManageUser($user) && (int)$_SESSION['user_id'] !== $id) {
    header('Location: access_denied.php?page=users&action=view'); exit;
}

// Permissions effectives du compte consulté
$effectivePerms = [];
if ($user['role'] === 'super_admin') {
    // Super admin a tout
    foreach (['schools','classes','students','teachers','subjects','payments','users','permissions',
              'portal_dashboard','portal_grades','portal_payments','portal_profile','portal_children'] as $pg) {
        $effectivePerms[$pg] = ['can_view'=>1,'can_create'=>1,'can_edit'=>1,'can_delete'=>1];
    }
} else {
    $rows = $pdo->prepare("SELECT page, can_view, can_create, can_edit, can_delete FROM role_permissions WHERE role=? ORDER BY page");
    $rows->execute([$user['role']]);
    foreach ($rows->fetchAll() as $row) { $effectivePerms[$row['page']] = $row; }
}

// Élève lié (si student)
$linkedStudent = null;
if ($user['role'] === 'student') {
    $stmt = $pdo->prepare("SELECT s.*, c.name AS class_name, sc.name AS school_name
        FROM students s LEFT JOIN classes c ON s.class_id=c.id LEFT JOIN schools sc ON s.school_id=sc.id
        WHERE s.user_id=?");
    $stmt->execute([$id]); $linkedStudent = $stmt->fetch();
}

// Enfants liés (si parent)
$children = [];
if ($user['role'] === 'parent') {
    $stmt = $pdo->prepare("SELECT s.*, c.name AS class_name, sc.name AS school_name
        FROM parent_students ps JOIN students s ON ps.student_id=s.id
        LEFT JOIN classes c ON s.class_id=c.id LEFT JOIN schools sc ON s.school_id=sc.id
        WHERE ps.user_id=? ORDER BY s.last_name, s.first_name");
    $stmt->execute([$id]); $children = $stmt->fetchAll();
}

// Stats notes (si student ou parent)
$gradeStats = null;
$studentIds = [];
if ($user['role'] === 'student' && $linkedStudent) {
    $studentIds = [$linkedStudent['id']];
} elseif ($user['role'] === 'parent' && !empty($children)) {
    $studentIds = array_column($children, 'id');
}
if (!empty($studentIds)) {
    $in = implode(',', array_fill(0, count($studentIds), '?'));
    $stmt = $pdo->prepare("SELECT COUNT(*) AS nb_grades, AVG((COALESCE(note_interro,0)+COALESCE(note_devoir,0)+COALESCE(note_compo,0))/3) AS avg_score FROM grades WHERE student_id IN ($in)");
    $stmt->execute($studentIds); $gradeStats = $stmt->fetch();
    $stmt = $pdo->prepare("SELECT COUNT(*) AS nb_payments, COALESCE(SUM(amount),0) AS total_paid FROM payments WHERE student_id IN ($in)");
    $stmt->execute($studentIds); $payStats = $stmt->fetch();
}

// Labels des pages
$pageLabels = [
    'schools'          => ['label'=>'Écoles',          'icon'=>'fa-school',         'group'=>'Administration'],
    'classes'          => ['label'=>'Classes',          'icon'=>'fa-users',          'group'=>'Administration'],
    'students'         => ['label'=>'Élèves',           'icon'=>'fa-user-graduate',  'group'=>'Administration'],
    'teachers'         => ['label'=>'Enseignants',      'icon'=>'fa-chalkboard-teacher','group'=>'Administration'],
    'subjects'         => ['label'=>'Matières',         'icon'=>'fa-book',           'group'=>'Administration'],
    'grades'           => ['label'=>'Notes',            'icon'=>'fa-star-half-alt',  'group'=>'Administration'],
    'payments'         => ['label'=>'Paiements',        'icon'=>'fa-money-bill-wave','group'=>'Administration'],
    'users'            => ['label'=>'Utilisateurs',     'icon'=>'fa-users-cog',      'group'=>'Administration'],
    'permissions'      => ['label'=>'Permissions',      'icon'=>'fa-shield-alt',     'group'=>'Administration'],
    'portal_dashboard' => ['label'=>'Dashboard portail','icon'=>'fa-tachometer-alt', 'group'=>'Portail'],
    'portal_grades'    => ['label'=>'Notes portail',    'icon'=>'fa-star-half-alt',  'group'=>'Portail'],
    'portal_payments'  => ['label'=>'Paiements portail','icon'=>'fa-receipt',        'group'=>'Portail'],
    'portal_profile'   => ['label'=>'Profil portail',   'icon'=>'fa-user-circle',    'group'=>'Portail'],
    'portal_children'  => ['label'=>'Enfants portail',  'icon'=>'fa-child',          'group'=>'Portail'],
];
$actionLabels = ['can_view'=>'Voir','can_create'=>'Créer','can_edit'=>'Modifier','can_delete'=>'Supprimer'];
$actionIcons  = ['can_view'=>'fa-eye','can_create'=>'fa-plus','can_edit'=>'fa-edit','can_delete'=>'fa-trash'];
$actionColors = ['can_view'=>'#2b6cb0','can_create'=>'#276749','can_edit'=>'#975a16','can_delete'=>'#c53030'];
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Détail compte — <?= e($user['name']) ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">

        <!-- En-tête -->
        <div class="header-bar">
            <div style="display:flex;align-items:center;gap:1rem;">
                <a href="users.php" class="btn-action btn-view"><i class="fas fa-arrow-left"></i></a>
                <h1><i class="fas fa-id-card"></i> Détail du compte</h1>
            </div>
            <div style="display:flex;gap:.5rem;">
                <?php if (canManageUser($user)): ?>
                <a href="users.php?action=edit&id=<?= $id ?>" class="btn-action btn-edit">
                    <i class="fas fa-edit"></i> Modifier
                </a>
                <?php if ($id !== (int)$_SESSION['user_id']): ?>
                <form method="POST" action="users.php?action=toggle_active&id=<?= $id ?>" style="display:inline">
                    <?= csrfField() ?>
                    <button type="submit" class="btn-action <?= $user['active'] ? 'btn-toggle-off' : 'btn-toggle-on' ?>">
                        <i class="fas fa-<?= $user['active'] ? 'ban' : 'check-circle' ?>"></i>
                        <?= $user['active'] ? 'Désactiver' : 'Activer' ?>
                    </button>
                </form>
                <?php if (isSuperAdmin()): ?>
                <form method="POST" action="users.php?action=delete&id=<?= $id ?>" style="display:inline"
                      onsubmit="return confirm('Supprimer définitivement ce compte ?')">
                    <?= csrfField() ?>
                    <button type="submit" class="btn-action btn-delete">
                        <i class="fas fa-trash"></i> Supprimer
                    </button>
                </form>
                <?php endif; ?>
                <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <?= showFlash() ?>

        <div class="detail-layout">

            <!-- Colonne gauche : profil -->
            <div class="detail-col-left">

                <!-- Carte identité -->
                <div class="card detail-profile-card">
                    <div class="detail-avatar <?= $user['active'] ? '' : 'detail-avatar-inactive' ?>">
                        <?= userPhotoImg($user['photo'] ?? null, $user['name']) ?>
                    </div>
                    <div class="detail-name"><?= e($user['name']) ?></div>
                    <div class="detail-email"><?= e($user['email']) ?></div>
                    <span class="badge <?= getRoleBadgeClass($user['role']) ?>" style="font-size:.9rem;margin-top:.5rem;">
                        <?= getRoleLabel($user['role']) ?>
                    </span>
                    <?php if ($user['active']): ?>
                    <span class="status-badge status-active" style="margin-top:.5rem;">
                        <i class="fas fa-circle" style="font-size:.5rem;"></i> Compte actif
                    </span>
                    <?php else: ?>
                    <span class="status-badge status-inactive" style="margin-top:.5rem;">
                        <i class="fas fa-ban"></i> Compte désactivé
                    </span>
                    <?php endif; ?>
                </div>

                <!-- Informations -->
                <div class="card" style="margin-top:1rem;">
                    <div class="card-header"><span class="card-title"><i class="fas fa-info-circle"></i> Informations</span></div>
                    <table class="detail-info-table">
                        <tr><td><i class="fas fa-hashtag"></i> ID</td><td><code>#<?= $user['id'] ?></code></td></tr>
                        <tr><td><i class="fas fa-school"></i> École</td><td><?= e($user['school_name'] ?? '— Global —') ?></td></tr>
                        <tr><td><i class="fas fa-calendar-plus"></i> Créé le</td><td><?= formatDate($user['created_at']) ?></td></tr>
                        <tr>
                            <td><i class="fas fa-clock"></i> Dernière connexion</td>
                            <td>
                                <?php if (!empty($user['last_login'])): ?>
                                <span title="<?= e($user['last_login']) ?>">
                                    <?= formatDate($user['last_login']) ?>
                                    <small style="color:#a0aec0;"><?= date('H:i', strtotime($user['last_login'])) ?></small>
                                </span>
                                <?php else: ?>
                                <span style="color:#a0aec0;">Jamais connecté</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <td><i class="fas fa-sign-in-alt"></i> Connexions</td>
                            <td><strong><?= (int)($user['login_count'] ?? 0) ?></strong> fois</td>
                        </tr>
                        <tr><td><i class="fas fa-envelope"></i> Email</td><td><?= e($user['email']) ?></td></tr>
                        <tr><td><i class="fas fa-calendar-alt"></i> Naissance</td><td><?= $user['birth_date'] ? e(formatDate($user['birth_date'])) : '<span style="color:#a0aec0;">Non renseignée</span>' ?></td></tr>
                        <?php if ($user['role'] === 'teacher'): ?>
                        <tr><td><i class="fas fa-graduation-cap"></i> Diplôme</td><td><?= e($teacherInfo['diploma'] ?? '') ?: '<span style="color:#a0aec0;">—</span>' ?></td></tr>
                        <tr><td><i class="fas fa-chalkboard"></i> Matière</td><td><?= e($teacherInfo['subject'] ?? '') ?: '<span style="color:#a0aec0;">—</span>' ?></td></tr>
                        <?php endif; ?>
                    </table>
                </div>

                <!-- Stats (élève/parent) -->
                <?php if ($gradeStats): ?>
                <div class="card" style="margin-top:1rem;">
                    <div class="card-header"><span class="card-title"><i class="fas fa-chart-bar"></i> Statistiques</span></div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem;margin-top:.5rem;">
                        <div class="detail-stat-box">
                            <i class="fas fa-star-half-alt" style="color:#667eea;font-size:1.4rem;"></i>
                            <div class="detail-stat-val"><?= (int)$gradeStats['nb_grades'] ?></div>
                            <div class="detail-stat-lbl">Notes</div>
                        </div>
                        <div class="detail-stat-box">
                            <i class="fas fa-trophy" style="color:#ed8936;font-size:1.4rem;"></i>
                            <div class="detail-stat-val"><?= $gradeStats['nb_grades'] > 0 ? round((float)$gradeStats['avg_score'], 1) : '—' ?></div>
                            <div class="detail-stat-lbl">Moy. /20</div>
                        </div>
                        <div class="detail-stat-box">
                            <i class="fas fa-receipt" style="color:#48bb78;font-size:1.4rem;"></i>
                            <div class="detail-stat-val"><?= (int)$payStats['nb_payments'] ?></div>
                            <div class="detail-stat-lbl">Paiements</div>
                        </div>
                        <div class="detail-stat-box">
                            <i class="fas fa-coins" style="color:#38b2ac;font-size:1.4rem;"></i>
                            <div class="detail-stat-val" style="font-size:.85rem;"><?= formatAmount($payStats['total_paid']) ?></div>
                            <div class="detail-stat-lbl">Total versé</div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Élève lié -->
                <?php if ($linkedStudent): ?>
                <div class="card" style="margin-top:1rem;">
                    <div class="card-header"><span class="card-title"><i class="fas fa-user-graduate"></i> Élève lié</span></div>
                    <div class="detail-linked-student">
                        <div class="user-avatar-sm" style="width:40px;height:40px;font-size:1.1rem;">
                            <?= strtoupper(mb_substr($linkedStudent['first_name'],0,1)) ?>
                        </div>
                        <div>
                            <div style="font-weight:700;"><?= e($linkedStudent['last_name'].' '.$linkedStudent['first_name']) ?></div>
                            <div style="color:#718096;font-size:.85rem;"><?= e($linkedStudent['class_name'] ?? '-') ?> — <?= e($linkedStudent['school_name'] ?? '-') ?></div>
                        </div>
                        <a href="id_cards.php?type=students&ids[]=<?= $linkedStudent['id'] ?>" class="btn-action btn-view" style="margin-left:auto;font-size:.72rem;" title="Carte d'identité"><i class="fas fa-id-card"></i></a>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Enfants liés (parent) -->
                <?php if (!empty($children)): ?>
                <div class="card" style="margin-top:1rem;">
                    <div class="card-header">
                        <span class="card-title"><i class="fas fa-child"></i> Enfants liés</span>
                        <span class="role-count"><?= count($children) ?></span>
                    </div>
                    <div style="display:flex;flex-direction:column;gap:.6rem;margin-top:.5rem;">
                    <?php foreach ($children as $ch): ?>
                    <div class="detail-linked-student">
                        <div class="user-avatar-sm" style="width:36px;height:36px;font-size:1rem;">
                            <?= strtoupper(mb_substr($ch['first_name'],0,1)) ?>
                        </div>
                        <div>
                            <div style="font-weight:600;font-size:.95rem;"><?= e($ch['last_name'].' '.$ch['first_name']) ?></div>
                            <div style="color:#718096;font-size:.82rem;"><?= e($ch['class_name'] ?? '-') ?></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Colonne droite : permissions effectives -->
            <div class="detail-col-right">
                <div class="card">
                    <div class="card-header">
                        <span class="card-title"><i class="fas fa-shield-alt"></i> Permissions effectives</span>
                        <?php if ($user['role'] === 'super_admin'): ?>
                        <span class="badge badge-super"><i class="fas fa-crown"></i> Accès total</span>
                        <?php else: ?>
                        <a href="permissions.php" class="btn-action btn-edit" style="font-size:.8rem;">
                            <i class="fas fa-sliders-h"></i> Modifier
                        </a>
                        <?php endif; ?>
                    </div>

                    <?php
                    $groups = ['Administration' => [], 'Portail' => []];
                    foreach ($pageLabels as $pageKey => $meta) {
                        if (isset($effectivePerms[$pageKey])) {
                            $groups[$meta['group']][$pageKey] = $meta;
                        }
                    }
                    foreach ($groups as $groupName => $groupPages):
                        if (empty($groupPages)) continue;
                    ?>
                    <div class="perm-detail-group">
                        <div class="perm-detail-group-title">
                            <i class="fas fa-<?= $groupName === 'Portail' ? 'user-circle' : 'cogs' ?>"></i>
                            <?= $groupName ?>
                        </div>
                        <?php foreach ($groupPages as $pageKey => $meta): ?>
                        <?php $perm = $effectivePerms[$pageKey] ?? []; ?>
                        <div class="perm-detail-row">
                            <div class="perm-detail-page">
                                <i class="fas <?= $meta['icon'] ?>"></i>
                                <?= $meta['label'] ?>
                            </div>
                            <div class="perm-detail-actions">
                                <?php foreach ($actionLabels as $actKey => $actLabel): ?>
                                <?php $granted = !empty($perm[$actKey]); ?>
                                <span class="perm-bit <?= $granted ? 'perm-bit-on' : 'perm-bit-off' ?>"
                                      title="<?= $actLabel ?>">
                                    <i class="fas <?= $actionIcons[$actKey] ?>"></i>
                                    <?= $actLabel ?>
                                </span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endforeach; ?>

                    <?php if (empty(array_merge(...array_values($groups)))): ?>
                    <p style="color:#a0aec0;text-align:center;padding:1rem;">Aucune permission configurée.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div><!-- .detail-layout -->

    </div>
</div>
</body>
</html>
