<?php
require_once 'db2.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db = Database::getInstance();
        
        $stmt = $db->prepare("INSERT INTO users (name, email, company) VALUES (?, ?, ?)");
        $stmt->execute([
            $_POST['name'],
            $_POST['email'],
            $_POST['company']
        ]);
        
        $response = [
            'status' => 'success',
            'message' => 'Utilisateur ajouté avec succès'
        ];
    } catch (PDOException $e) {
        $response = [
            'status' => 'error',
            'message' => $e->getMessage()
        ];
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
    <title>Ajout d'Utilisateurs</title>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen py-12 px-4 sm:px-6 lg:px-8">
        <div class="max-w-md mx-auto">
            <div class="text-center mb-8">
                <h2 class="text-3xl font-bold text-gray-900">
                    Ajout d'utilisateur
                </h2>
                <p class="mt-2 text-gray-600">
                    Remplissez les informations ci-dessous
                </p>
            </div>

            <div class="bg-white py-8 px-6 shadow rounded-lg">
                <form id="userForm" class="space-y-6">
                    <div>
                        <label for="name" class="block text-sm font-medium text-gray-700">
                            Nom complet
                        </label>
                        <div class="mt-1">
                            <input type="text" name="name" id="name" required
                                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>

                    <div>
                        <label for="email" class="block text-sm font-medium text-gray-700">
                            Email
                        </label>
                        <div class="mt-1">
                            <input type="email" name="email" id="email" required
                                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>

                    <div>
                        <label for="company" class="block text-sm font-medium text-gray-700">
                            Entreprise
                        </label>
                        <div class="mt-1">
                            <input type="text" name="company" id="company"
                                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>

                    <div>
                        <button type="submit"
                            class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            Ajouter l'utilisateur
                        </button>
                    </div>
                </form>

                <!-- Notification -->
                <div id="notification" class="hidden mt-4 p-4 rounded-md">
                    <p id="notificationText" class="text-sm"></p>
                </div>
            </div>

            <!-- Tableau des derniers ajouts -->
            <div class="mt-8 bg-white shadow rounded-lg overflow-hidden">
                <div class="px-4 py-5 sm:px-6">
                    <h3 class="text-lg font-medium text-gray-900">
                        Derniers utilisateurs ajoutés
                    </h3>
                </div>
                <div class="border-t border-gray-200">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Nom
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Email
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Entreprise
                                    </th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200" id="usersTable">
                                <?php
                                try {
                                    $db = Database::getInstance();
                                    $users = $db->query("SELECT * FROM users ORDER BY created_at DESC LIMIT 5")->fetchAll();
                                    
                                    foreach ($users as $user) {
                                        echo "<tr>
                                            <td class='px-6 py-4 whitespace-nowrap text-sm text-gray-900'>{$user['name']}</td>
                                            <td class='px-6 py-4 whitespace-nowrap text-sm text-gray-500'>{$user['email']}</td>
                                            <td class='px-6 py-4 whitespace-nowrap text-sm text-gray-500'>{$user['company']}</td>
                                        </tr>";
                                    }
                                } catch (PDOException $e) {
                                    echo "<tr><td colspan='3' class='px-6 py-4 text-center text-red-500'>Erreur lors du chargement des utilisateurs</td></tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
    document.getElementById('userForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const form = e.target;
        const notification = document.getElementById('notification');
        const notificationText = document.getElementById('notificationText');
        
        try {
            const response = await fetch('add_user.php', {
                method: 'POST',
                body: new FormData(form)
            });
            
            const result = await response.json();
            
            notification.className = result.status === 'success' 
                ? 'mt-4 p-4 rounded-md bg-green-50'
                : 'mt-4 p-4 rounded-md bg-red-50';
            
            notificationText.className = result.status === 'success'
                ? 'text-sm text-green-700'
                : 'text-sm text-red-700';
            
            notificationText.textContent = result.message;
            notification.classList.remove('hidden');
            
            if (result.status === 'success') {
                form.reset();
                // Recharger la page après 1 seconde pour mettre à jour le tableau
                setTimeout(() => window.location.reload(), 1000);
            }
            
        } catch (error) {
            notification.className = 'mt-4 p-4 rounded-md bg-red-50';
            notificationText.className = 'text-sm text-red-700';
            notificationText.textContent = 'Erreur lors de l\'envoi du formulaire';
            notification.classList.remove('hidden');
        }
    });
    </script>
</body>
</html>