<?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();
$error = '';
$dossier_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$dossier_id) {
    header('Location: gestion_projets.php');
    exit;
}

$stmt = $pdo->prepare("SELECT d.*, p.nom as projet_nom FROM dossiers d JOIN projets p ON d.projet_id = p.id WHERE d.id = ?");
$stmt->execute([$dossier_id]);
$dossier = $stmt->fetch();
if (!$dossier) {
    header('Location: gestion_projets.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nom = trim($_POST['nom'] ?? '');
    if (empty($nom)) {
        $error = "Le nom est requis.";
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE dossiers SET nom = ? WHERE id = ?");
            $stmt->execute([$nom, $dossier_id]);
            logAction($pdo, $_SESSION['user_id'], 'modification_dossier', "Dossier ID $dossier_id : '$nom'");
            $_SESSION['success'] = "Dossier modifié.";
            header('Location: gestion_projets.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-warning text-white">
                <h4 class="mb-0"><i class="fas fa-edit me-2"></i>Modifier le dossier</h4>
            </div>
            <div class="card-body">
                <p class="text-muted">Projet : <?= htmlspecialchars($dossier['projet_nom']) ?></p>
                <?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" value="<?= htmlspecialchars($dossier['nom']) ?>" required>
                    </div>
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-warning">Enregistrer</button>
                        <a href="gestion_projets.php" class="btn btn-outline-secondary">Annuler</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php require_once '../includes/footer.php'; ?>