<?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 = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nom = trim($_POST['nom'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $date_debut = $_POST['date_debut'] ?? null;

    if (empty($nom)) {
        $error = "Le nom du projet est requis.";
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO projets (nom, description, date_debut, created_by) VALUES (?, ?, ?, ?)");
            $stmt->execute([$nom, $description, $date_debut, $_SESSION['user_id']]);
            logAction($pdo, $_SESSION['user_id'], 'creation_projet', "Projet $nom");
            $_SESSION['success'] = "Projet créé avec succès.";
            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-8">
        <div class="card">
            <div class="card-header bg-success text-white">
                <h4 class="mb-0"><i class="fas fa-plus-circle me-2"></i>Créer un nouveau projet</h4>
            </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 projet *</label>
                        <input type="text" class="form-control" id="nom" name="nom" required>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="date_debut" class="form-label">Date de début</label>
                        <input type="date" class="form-control" id="date_debut" name="date_debut">
                    </div>
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-success">Créer</button>
                        <a href="../dashboard.php" class="btn btn-outline-secondary">Annuler</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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