<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// Fonction pour copier un répertoire et son contenu
function copyDirectory($source, $destination) {
    if (!is_dir($destination)) {
        mkdir($destination, 0755, true);
    }
    $dir = opendir($source);
    while (($file = readdir($dir)) !== false) {
        if ($file != '.' && $file != '..') {
            $srcFile = $source . '/' . $file;
            $destFile = $destination . '/' . $file;
            if (is_dir($srcFile)) {
                copyDirectory($srcFile, $destFile);
            } else {
                copy($srcFile, $destFile);
            }
        }
    }
    closedir($dir);
    return true;
}

// Connexion à la base de données SQLite
$db = new SQLite3('admin.db');

// Récupération des gérants
$query = "SELECT * FROM managers";
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = SQLite3::escapeString($_GET['search']);
    $query .= " WHERE name LIKE '%$search%'";
}
$query .= " ORDER BY name ASC";
$result = $db->query($query);

$managers = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $managers[] = $row;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Portail de Gestion des Associations - Lahcen Dadda</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <header class="main-header">
        <h1><i class="fas fa-users-cog"></i> Portail de Gestion des Associations - Lahcen Dadda</h1>
        <nav>
            <a href="add_manager.php" class="btn btn-success"><i class="fas fa-user-plus"></i> Ajouter une Association</a>
            <a href="change_password.php" class="btn btn-info"><i class="fas fa-key"></i> Changer Mot de Passe</a>
            <a href="logout.php" class="btn btn-logout"><i class="fas fa-sign-out-alt"></i> Déconnexion</a>
        </nav>
    </header>

    <div class="container">
        <div class="card">
            <div class="card-header">
                <h2><i class="fas fa-search"></i> Rechercher une Association</h2>
            </div>
            <div class="card-body">
                <?php if (isset($_SESSION['success_message'])): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success_message']; ?>
                    </div>
                    <?php unset($_SESSION['success_message']); ?>
                <?php endif; ?>
                
                <form action="index.php" method="GET" class="search-form">
                    <input type="search" name="search" placeholder="Rechercher par nom..." value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Rechercher</button>
                </form>
            </div>
        </div>

        <div class="section-title">
            <i class="fas fa-list"></i> <?php echo count($managers); ?> Association<?php echo count($managers) > 1 ? 's' : ''; ?>
        </div>

        <?php if (count($managers) > 0): ?>
            <div class="manager-list">
                <?php foreach ($managers as $index => $manager): ?>
                    <div class="manager-item">
                        <h3><i class="fas fa-user"></i> <?php echo htmlspecialchars($manager['name']); ?></h3>
                        <div class="manager-details">
                            <p><i class="fas fa-folder"></i> Dossier: <?php echo htmlspecialchars($manager['folder_name']); ?></p>
                            <p><i class="fas fa-calendar-alt"></i> Créé le: <?php echo htmlspecialchars($manager['created_at']); ?></p>
                        </div>
                        <div class="link-container">
                            <input type="text" readonly value="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/dadda-eps/' . $manager['folder_name']; ?>" id="link-<?php echo $manager['id']; ?>">
                            <button class="btn btn-info btn-sm copy-link" data-link="link-<?php echo $manager['id']; ?>">
                                <i class="fas fa-copy"></i> Copier
                            </button>
                            <a href="<?php echo htmlspecialchars($manager['folder_name']); ?>" class="btn btn-success btn-sm" target="_blank"   >
                                <i class="fas fa-external-link-alt"></i> Accéder
                            </a>
                            <a href="delete_manager.php?id=<?php echo $manager['id']; ?>" class="btn btn-danger btn-sm delete-manager" onclick="return confirm('Êtes-vous sûr de vouloir supprimer cette association ?');">
                                <i class="fas fa-trash-alt"></i> Supprimer
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="no-results">
                <i class="fas fa-search"></i>
                <h3>Aucune association trouvée</h3>
                <p>Essayez avec un terme de recherche différent ou ajoutez une nouvelle association.</p>
                <a href="add_manager.php" class="btn btn-success"><i class="fas fa-user-plus"></i> Ajouter une Association</a>
            </div>
        <?php endif; ?>
    </div>

    <div class="notification" id="notification">
        <i class="fas fa-check-circle"></i> Lien copié dans le presse-papiers!
    </div>

    <script>
        // Fonction pour copier le lien dans le presse-papiers
        document.querySelectorAll('.copy-link').forEach(button => {
            button.addEventListener('click', function() {
                const linkId = this.getAttribute('data-link');
                const linkInput = document.getElementById(linkId);
                linkInput.select();
                
                try {
                    // Utilisation de l'API Clipboard
                    navigator.clipboard.writeText(linkInput.value).then(() => {
                        showNotification();
                    });
                } catch (err) {
                    // Fallback pour les navigateurs qui ne supportent pas l'API Clipboard
                    document.execCommand('copy');
                    showNotification();
                }
            });
        });

        // Afficher la notification
        function showNotification() {
            const notification = document.getElementById('notification');
            notification.classList.add('show');
            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }
    </script>
</body>
</html>
