<?php
require_once '../includes/auth.php';
if (!checkPermission('admin')) {
    header('Location: ../dashboard.php');
    exit;
}
$dossier_id = filter_input(INPUT_GET, 'dossier_id', FILTER_VALIDATE_INT);
if (!$dossier_id) {
    header('Location: ../dashboard.php');
    exit;
}
require_once '../config/database.php';
require_once '../includes/functions.php';

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

$stmt = $pdo->prepare("SELECT id FROM dossiers WHERE id = ?");
$stmt->execute([$dossier_id]);
if (!$stmt->fetch()) {
    $_SESSION['error'] = "Dossier introuvable.";
    header('Location: ../dashboard.php');
    exit;
}

// Récupérer les templates de bibliothèque
$templates_lib = $pdo->query("SELECT id, nom FROM templates_library ORDER BY nom")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nom = trim($_POST['nom'] ?? '');
    $template_lib_id = filter_input(INPUT_POST, 'template_lib_id', FILTER_VALIDATE_INT);

    if (empty($nom)) {
        $error = "Le nom est requis.";
    } else {
        $stmt2 = $pdo->prepare("SELECT id FROM sous_dossiers WHERE dossier_id = ? AND nom = ?");
        $stmt2->execute([$dossier_id, $nom]);
        if ($stmt2->fetch()) {
            $error = "Ce nom existe déjà dans ce dossier.";
        } else {
            try {
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("SELECT MAX(ordre) FROM sous_dossiers WHERE dossier_id = ?");
                $stmt->execute([$dossier_id]);
                $ordre = ($stmt->fetchColumn() ?? -1) + 1;

                $stmt = $pdo->prepare("INSERT INTO sous_dossiers (dossier_id, nom, ordre, template_library_id) VALUES (?, ?, ?, ?)");
                $stmt->execute([$dossier_id, $nom, $ordre, $template_lib_id]);
                $sd_id = $pdo->lastInsertId();

                if ($template_lib_id) {
                    $stmt = $pdo->prepare("SELECT contenu_template FROM templates_library WHERE id = ?");
                    $stmt->execute([$template_lib_id]);
                    $template_json = $stmt->fetchColumn();
                } else {
                    $template_json = json_encode([
                        'en_tete' => [
                            ['label' => 'Chantier', 'type' => 'text', 'name' => 'chantier'],
                            ['label' => 'Date', 'type' => 'date', 'name' => 'date_controle'],
                            ['label' => 'Intervenant', 'type' => 'text', 'name' => 'intervenant']
                        ],
                        'tableau' => [
                            'colonnes' => [
                                ['label' => 'C', 'type' => 'radio', 'options' => ['C','NC','NA']],
                                ['label' => 'Observation', 'type' => 'text', 'options' => []]
                            ],
                            'lignes' => ['Point 1', 'Point 2', 'Point 3']
                        ]
                    ]);
                }
                $stmt = $pdo->prepare("INSERT INTO templates (sous_dossier_id, contenu_template) VALUES (?, ?)");
                $stmt->execute([$sd_id, $template_json]);

                $pdo->commit();
                $_SESSION['success'] = "Sous-dossier créé. Vous pouvez maintenant éditer son template.";
                header("Location: editer_template.php?id=$sd_id&type=subfolder");
                exit;
            } catch (Exception $e) {
                $pdo->rollBack();
                $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 sous-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>Nom du sous-dossier *</label>
                        <input type="text" name="nom" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label>Utiliser un template pré-enregistré (optionnel)</label>
                        <select name="template_lib_id" class="form-select">
                            <option value="">-- Aucun (template par défaut) --</option>
                            <?php foreach ($templates_lib as $tpl): ?>
                                <option value="<?= $tpl['id'] ?>"><?= htmlspecialchars($tpl['nom']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <small class="text-muted">Vous pourrez ensuite modifier le template depuis l'éditeur.</small>
                    </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'; ?>