<?php
/**
 * Gestion des photos passeport des utilisateurs
 */
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', 'edit');

$schoolFilter = currentSchoolId();
if (isSuperAdmin() && !empty($_GET['school_id'])) {
    $schoolFilter = (int)$_GET['school_id'];
}

$filterRole = $_GET['filter_role'] ?? '';
$noPhoto   = isset($_GET['no_photo']) ? true : false;

// ── Upload d'une photo ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_photo'])) {
    verifyCsrf();
    $userId = (int)($_POST['user_id'] ?? 0);
    if ($userId && !empty($_FILES['photo']['name'])) {
        $allowedExts = ['jpg','jpeg','png','gif','webp'];
        $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExts)) {
            flashMessage('error', 'Format non autorisé (jpeg, png, gif, webp).');
        } elseif ($_FILES['photo']['size'] > 2 * 1024 * 1024) {
            flashMessage('error', 'Fichier trop volumineux (max 2 Mo).');
        } else {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $_FILES['photo']['tmp_name']);
            finfo_close($finfo);
            if (!in_array($mime, ['image/jpeg','image/png','image/gif','image/webp'])) {
                flashMessage('error', 'Le fichier n\'est pas une image valide.');
            } else {
                $old = $pdo->prepare("SELECT photo FROM users WHERE id=?");
                $old->execute([$userId]); $oldPhoto = $old->fetchColumn();
                if ($oldPhoto && file_exists(__DIR__ . '/../uploads/users/' . $oldPhoto)) {
                    unlink(__DIR__ . '/../uploads/users/' . $oldPhoto);
                }
                $photo = uniqid('user_') . '.' . $ext;
                move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__ . '/../uploads/users/' . $photo);
                $pdo->prepare("UPDATE users SET photo=? WHERE id=?")->execute([$photo, $userId]);
                if ($userId === (int)$_SESSION['user_id']) {
                    $_SESSION['user_photo'] = $photo;
                }
                flashMessage('success', 'Photo mise à jour.');
            }
        }
    }
    header('Location: user_photos.php');
    exit;
}

// ── Suppression d'une photo ───────────────────────────────────────────────────
if (isset($_GET['delete']) && isset($_GET['user_id'])) {
    verifyCsrf();
    $userId = (int)$_GET['user_id'];
    $old = $pdo->prepare("SELECT photo FROM users WHERE id=?");
    $old->execute([$userId]); $oldPhoto = $old->fetchColumn();
    if ($oldPhoto && file_exists(__DIR__ . '/../uploads/users/' . $oldPhoto)) {
        unlink(__DIR__ . '/../uploads/users/' . $oldPhoto);
    }
    $pdo->prepare("UPDATE users SET photo=NULL WHERE id=?")->execute([$userId]);
    if ($userId === (int)$_SESSION['user_id']) {
        $_SESSION['user_photo'] = null;
    }
    flashMessage('success', 'Photo supprimée.');
    header('Location: user_photos.php');
    exit;
}

