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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $slug = $_POST['slug'] ?? '';
    $image_url = $_POST['image_url'] ?? '';
    $link_url = $_POST['link_url'] ?? '';
    $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 resources SET title=?, slug=?, image_url=?, link_url=?, sort_order=? WHERE id=?");
                $stmt->execute([$title, $slug, $image_url, $link_url, $sort_order, $id]);
                $message = 'Resource updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO resources (title, slug, image_url, link_url, sort_order) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$title, $slug, $image_url, $link_url, $sort_order]);
                $message = 'Resource added successfully.';
            }
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'duplicate') !== false || strpos($e->getMessage(), '23505') !== false) {
                $message = 'Error: A resource with that slug already exists. Please use a different slug.';
            } else {
                $message = 'Database error: ' . htmlspecialchars($e->getMessage());
            }
        }
    }
}

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

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

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

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

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

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