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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $image_url = $_POST['image_url'] ?? '';
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $id = $_POST['id'] ?? '';

    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        try {
            if ($id) {
                $stmt = $db->prepare("UPDATE facilities SET title=?, image_url=?, sort_order=? WHERE id=?");
                $stmt->execute([$title, $image_url, $sort_order, $id]);
                $message = 'Facility updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO facilities (title, image_url, sort_order) VALUES (?, ?, ?)");
                $stmt->execute([$title, $image_url, $sort_order]);
                $message = 'Facility added successfully.';
            }
        } catch (PDOException $e) {
            $message = 'Database error: ' . htmlspecialchars($e->getMessage());
        }
    }
}

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

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

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

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

<div class="admin-card">
    <h3><?= $editFac ? 'Edit Facility' : 'Add New Facility' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <?php if ($editFac): ?>
        <input type="hidden" name="id" value="<?= $editFac['id'] ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>Equipment Name</label>
            <input type="text" name="title" value="<?= htmlspecialchars($editFac['title'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Image URL</label>
            <input type="url" name="image_url" value="<?= htmlspecialchars($editFac['image_url'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Sort Order</label>
            <input type="number" name="sort_order" value="<?= htmlspecialchars($editFac['sort_order'] ?? '0') ?>">
        </div>
        <button type="submit" class="btn-sm btn-sm-primary"><?= $editFac ? 'Update' : 'Add' ?> Facility</button>
        <?php if ($editFac): ?>
        <a href="/admin/facilities" class="btn-sm btn-sm-success">Cancel</a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card">
    <h3>All Facilities</h3>
    <table>
        <thead>
            <tr><th>Image</th><th>Equipment Name</th><th>Order</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($facilities as $f): ?>
            <tr>
                <td><img src="<?= htmlspecialchars($f['image_url']) ?>" class="admin-img-preview"></td>
                <td><?= htmlspecialchars($f['title'] ?? 'N/A') ?></td>
                <td><?= $f['sort_order'] ?></td>
                <td class="actions">
                    <a href="/admin/facilities?edit=<?= $f['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="facilities"><input type="hidden" name="delete_id" value="<?= $f['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'; ?>
