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

// Récupérer tous les dossiers (pour choisir où créer)
$dossiers = $pdo->query("SELECT d.*, p.nom as projet_nom FROM dossiers d JOIN projets p ON d.projet_id = p.id ORDER BY p.nom, d.nom")->fetchAll();

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

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

    if (!$dossier_id || empty($nom)) {
        $error = "Dossier et nom requis.";
    } else {
        // Vérifier unicité
        $stmt = $pdo->prepare("SELECT id FROM sous_dossiers WHERE dossier_id = ? AND nom = ?");
        $stmt->execute([$dossier_id, $nom]);
        if ($stmt->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");
                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-info text-white">
                <h4><i class="fas fa-bolt"></i> Création rapide d'un sous-dossier</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>Dossier parent *</label>
                        <select name="dossier_id" class="form-select" required>
                            <option value="">-- Choisir un dossier --</option>
                            <?php foreach ($dossiers as $d): ?>
                                <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['projet_nom']) ?> / <?= htmlspecialchars($d['nom']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <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>Template pré-existant (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>
                    </div>
                    <button type="submit" class="btn btn-primary">Créer et éditer le template</button>
                    <a href="editer_template.php" class="btn btn-secondary">Annuler</a>
                </form>
            </div>
        </div>
    </div>
</div>

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