<?php
require_once '../includes/auth.php';
if (!checkPermission('admin')) {
    header('Location: ../dashboard.php');
    exit;
}
require_once '../config/database.php';
require_once '../includes/functions.php';

$pdo = getPDO();

// Suppression d'un projet (avec vérification)
if (isset($_GET['delete_projet'])) {
    $id = filter_input(INPUT_GET, 'delete_projet', FILTER_VALIDATE_INT);
    if ($id) {
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM fiches f JOIN sous_dossiers sd ON f.sous_dossier_id = sd.id JOIN dossiers d ON sd.dossier_id = d.id WHERE d.projet_id = ?");
            $stmt->execute([$id]);
            $count = $stmt->fetchColumn();
            if ($count > 0) {
                $_SESSION['error'] = "Impossible de supprimer ce projet car il contient des fiches.";
            } else {
                $stmt = $pdo->prepare("DELETE FROM projets WHERE id = ?");
                $stmt->execute([$id]);
                logAction($pdo, $_SESSION['user_id'], 'suppression_projet', "Projet ID $id");
                $_SESSION['success'] = "Projet supprimé avec succès.";
            }
            $pdo->commit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = "Erreur : " . $e->getMessage();
        }
    }
    header('Location: gestion_projets.php');
    exit;
}

// Suppression d'un dossier
if (isset($_GET['delete_dossier'])) {
    $id = filter_input(INPUT_GET, 'delete_dossier', FILTER_VALIDATE_INT);
    if ($id) {
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM fiches f JOIN sous_dossiers sd ON f.sous_dossier_id = sd.id WHERE sd.dossier_id = ?");
            $stmt->execute([$id]);
            $count = $stmt->fetchColumn();
            if ($count > 0) {
                $_SESSION['error'] = "Impossible de supprimer ce dossier car il contient des fiches.";
            } else {
                $stmt = $pdo->prepare("DELETE FROM dossiers WHERE id = ?");
                $stmt->execute([$id]);
                logAction($pdo, $_SESSION['user_id'], 'suppression_dossier', "Dossier ID $id");
                $_SESSION['success'] = "Dossier supprimé avec succès.";
            }
            $pdo->commit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = "Erreur : " . $e->getMessage();
        }
    }
    header('Location: gestion_projets.php');
    exit;
}

// Suppression d'un sous-dossier
if (isset($_GET['delete_sous_dossier'])) {
    $id = filter_input(INPUT_GET, 'delete_sous_dossier', FILTER_VALIDATE_INT);
    if ($id) {
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM fiches WHERE sous_dossier_id = ?");
            $stmt->execute([$id]);
            $count = $stmt->fetchColumn();
            if ($count > 0) {
                $_SESSION['error'] = "Impossible de supprimer ce sous-dossier car il contient des fiches.";
            } else {
                $stmt = $pdo->prepare("DELETE FROM sous_dossiers WHERE id = ?");
                $stmt->execute([$id]);
                logAction($pdo, $_SESSION['user_id'], 'suppression_sous_dossier', "Sous-dossier ID $id");
                $_SESSION['success'] = "Sous-dossier supprimé avec succès.";
            }
            $pdo->commit();
        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = "Erreur : " . $e->getMessage();
        }
    }
    header('Location: gestion_projets.php');
    exit;
}

// Recherche
$search = trim($_GET['search'] ?? '');
if ($search) {
    $stmt = $pdo->prepare("SELECT * FROM projets WHERE nom LIKE ? ORDER BY nom");
    $stmt->execute(["%$search%"]);
} else {
    $stmt = $pdo->query("SELECT * FROM projets ORDER BY nom");
}
$projets = $stmt->fetchAll();

require_once '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
    <div>
        <a href="index.php" class="btn btn-outline-secondary me-2">
            <i class="fas fa-arrow-left me-1"></i> Retour à l'espace admin
        </a>
    </div>
    <div>
        <a href="ajouter_projet.php" class="btn btn-success"><i class="fas fa-plus-circle"></i> Nouveau projet</a>
    </div>
</div>

<h1><i class="fas fa-project-diagram me-2"></i>Gestion des projets</h1>

