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

// Traitement ajout / modification
if (isset($_POST['save_template'])) {
    $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
    $nom = trim($_POST['nom'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $contenu_json = $_POST['contenu_template'] ?? '';

    if (empty($nom)) {
        $error = "Le nom est requis.";
    } elseif (empty($contenu_json)) {
        $error = "Le contenu JSON est requis.";
    } else {
        // Validation du JSON
        $decoded = json_decode($contenu_json, true);
        if (!is_array($decoded)) {
            $error = "JSON invalide.";
        } else {
            try {
                if ($id) {
                    $stmt = $pdo->prepare("UPDATE templates_library SET nom = ?, description = ?, contenu_template = ? WHERE id = ?");
                    $stmt->execute([$nom, $description, $contenu_json, $id]);
                    logAction($pdo, $_SESSION['user_id'], 'update_template_library', "Template ID $id");
                    $success = "Template mis à jour.";
                } else {
                    $stmt = $pdo->prepare("INSERT INTO templates_library (nom, description, contenu_template) VALUES (?, ?, ?)");
                    $stmt->execute([$nom, $description, $contenu_json]);
                    logAction($pdo, $_SESSION['user_id'], 'create_template_library', "Template $nom");
                    $success = "Template créé.";
                }
            } catch (Exception $e) {
                $error = "Erreur : " . $e->getMessage();
            }
        }
    }
}

// Suppression
if (isset($_GET['delete'])) {
    $id = filter_input(INPUT_GET, 'delete', FILTER_VALIDATE_INT);
    if ($id) {
        try {
            $stmt = $pdo->prepare("DELETE FROM templates_library WHERE id = ?");
            $stmt->execute([$id]);
            logAction($pdo, $_SESSION['user_id'], 'delete_template_library', "Template ID $id");
            $success = "Template supprimé.";
        } catch (Exception $e) {
            $error = "Erreur : " . $e->getMessage();
        }
    }
    header('Location: gestion_templates_library.php');
    exit;
}

// Récupération de la liste
$templates = $pdo->query("SELECT * FROM templates_library ORDER BY nom")->fetchAll();

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="fas fa-book me-2"></i>Bibliothèque de templates</h1>
    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#templateModal" onclick="resetForm()">
        <i class="fas fa-plus"></i> Nouveau template
    </button>
</div>

<?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>

<div class="row">
    <?php foreach ($templates as $tpl): ?>
        <div class="col-md-4 mb-3">
            <div class="card h-100">
                <div class="card-header">
                    <strong><?= htmlspecialchars($tpl['nom']) ?></strong>
                </div>
                <div class="card-body">
                    <p class="small text-muted"><?= nl2br(htmlspecialchars($tpl['description'])) ?></p>
                    <pre class="small" style="max-height:150px; overflow:auto;"><?= htmlspecialchars(substr($tpl['contenu_template'], 0, 200)) ?>...</pre>
                </div>
                <div class="card-footer text-end">
                    <button class="btn btn-sm btn-warning" onclick="editTemplate(<?= $tpl['id'] ?>, '<?= addslashes($tpl['nom']) ?>', '<?= addslashes($tpl['description']) ?>', <?= htmlspecialchars(json_encode(json_decode($tpl['contenu_template'], true))) ?>)">
                        <i class="fas fa-edit"></i> Modifier
                    </button>
                    <a href="?delete=<?= $tpl['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Supprimer ce template ?')">
                        <i class="fas fa-trash"></i>
                    </a>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<!-- Modal d'édition -->
<div class="modal fade" id="templateModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="post" id="libraryForm">
                <input type="hidden" name="id" id="template_id">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title"><i class="fas fa-cog"></i> Template</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label>Nom *</label>
                        <input type="text" name="nom" id="tpl_nom" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label>Description</label>
                        <textarea name="description" id="tpl_desc" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label>Contenu du template (JSON)</label>
                        <textarea name="contenu_template" id="tpl_contenu" class="form-control" rows="10" required></textarea>
                        <small class="text-muted">Structure : {"en_tete":[...], "tableau":{"colonnes":[...], "lignes":[...]}}</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="submit" name="save_template" class="btn btn-primary">Enregistrer</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetForm() {
    document.getElementById('template_id').value = '';
    document.getElementById('tpl_nom').value = '';
    document.getElementById('tpl_desc').value = '';
    document.getElementById('tpl_contenu').value = '';
}
function editTemplate(id, nom, desc, contenu) {
    document.getElementById('template_id').value = id;
    document.getElementById('tpl_nom').value = nom;
    document.getElementById('tpl_desc').value = desc;
    document.getElementById('tpl_contenu').value = JSON.stringify(contenu, null, 2);
    var modal = new bootstrap.Modal(document.getElementById('templateModal'));
    modal.show();
}
</script>

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