<?php
$db = getDB();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $slug = $_POST['slug'] ?? '';
    $short_description = $_POST['short_description'] ?? '';
    $description = $_POST['description'] ?? '';
    $objectives = $_POST['objectives'] ?? '';
    $syllabus = $_POST['syllabus'] ?? '';
    $image_url = $_POST['image_url'] ?? '';
    $duration = $_POST['duration'] ?? '';
    $price = $_POST['price'] ?? '';
    $location = $_POST['location'] ?? '';
    $max_participants = (int)($_POST['max_participants'] ?? 30);
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $id = $_POST['id'] ?? '';

    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        if (!$slug) {
            $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $title));
        }

        try {
            if ($id) {
                $stmt = $db->prepare("UPDATE workshops SET title=?, slug=?, short_description=?, description=?, objectives=?, syllabus=?, image_url=?, duration=?, price=?, location=?, max_participants=?, sort_order=? WHERE id=?");
                $stmt->execute([$title, $slug, $short_description, $description, $objectives, $syllabus, $image_url, $duration, $price, $location, $max_participants, $sort_order, $id]);
                $message = 'Workshop updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO workshops (title, slug, short_description, description, objectives, syllabus, image_url, duration, price, location, max_participants, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$title, $slug, $short_description, $description, $objectives, $syllabus, $image_url, $duration, $price, $location, $max_participants, $sort_order]);
                $message = 'Workshop added successfully.';
            }
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'duplicate') !== false || strpos($e->getMessage(), '23505') !== false) {
                $message = 'Error: A workshop with that slug already exists. Please use a different slug.';
            } else {
                $message = 'Database error: ' . htmlspecialchars($e->getMessage());
            }
        }
    }
}

$workshops = $db->query("SELECT * FROM workshops ORDER BY sort_order ASC")->fetchAll();
$editWorkshop = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM workshops WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editWorkshop = $stmt->fetch();
}

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2>Manage Workshops</h2>
</div>

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

<div class="admin-card">
    <h3><?= $editWorkshop ? 'Edit Workshop' : 'Add New Workshop' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <?php if ($editWorkshop): ?>
        <input type="hidden" name="id" value="<?= $editWorkshop['id'] ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>Title</label>
            <input type="text" name="title" value="<?= htmlspecialchars($editWorkshop['title'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Slug (URL-friendly name, auto-generated if blank)</label>
            <input type="text" name="slug" value="<?= htmlspecialchars($editWorkshop['slug'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Short Description</label>
            <input type="text" name="short_description" value="<?= htmlspecialchars($editWorkshop['short_description'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Description</label>
            <textarea name="description" rows="5"><?= htmlspecialchars($editWorkshop['description'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Objectives</label>
            <textarea name="objectives" rows="4"><?= htmlspecialchars($editWorkshop['objectives'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Syllabus</label>
            <textarea name="syllabus" rows="4"><?= htmlspecialchars($editWorkshop['syllabus'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Image URL</label>
            <input type="url" name="image_url" value="<?= htmlspecialchars($editWorkshop['image_url'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Duration</label>
            <input type="text" name="duration" value="<?= htmlspecialchars($editWorkshop['duration'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Price</label>
            <input type="text" name="price" value="<?= htmlspecialchars($editWorkshop['price'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Location</label>
            <input type="text" name="location" value="<?= htmlspecialchars($editWorkshop['location'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Max Participants</label>
            <input type="number" name="max_participants" value="<?= htmlspecialchars($editWorkshop['max_participants'] ?? '30') ?>">
        </div>
        <div class="form-group">
            <label>Sort Order</label>
            <input type="number" name="sort_order" value="<?= htmlspecialchars($editWorkshop['sort_order'] ?? '0') ?>">
        </div>
        <button type="submit" class="btn-sm btn-sm-primary"><?= $editWorkshop ? 'Update' : 'Add' ?> Workshop</button>
        <?php if ($editWorkshop): ?>
        <a href="/admin/workshops" class="btn-sm btn-sm-success">Cancel</a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card">
    <h3>All Workshops</h3>
    <table>
        <thead>
            <tr><th>Title</th><th>Duration</th><th>Price</th><th>Location</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($workshops as $w): ?>
            <tr>
                <td><?= htmlspecialchars($w['title']) ?></td>
                <td><?= htmlspecialchars($w['duration']) ?></td>
                <td><?= htmlspecialchars($w['price']) ?></td>
                <td><?= htmlspecialchars($w['location']) ?></td>
                <td class="actions">
                    <a href="/admin/workshops?edit=<?= $w['id'] ?>" class="btn-sm btn-sm-primary">Edit</a>
                    <form method="post" action="/admin/delete" style="display:inline" onsubmit="return confirm('Are you sure?')"><input type="hidden" name="type" value="workshops"><input type="hidden" name="delete_id" value="<?= $w['id'] ?>"><?= csrfField() ?><button type="submit" class="btn-sm btn-sm-danger">Delete</button></form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include __DIR__ . '/admin_footer.php'; ?>
