<?php
require_once "config/config.php"; // PDO $pdo
include("Data.class.php");
$Data = new Data($pdo);

require_once "config/session.php";

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: index.php");
    exit;
}

// Kein Admin?
if ($_SESSION['role'] !== 'admin') {
    http_response_code(403);
    echo "<h1>Zugriff verweigert</h1>";
    echo "<p>Diese Seite ist nur für Admins.</p>";
    exit;
}

// speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title_template']);
    $desc  = trim($_POST['description_template']);

    $stmt = $pdo->prepare("
        UPDATE settings_calendar 
        SET title_template = :t, description_template = :d 
        WHERE id = 1
    ");
    $stmt->execute([
        ':t' => $title,
        ':d' => $desc
    ]);

    $success = true;
}

// laden
$stmt = $pdo->query("SELECT * FROM settings_calendar WHERE id = 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);

include('navbar.php');

?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Kalender Einstellungen – ANJUMA</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div class="container py-4">

    <h2 class="mb-4">📅 Kalender-Template Einstellungen</h2>

    <?php if (!empty($success)): ?>
        <div class="alert alert-success">
            Einstellungen gespeichert ✅
        </div>
    <?php endif; ?>

    <form method="post">

        <!-- TITEL -->
        <div class="mb-3">
            <label class="form-label fw-bold">Kalender-Titel Template</label>
            <input 
                type="text" 
                name="title_template" 
                class="form-control"
                value="<?= htmlspecialchars($settings['title_template']) ?>"
            >
            <div class="form-text">
                Beispiel: <code>ANJUMA – {{locationtype}} @ {{location}}</code>
            </div>
        </div>

        <!-- BESCHREIBUNG -->
        <div class="mb-3">
            <label class="form-label fw-bold">Kalender-Beschreibung Template</label>
            <textarea 
                name="description_template" 
                rows="8"
                class="form-control"
            ><?= htmlspecialchars($settings['description_template']) ?></textarea>
        </div>

        <!-- HINWEISE -->
        <div class="alert alert-secondary">
            <strong>Verfügbare Platzhalter:</strong><br>
            <code>{{status}}</code>,
            <code>{{localtiontype}}</code>,
            <code>{{location}}</code>,
            <code>{{startzeit}}</code>,
            <code>{{endzeit}}</code>,
            <code>{{gage}}</code>,
            <code>{{desc}}</code>,
            <code>{{creator}}</code>,
            <code>{{last_editor}}</code>,
            <code>{{last_edited}}</code>
        </div>

        <button class="btn btn-primary">
            💾 Speichern
        </button>

    </form>
</div>

</body>
</html>
