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

$projet_id = filter_input(INPUT_GET, 'projet_id', FILTER_VALIDATE_INT);
if (!$projet_id) {
    header('Location: ../dashboard.php');
    exit;
}

require_once '../config/database.php';
require_once '../includes/functions.php';

$pdo = getPDO();
$error = '';

// Vérifier que le projet existe
$stmt = $pdo->prepare("SELECT id FROM projets WHERE id = ?");
$stmt->execute([$projet_id]);
if (!$stmt->fetch()) {
    $_SESSION['error'] = "Projet introuvable.";
    header('Location: ../dashboard.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nom = trim($_POST['nom'] ?? '');  // Définition correcte de $nom
    if (empty($nom)) {
        $error = "Le nom est requis.";
    } else {
        // Vérifier l'unicité du nom dans le projet
        $stmt = $pdo->prepare("SELECT id FROM dossiers WHERE projet_id = ? AND nom = ?");
        $stmt->execute([$projet_id, $nom]);
        if ($stmt->fetch()) {
            $error = "Un dossier avec ce nom existe déjà dans ce projet.";
        } else {
            try {
                $stmt = $pdo->prepare("SELECT MAX(ordre) FROM dossiers WHERE projet_id = ?");
                $stmt->execute([$projet_id]);
                $max_ordre = $stmt->fetchColumn();
                $ordre = ($max_ordre === null) ? 0 : $max_ordre + 1;

                $stmt = $pdo->prepare("INSERT INTO dossiers (projet_id, nom, ordre) VALUES (?, ?, ?)");
                $stmt->execute([$projet_id, $nom, $ordre]);
                logAction($pdo, $_SESSION['user_id'], 'creation_dossier', "Dossier $nom dans projet $projet_id");
                $_SESSION['success'] = "Dossier créé.";
                header("Location: ../dashboard.php");
                exit;
            } catch (Exception $e) {
                $error = "Erreur : " . $e->getMessage();
            }
        }
    }
}

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

<div class="row justify-content-center">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header bg-primary text-white">Nouveau dossier</div>
            <div class="card-body">
                <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
                <form method="post">
                    <div class="mb-3">
                        <label for="nom" class="form-label">Nom du dossier</label>
                        <input type="text" class="form-control" id="nom" name="nom" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Créer</button>
                    <a href="../dashboard.php" class="btn btn-secondary">Annuler</a>
                </form>
            </div>
        </div>
    </div>
</div>

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