<!-- Formulaire de recherche -->
<form method="get" class="mb-4">
    <div class="input-group">
        <input type="text" name="search" class="form-control" placeholder="Rechercher un projet..." value="<?= htmlspecialchars($search) ?>">
        <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Rechercher</button>
        <?php if ($search): ?>
            <a href="gestion_projets.php" class="btn btn-outline-secondary">Réinitialiser</a>
        <?php endif; ?>
    </div>
</form>

<?php if (isset($_SESSION['error'])): ?>
    <div class="alert alert-danger"><?= $_SESSION['error'] ?></div>
    <?php unset($_SESSION['error']); ?>
<?php endif; ?>
<?php if (isset($_SESSION['success'])): ?>
    <div class="alert alert-success"><?= $_SESSION['success'] ?></div>
    <?php unset($_SESSION['success']); ?>
<?php endif; ?>

<?php if (empty($projets)): ?>
    <div class="alert alert-info">Aucun projet trouvé.</div>
<?php else: ?>
    <div class="accordion" id="accordionProjets">
        <?php foreach ($projets as $projet): ?>
            <div class="accordion-item">
                <h2 class="accordion-header" id="heading<?= $projet['id'] ?>">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse<?= $projet['id'] ?>">
                        <strong><?= htmlspecialchars($projet['nom']) ?></strong>
                        <small class="ms-3 text-muted"><?= htmlspecialchars($projet['description']) ?></small>
                        <div class="ms-auto">
                            <a href="modifier_projet.php?id=<?= $projet['id'] ?>" class="btn btn-sm btn-warning me-1" onclick="event.stopPropagation()"><i class="fas fa-edit"></i></a>
                            <a href="?delete_projet=<?= $projet['id'] ?>" class="btn btn-sm btn-danger" onclick="event.stopPropagation(); return confirm('Supprimer définitivement ce projet ? Toutes ses données seront effacées (sauf si des fiches existent).')"><i class="fas fa-trash"></i></a>
                        </div>
                    </button>
                </h2>
                <div id="collapse<?= $projet['id'] ?>" class="accordion-collapse collapse" data-bs-parent="#accordionProjets">
                    <div class="accordion-body">
                        <h5>Dossiers</h5>
                        <?php
                        $dossiers = $pdo->prepare("SELECT * FROM dossiers WHERE projet_id = ? ORDER BY ordre");
                        $dossiers->execute([$projet['id']]);
                        $dossiers = $dossiers->fetchAll();
                        ?>
                        <?php if (empty($dossiers)): ?>
                            <p class="text-muted">Aucun dossier.</p>
                        <?php else: ?>
                            <ul class="list-group mb-3">
                                <?php foreach ($dossiers as $dossier): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <span><?= htmlspecialchars($dossier['nom']) ?></span>
                                        <div>
                                            <a href="modifier_dossier.php?id=<?= $dossier['id'] ?>" class="btn btn-sm btn-warning"><i class="fas fa-edit"></i></a>
                                            <a href="?delete_dossier=<?= $dossier['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Supprimer ce dossier ?')"><i class="fas fa-trash"></i></a>
                                        </div>
                                    </li>
                                    <?php
                                    $sous_dossiers = $pdo->prepare("SELECT * FROM sous_dossiers WHERE dossier_id = ? ORDER BY ordre");
                                    $sous_dossiers->execute([$dossier['id']]);
                                    $sous_dossiers = $sous_dossiers->fetchAll();
                                    ?>
                                    <?php if (!empty($sous_dossiers)): ?>
                                        <li class="list-group-item">
                                            <ul class="list-group list-group-flush ps-3">
                                                <?php foreach ($sous_dossiers as $sd): ?>
                                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                                        <span>📄 <?= htmlspecialchars($sd['nom']) ?></span>
                                                        <div>
                                                            <a href="modifier_sous_dossier.php?id=<?= $sd['id'] ?>" class="btn btn-sm btn-warning"><i class="fas fa-edit"></i></a>
                                                            <a href="?delete_sous_dossier=<?= $sd['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Supprimer ce sous-dossier ?')"><i class="fas fa-trash"></i></a>
                                                        </div>
                                                    </li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </li>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                        <a href="ajouter_dossier.php?projet_id=<?= $projet['id'] ?>" class="btn btn-sm btn-primary"><i class="fas fa-plus"></i> Ajouter un dossier</a>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<?php require_once '../includes/footer.php'; ?>