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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $page_path = $_POST['page_path'] ?? '';
    $meta_title = $_POST['meta_title'] ?? '';
    $meta_description = $_POST['meta_description'] ?? '';
    $meta_keywords = $_POST['meta_keywords'] ?? '';
    $og_image = $_POST['og_image'] ?? '';
    $id = $_POST['id'] ?? '';

    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        try {
            if ($id) {
                $stmt = $db->prepare("UPDATE seo_metadata SET page_path=?, meta_title=?, meta_description=?, meta_keywords=?, og_image=?, updated_at=CURRENT_TIMESTAMP WHERE id=?");
                $stmt->execute([$page_path, $meta_title, $meta_description, $meta_keywords, $og_image, $id]);
                $message = 'SEO metadata updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO seo_metadata (page_path, meta_title, meta_description, meta_keywords, og_image) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$page_path, $meta_title, $meta_description, $meta_keywords, $og_image]);
                $message = 'SEO metadata added successfully.';
            }
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'duplicate') !== false || strpos($e->getMessage(), '23505') !== false) {
                $message = 'Error: SEO metadata for that page path already exists.';
            } else {
                $message = 'Database error: ' . htmlspecialchars($e->getMessage());
            }
        }
    }
}

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

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

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

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

<div class="admin-card">
    <h3><?= $editSeo ? 'Edit SEO Entry' : 'Add New SEO Entry' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <?php if ($editSeo): ?>
        <input type="hidden" name="id" value="<?= $editSeo['id'] ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>Page Path (e.g. /about, /services)</label>
            <input type="text" name="page_path" value="<?= htmlspecialchars($editSeo['page_path'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Meta Title</label>
            <input type="text" name="meta_title" value="<?= htmlspecialchars($editSeo['meta_title'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Meta Description</label>
            <textarea name="meta_description" rows="3"><?= htmlspecialchars($editSeo['meta_description'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Meta Keywords</label>
            <input type="text" name="meta_keywords" value="<?= htmlspecialchars($editSeo['meta_keywords'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>OG Image URL</label>
            <input type="url" name="og_image" value="<?= htmlspecialchars($editSeo['og_image'] ?? '') ?>">
        </div>
        <button type="submit" class="btn-sm btn-sm-primary"><?= $editSeo ? 'Update' : 'Add' ?> SEO Entry</button>
        <?php if ($editSeo): ?>
        <a href="/admin/seo" class="btn-sm btn-sm-success">Cancel</a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card">
    <h3>All SEO Entries</h3>
    <table>
        <thead>
            <tr><th>Page Path</th><th>Meta Title</th><th>Meta Description</th><th>Keywords</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($seoEntries as $s): ?>
            <tr>
                <td><?= htmlspecialchars($s['page_path']) ?></td>
                <td><?= htmlspecialchars($s['meta_title'] ?? '') ?></td>
                <td><?= htmlspecialchars(substr($s['meta_description'] ?? '', 0, 80)) ?></td>
                <td><?= htmlspecialchars(substr($s['meta_keywords'] ?? '', 0, 50)) ?></td>
                <td class="actions">
                    <a href="/admin/seo?edit=<?= $s['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="seo_metadata"><input type="hidden" name="delete_id" value="<?= $s['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'; ?>