// ── Chargement des utilisateurs ──────────────────────────────────────────────
$where = [];
$params = [];
if ($schoolFilter) { $where[] = "u.school_id=?"; $params[] = $schoolFilter; }
if ($filterRole && in_array($filterRole, ['super_admin','school_admin','teacher','accountant','student','parent'])) {
    $where[] = "u.role=?";
    $params[] = $filterRole;
}
if ($noPhoto) {
    $where[] = "(u.photo IS NULL OR u.photo='')";
}
$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$users = $pdo->prepare("
    SELECT u.id, u.name, u.email, u.role, u.photo, u.active, s.name AS school_name
    FROM users u
    LEFT JOIN schools s ON u.school_id = s.id
    $whereSql
    ORDER BY u.role, u.name
");
$users->execute($params);
$users = $users->fetchAll();

$schools = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Photos passeport - Nukunu Mofiala</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">
    <style>
        .photo-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
            gap: 1rem;
        }
        .photo-card {
            background: #fff;
            border-radius: 12px;
            border: 1px solid #e2e8f0;
            overflow: hidden;
            transition: box-shadow .2s;
        }
        .photo-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,.1);
        }
        .photo-card-header {
            padding: 1rem 1rem .5rem;
            display: flex;
            align-items: center;
            gap: .75rem;
        }
        .photo-card-header .user-info {
            flex: 1;
            min-width: 0;
        }
        .photo-card-header .user-info .uname {
            font-weight: 700;
            color: #2d3748;
            font-size: .9rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .photo-card-header .user-info .uemail {
            font-size: .75rem;
            color: #a0aec0;
        }
        .photo-card-body {
            padding: 0 1rem 1rem;
            text-align: center;
        }
        .photo-card-body .current-photo {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            margin: 0 auto .5rem;
            display: block;
            border: 3px solid #e2e8f0;
        }
        .photo-card-body .current-photo-initial {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: linear-gradient(135deg, #e2e8f0, #cbd5e0);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto .5rem;
            font-weight: 700;
            font-size: 2rem;
            color: #a0aec0;
            border: 3px solid #e2e8f0;
        }
        .photo-card-body .badge {
            display: inline-block;
            margin-bottom: .5rem;
        }
        .photo-card-body form {
            display: flex;
            flex-direction: column;
            gap: .5rem;
            align-items: center;
        }
        .photo-card-body form input[type="file"] {
            width: 100%;
            font-size: .8rem;
            padding: .3rem;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            background: #f7fafc;
        }
        .photo-card-body .btn-group {
            display: flex;
            gap: .4rem;
            width: 100%;
        }
        .photo-card-body .btn-group button,
        .photo-card-body .btn-group a {
            flex: 1;
            text-align: center;
            font-size: .8rem;
            padding: .4rem .5rem;
        }
        .photo-card.uploaded {
            border-color: #38a169;
            background: #f0fff4;
        }
        .photo-filter-bar {
            display: flex;
            gap: .5rem;
            flex-wrap: wrap;
            align-items: center;
            margin-bottom: 1rem;
        }
        .photo-count {
            font-size: .85rem;
            color: #718096;
            margin-left: auto;
        }
        @media (max-width: 768px) {
            .photo-count { margin-left: 0; }
        }
    </style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-camera"></i> Photos passeport'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>

        <!-- Filtres -->
        <div class="card no-print">
            <div class="card-header"><span class="card-title"><i class="fas fa-filter"></i> Filtres</span></div>
            <form method="GET" class="photo-filter-bar" style="padding:1rem;">
                <?php if (isSuperAdmin()): ?>
                <select name="school_id" onchange="this.form.submit()" style="padding:.4rem .7rem;border:1px solid #e2e8f0;border-radius:6px;">
                    <option value="">— Toutes les écoles —</option>
                    <?php foreach ($schools as $sc): ?>
                    <option value="<?= $sc['id'] ?>" <?= $schoolFilter==$sc['id']?'selected':'' ?>><?= e($sc['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
                <select name="filter_role" onchange="this.form.submit()" style="padding:.4rem .7rem;border:1px solid #e2e8f0;border-radius:6px;">
                    <option value="">— Tous les rôles —</option>
                    <?php foreach (['super_admin','school_admin','teacher','accountant','student','parent'] as $r): ?>
                    <option value="<?= $r ?>" <?= $filterRole===$r?'selected':'' ?>><?= getRoleLabel($r) ?></option>
                    <?php endforeach; ?>
                </select>
                <label style="display:flex;align-items:center;gap:.4rem;font-size:.85rem;cursor:pointer;">
                    <input type="checkbox" name="no_photo" value="1" <?= $noPhoto?'checked':'' ?> onchange="this.form.submit()">
                    Sans photo uniquement
                </label>
                <button type="submit" class="btn-action btn-view"><i class="fas fa-search"></i> Filtrer</button>
                <span class="photo-count"><?= count($users) ?> utilisateur(s)</span>
            </form>
        </div>

        <!-- Grille -->
        <div class="photo-grid">
            <?php foreach ($users as $u):
                $hasPhoto = !empty($u['photo']) && file_exists(__DIR__ . '/../uploads/users/' . $u['photo']);
            ?>
            <div class="photo-card <?= $hasPhoto?'uploaded':'' ?>">
                <div class="photo-card-header">
                    <?= userPhotoImg($u['photo'] ?? null, $u['name']) ?>
                    <div class="user-info">
                        <div class="uname"><?= e($u['name']) ?></div>
                        <div class="uemail"><?= e($u['email']) ?></div>
                    </div>
                </div>
                <div class="photo-card-body">
                    <?php if ($hasPhoto): ?>
                    <img src="<?= BASE_URL ?>uploads/users/<?= rawurlencode($u['photo']) ?>" alt="" class="current-photo">
                    <?php else: ?>
                    <div class="current-photo-initial"><?= strtoupper(mb_substr($u['name'], 0, 1)) ?></div>
                    <?php endif; ?>
                    <span class="badge <?= getRoleBadgeClass($u['role']) ?>"><?= getRoleLabel($u['role']) ?></span>

                    <form method="POST" enctype="multipart/form-data">
                        <?= csrfField() ?>
                        <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                        <input type="file" name="photo" accept="image/jpeg,image/png,image/gif,image/webp" required>
                        <div class="btn-group">
                            <button type="submit" name="upload_photo" class="btn-action" style="background:#667eea;color:white;border:none;">
                                <i class="fas fa-upload"></i> <?= $hasPhoto ? 'Remplacer' : 'Ajouter' ?>
                            </button>
                            <?php if ($hasPhoto): ?>
                            <a href="?delete=1&user_id=<?= $u['id'] ?>&csrf_token=<?= csrfToken() ?>"
                               class="btn-action btn-delete"
                               onclick="return confirm('Supprimer cette photo ?')">
                                <i class="fas fa-trash"></i>
                            </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
            <?php if (empty($users)): ?>
            <div style="grid-column:1/-1;text-align:center;padding:3rem;color:#999;">
                <i class="fas fa-camera" style="font-size:3rem;margin-bottom:1rem;"></i><br>
                Aucun utilisateur trouvé.
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>
</body>
</html>
