<?php
/**
 * Gestion des Utilisateurs Admin - Version Standalone - SERVICES-AE
 */

// Démarrer la session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Simuler une session admin pour les tests si nécessaire
if (!isset($_SESSION['admin_logged_in'])) {
    $_SESSION['admin_logged_in'] = true;
    $_SESSION['admin_user_id'] = 1;
    $_SESSION['admin_username'] = 'admin';
}

// Inclure les dépendances
require_once '../config/config.php';
require_once '../config/db.php';
require_once __DIR__ . '/AdminUser.php';

// Initialiser AdminUser
$adminUser = new AdminUser($pdo);

// Vérifier et créer la table si nécessaire
if (!$adminUser->tableExists()) {
    $adminUser->createTable();
}

// Variables pour les messages
$success_message = '';
$error_message = '';

// Traitement des actions POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'create_user':
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $confirm_password = $_POST['confirm_password'] ?? '';
            
            // Validation
            if (empty($username) || empty($password)) {
                $error_message = "Le nom d'utilisateur et le mot de passe sont requis.";
            } elseif (strlen($username) < 3) {
                $error_message = "Le nom d'utilisateur doit contenir au moins 3 caractères.";
            } elseif (strlen($password) < 6) {
                $error_message = "Le mot de passe doit contenir au moins 6 caractères.";
            } elseif ($password !== $confirm_password) {
                $error_message = "Les mots de passe ne correspondent pas.";
            } else {
                // Vérifier si l'utilisateur existe déjà
                $existingUser = $adminUser->getByUsername($username);
                if ($existingUser) {
                    $error_message = "Un utilisateur avec ce nom existe déjà.";
                } else {
                    // Créer l'utilisateur
                    if ($adminUser->create($username, $password)) {
                        $success_message = "Utilisateur '$username' créé avec succès !";
                    } else {
                        $error_message = "Erreur lors de la création de l'utilisateur.";
                    }
                }
            }
            
            // Réponse AJAX
            if (isset($_POST['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => !empty($success_message),
                    'message' => $success_message ?: $error_message
                ]);
                exit;
            }
            break;
            
        case 'delete_user':
            $user_id = (int)($_POST['user_id'] ?? 0);
            
            if ($user_id <= 0) {
                $error_message = "ID utilisateur invalide.";
            } elseif ($user_id == ($_SESSION['admin_user_id'] ?? 0)) {
                $error_message = "Vous ne pouvez pas supprimer votre propre compte.";
            } else {
                $userToDelete = $adminUser->getById($user_id);
                if (!$userToDelete) {
                    $error_message = "Utilisateur non trouvé.";
                } else {
                    // Supprimer l'avatar s'il existe
                    if ($userToDelete['avatar']) {
                        $avatar_path = __DIR__ . '/uploads/avatars/' . $userToDelete['avatar'];
                        if (file_exists($avatar_path)) {
                            unlink($avatar_path);
                        }
                    }
                    
                    // Supprimer l'utilisateur
                    $stmt = $pdo->prepare("DELETE FROM admin_users WHERE id = ?");
                    if ($stmt->execute([$user_id])) {
                        $success_message = "Utilisateur '" . htmlspecialchars($userToDelete['username']) . "' supprimé avec succès.";
                    } else {
                        $error_message = "Erreur lors de la suppression.";
                    }
                }
            }
            
            // Réponse AJAX
            if (isset($_POST['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => !empty($success_message),
                    'message' => $success_message ?: $error_message
                ]);
                exit;
            }
            break;
    }
}

