<?php
require 'auth_check.php';
require '../config/db.php';

// Delete Post
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $pdo->prepare("DELETE FROM posts WHERE id = ?")->execute([$id]);
    header("Location: blog.php?msg=deleted");
    exit();
}

// Fetch Posts
$posts = $pdo->query("SELECT * FROM posts ORDER BY created_at DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Blog</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>

    <div class="sidebar">
        <?php include 'sidebar.php'; ?>
    </div>>

    <div class="content">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h1>Blog Posts</h1>
            <a href="blog_editor.php" class="btn btn-primary" style="background: #8e44ad;"><i class="fas fa-pen"></i> Write New Article</a>
        </div>

        <?php if(isset($_GET['msg']) && $_GET['msg']=='deleted'): ?>
            <div style="padding: 10px; background: #d4edda; color: #155724; border-radius: 5px; margin-bottom: 20px;">Post deleted successfully.</div>
        <?php endif; ?>

        <table style="background: white;">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Views</th>
                    <th>Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($posts as $p): ?>
                <tr>
                    <td>#<?php echo $p['id']; ?></td>
                    <td>
                        <strong><?php echo htmlspecialchars($p['title']); ?></strong><br>
                        <small style="color: #777;">/post/<?php echo $p['slug']; ?></small>
                    </td>
                    <td><?php echo $p['views']; ?></td>
                    <td><?php echo date('d M Y', strtotime($p['created_at'])); ?></td>
                    <td>
                        <a href="blog_editor.php?edit=<?php echo $p['id']; ?>" class="btn btn-primary" style="padding: 5px 10px; font-size: 12px;">Edit</a>
                        <a href="blog.php?delete=<?php echo $p['id']; ?>" class="btn btn-primary" style="background: #c0392b; padding: 5px 10px; font-size: 12px;" onclick="return confirm('Delete this post?')">Delete</a>
                        <a href="../post.php?slug=<?php echo $p['slug']; ?>" target="_blank" style="margin-left: 5px; font-size: 14px; color: #3498db;"><i class="fas fa-external-link-alt"></i></a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

</body>
</html>