<?php
require_once 'config/db.php';
require_once 'includes/header.php';

// Handle Delete Blog Post
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        // First get the image path so we can delete the file from the server
        $stmt = $pdo->prepare("SELECT image_path FROM blog_posts WHERE id = ?");
        $stmt->execute([$id]);
        $post = $stmt->fetch();
        
        if ($post && !empty($post['image_path'])) {
            $filepath = "../" . $post['image_path'];
            if (file_exists($filepath)) {
                unlink($filepath);
            }
        }
        
        // Now delete the record
        $stmt = $pdo->prepare("DELETE FROM blog_posts WHERE id = ?");
        $stmt->execute([$id]);
        $success = "Blog post deleted successfully.";
    } catch (PDOException $e) {
        $error = "Error deleting blog post: " . $e->getMessage();
    }
}

// Fetch all blog posts with category and subcategory names
$query = "
    SELECT p.*, c.name as category_name, s.name as subcategory_name 
    FROM blog_posts p
    LEFT JOIN blog_categories c ON p.category_id = c.id
    LEFT JOIN blog_subcategories s ON p.subcategory_id = s.id
    ORDER BY p.created_at DESC
";
$stmt = $pdo->query($query);
$posts = $stmt->fetchAll();
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px; display: flex; justify-content: space-between; align-items: center;">
        <div>
            <h2><i class="fa-solid fa-newspaper"></i> Blog Posts</h2>
            <p>Draft, publish, and manage all your articles.</p>
        </div>
        <div>
            <a href="blog_add.php" class="logout-btn" style="background: var(--white); color: var(--primary); text-decoration: none; font-weight: 600; display: inline-block;">
                <i class="fa-solid fa-plus"></i> Write New Post
            </a>
        </div>
    </div>

    <?php 
    if (isset($_SESSION['success_msg'])) {
        echo '<div class="badge badge-completed" style="display:block; padding:15px; margin-bottom: 20px; font-size:1rem;">' . htmlspecialchars($_SESSION['success_msg']) . '</div>';
        unset($_SESSION['success_msg']);
    }
    ?>
    
    <?php if (isset($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:15px; margin-bottom: 20px; font-size:1rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="badge badge-pending" style="display:block; padding:15px; margin-bottom: 20px; background-color: #fee2e2; color: #ef4444; font-size:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="recent-activity">
        <div class="table-responsive">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Cover</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th>Status</th>
                        <th>Date Published</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($posts) > 0): ?>
                        <?php foreach ($posts as $post): ?>
                            <tr>
                                <td>
                                    <?php if (!empty($post['image_path'])): ?>
                                        <img src="../<?= htmlspecialchars($post['image_path']) ?>" alt="Cover" style="width: 60px; height: 60px; object-fit: cover; border-radius: 6px;">
                                    <?php else: ?>
                                        <div style="width: 60px; height: 60px; background: #e2e8f0; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: #94a3b8;"><i class="fa-solid fa-image"></i></div>
                                    <?php endif; ?>
                                </td>
                                <td style="font-weight:600;">
                                    <?= htmlspecialchars($post['title']) ?><br>
                                    <small style="color:#94a3b8; font-weight:normal;">By <?= htmlspecialchars($post['author'] ?? 'Admin') ?></small>
                                </td>
                                <td>
                                    <?= htmlspecialchars($post['category_name']) ?>
                                    <?php if (!empty($post['subcategory_name'])): ?>
                                        <br><small style="color:#64748b;">> <?= htmlspecialchars($post['subcategory_name']) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if($post['status'] == 'published'): ?>
                                        <span class="badge badge-completed">Published</span>
                                    <?php else: ?>
                                        <span class="badge badge-pending" style="background:rgba(148, 163, 184, 0.2); color:#64748b;">Draft</span>
                                    <?php endif; ?>
                                </td>
                                <td style="color:#64748b; font-size: 0.9rem;">
                                    <?= $post['published_at'] ? date('M d, Y', strtotime($post['published_at'])) : '-' ?>
                                </td>
                                <td>
                                    <a href="blog_edit.php?id=<?= $post['id'] ?>" style="color:var(--primary); margin-right:10px;"><i class="fa-solid fa-pen-to-square"></i></a>
                                    <a href="blog_posts.php?delete=<?= $post['id'] ?>" onclick="return confirm('Are you sure you want to delete this blog post? The associated cover image will also be removed.');" style="color:var(--danger);"><i class="fa-solid fa-trash"></i></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" style="text-align: center; color: #94a3b8; padding: 40px 20px;">
                                <i class="fa-solid fa-newspaper" style="font-size: 2rem; margin-bottom: 15px; color: #cbd5e1; display: block;"></i>
                                No blog posts found. Click "Write New Post" to start.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