// Récupérer tous les utilisateurs
$search = $_GET['search'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 10;
$offset = ($page - 1) * $per_page;

$where_clause = '';
$params = [];

if (!empty($search)) {
    $where_clause = "WHERE username LIKE ?";
    $params[] = "%$search%";
}

// Compter le total
$count_sql = "SELECT COUNT(*) FROM admin_users $where_clause";
$stmt = $pdo->prepare($count_sql);
$stmt->execute($params);
$total_users = $stmt->fetchColumn();

// Récupérer les utilisateurs avec pagination
$sql = "SELECT id, username, created_at, updated_at, last_login, avatar 
        FROM admin_users 
        $where_clause 
        ORDER BY created_at DESC 
        LIMIT $per_page OFFSET $offset";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

$total_pages = ceil($total_users / $per_page);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des Utilisateurs - SERVICES-AE Admin</title>
    
    <!-- Bootstrap & Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/remixicon@4.3.0/fonts/remixicon.css">
    
    <style>
        :root {
            --primary-color: #696cff;
            --secondary-color: #8592a3;
            --success-color: #71dd37;
            --danger-color: #ff3e1d;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background-color: #f8f7fa;
            color: #697a8d;
        }
        
        .navbar {
            background: linear-gradient(135deg, var(--primary-color), #5a5fe7);
            box-shadow: 0 2px 6px rgba(67, 89, 113, 0.12);
        }
        
        .main-content {
            padding: 2rem 0;
        }
        
        .page-header {
            background: white;
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 6px rgba(67, 89, 113, 0.12);
        }
        
        .stats-card {
            background: white;
            border-radius: 0.5rem;
            padding: 1.5rem;
            text-align: center;
            box-shadow: 0 2px 6px rgba(67, 89, 113, 0.12);
            border: 1px solid #d9dee3;
        }
        
        .stats-card i {
            font-size: 2.5rem;
            margin-bottom: 1rem;
        }
        
        .card {
            border: 1px solid #d9dee3;
            box-shadow: 0 2px 6px rgba(67, 89, 113, 0.12);
            border-radius: 0.5rem;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: #5a5fe7;
            border-color: #5a5fe7;
        }
        
        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
        
        .avatar-placeholder {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e9ecef;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
        }
        
        .table th {
            font-weight: 600;
            color: #495057;
            border-top: none;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand fw-bold" href="index.php">
                <i class="ri-dashboard-line me-2"></i>SERVICES-AE Admin
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="index.php">
                    <i class="ri-dashboard-line me-1"></i>Dashboard
                </a>
                <a class="nav-link" href="admin-profile.php">
                    <i class="ri-user-line me-1"></i>Profil
                </a>
                <a class="nav-link active" href="admin-users-standalone.php">
                    <i class="ri-group-line me-1"></i>Utilisateurs
                </a>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <div class="container">
            
            <!-- En-tête de page -->
            <div class="page-header">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h2 class="mb-2">👥 Gestion des Utilisateurs</h2>
                        <p class="text-muted mb-0">Créer, modifier et gérer les comptes administrateurs</p>
                    </div>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createUserModal">
                        <i class="ri-user-add-line me-2"></i>Nouvel Utilisateur
                    </button>
                </div>
            </div>

            <!-- Messages d'alerte -->
            <div id="alertContainer">
                <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="ri-check-circle-line me-2"></i>
                        <?= htmlspecialchars($success_message) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-2"></i>
                        <?= htmlspecialchars($error_message) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Statistiques -->
            <div class="row mb-4">
                <div class="col-md-3 mb-3">
                    <div class="stats-card">
                        <i class="ri-group-line text-primary"></i>
                        <h4 class="fw-bold"><?= $total_users ?></h4>
                        <p class="mb-0 text-muted">Total Utilisateurs</p>
                    </div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="stats-card">
                        <i class="ri-user-add-line text-success"></i>
                        <h4 class="fw-bold">Actif</h4>
                        <p class="mb-0 text-muted">Système</p>
                    </div>
                </div>
            </div>

            <!-- Table des utilisateurs -->
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Liste des Utilisateurs</h5>
                        
                        <!-- Recherche -->
                        <form method="GET" class="d-flex">
                            <input type="text" 
                                   name="search" 
                                   class="form-control me-2" 
                                   placeholder="Rechercher..."
                                   value="<?= htmlspecialchars($search) ?>"
                                   style="width: 200px;">
                            <button type="submit" class="btn btn-outline-primary">
                                <i class="ri-search-line"></i>
                            </button>
                        </form>
                    </div>
                </div>
                
                <div class="card-body p-0">
                    <?php if (empty($users)): ?>
                        <div class="text-center py-5">
                            <i class="ri-user-search-line text-muted" style="font-size: 4rem;"></i>
                            <h5 class="mt-3 text-muted">Aucun utilisateur trouvé</h5>
                            <p class="text-muted">
                                <?= $search ? "Aucun résultat pour \"$search\"" : "Commencez par créer un utilisateur" ?>
                            </p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>ID</th>
                                        <th>Avatar</th>
                                        <th>Nom d'utilisateur</th>
                                        <th>Créé le</th>
                                        <th>Dernière connexion</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($users as $user): ?>
                                        <tr>
                                            <td class="align-middle">
                                                <span class="badge bg-primary">#<?= $user['id'] ?></span>
                                            </td>
                                            <td class="align-middle">
                                                <?php if ($user['avatar'] && file_exists("uploads/avatars/{$user['avatar']}")): ?>
                                                    <img src="uploads/avatars/<?= htmlspecialchars($user['avatar']) ?>" 
                                                         alt="Avatar" class="avatar">
                                                <?php else: ?>
                                                    <div class="avatar-placeholder">
                                                        <i class="ri-user-line"></i>
                                                    </div>
                                                <?php endif; ?>
                                            </td>
                                            <td class="align-middle">
                                                <div class="d-flex align-items-center">
                                                    <div>
                                                        <div class="fw-medium"><?= htmlspecialchars($user['username']) ?></div>
                                                        <?php if ($user['id'] == ($_SESSION['admin_user_id'] ?? 0)): ?>
                                                            <small class="badge bg-info">Vous</small>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </td>
                                            <td class="align-middle">
                                                <?php if ($user['created_at']): ?>
                                                    <small class="text-muted">
                                                        <?= date('d/m/Y H:i', strtotime($user['created_at'])) ?>
                                                    </small>
                                                <?php else: ?>
                                                    <small class="text-muted">-</small>
                                                <?php endif; ?>
                                            </td>
                                            <td class="align-middle">
                                                <?php if ($user['last_login']): ?>
                                                    <small class="text-muted">
                                                        <?= date('d/m/Y H:i', strtotime($user['last_login'])) ?>
                                                    </small>
                                                <?php else: ?>
                                                    <span class="badge bg-warning">Jamais</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="align-middle">
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-outline-primary" title="Modifier">
                                                        <i class="ri-edit-line"></i>
                                                    </button>
                                                    <?php if ($user['id'] != ($_SESSION['admin_user_id'] ?? 0)): ?>
                                                        <button class="btn btn-outline-danger" 
                                                                onclick="deleteUser(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username']) ?>')"
                                                                title="Supprimer">
                                                            <i class="ri-delete-bin-line"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="card-footer">
                        <nav>
                            <ul class="pagination justify-content-center mb-0">
                                <?php if ($page > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?= $page - 1 ?><?= $search ? '&search=' . urlencode($search) : '' ?>">
                                            Précédent
                                        </a>
                                    </li>
                                <?php endif; ?>

                                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                        <a class="page-link" href="?page=<?= $i ?><?= $search ? '&search=' . urlencode($search) : '' ?>">
                                            <?= $i ?>
                                        </a>
                                    </li>
                                <?php endfor; ?>

                                <?php if ($page < $total_pages): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?= $page + 1 ?><?= $search ? '&search=' . urlencode($search) : '' ?>">
                                            Suivant
                                        </a>
                                    </li>
                                <?php endif; ?>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Modal Créer Utilisateur -->
    <div class="modal fade" id="createUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="ri-user-add-line me-2"></i>Nouvel Utilisateur
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="createUserForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Nom d'utilisateur</label>
                            <input type="text" class="form-control" name="username" required minlength="3">
                            <div class="form-text">Au moins 3 caractères</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Mot de passe</label>
                            <input type="password" class="form-control" name="password" required minlength="6">
                            <div class="form-text">Au moins 6 caractères</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Confirmer le mot de passe</label>
                            <input type="password" class="form-control" name="confirm_password" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                        <button type="submit" class="btn btn-primary">Créer</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Fonction pour afficher les alertes
        function showAlert(message, type = 'success') {
            const alertContainer = document.getElementById('alertContainer');
            const alertId = 'alert_' + Date.now();
            
            const alertHtml = `
                <div id="${alertId}" class="alert alert-${type} alert-dismissible fade show" role="alert">
                    <i class="ri-${type === 'success' ? 'check-circle' : 'error-warning'}-line me-2"></i>
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            alertContainer.insertAdjacentHTML('afterbegin', alertHtml);
            
            // Auto-dismiss after 5 seconds
            setTimeout(() => {
                const alert = document.getElementById(alertId);
                if (alert) {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                }
            }, 5000);
        }

        // Créer un utilisateur
        document.getElementById('createUserForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            formData.append('action', 'create_user');
            formData.append('ajax', '1');
            
            // Validation des mots de passe
            const password = formData.get('password');
            const confirmPassword = formData.get('confirm_password');
            
            if (password !== confirmPassword) {
                showAlert('Les mots de passe ne correspondent pas.', 'danger');
                return;
            }
            
            // Désactiver le bouton
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="ri-loader-4-line ri-spin me-2"></i>Création...';
            
            fetch('admin-users-standalone.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert(data.message, 'success');
                    bootstrap.Modal.getInstance(document.getElementById('createUserModal')).hide();
                    this.reset();
                    
                    // Recharger la page après 1 seconde
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showAlert(data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Erreur:', error);
                showAlert('Erreur de connexion au serveur.', 'danger');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        });

        // Supprimer un utilisateur
        function deleteUser(userId, username) {
            if (confirm(`Êtes-vous sûr de vouloir supprimer l'utilisateur "${username}" ?\n\nCette action est irréversible.`)) {
                const formData = new FormData();
                formData.append('action', 'delete_user');
                formData.append('user_id', userId);
                formData.append('ajax', '1');
                
                fetch('admin-users-standalone.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showAlert(data.message, 'success');
                        
                        // Recharger la page après 1 seconde
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        showAlert(data.message, 'danger');
                    }
                })
                .catch(error => {
                    console.error('Erreur:', error);
                    showAlert('Erreur de connexion au serveur.', 'danger');
                });
            }
        }
    </script>
</body>
</html>