<?php
// ==========================================
// FILE: admin/blog.php
// ==========================================
/* Blog management page */
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Blog Management';

// Get blog posts
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$page_num = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page_num - 1) * $limit;

$where = [];
$params = [];

if ($search) {
    $where[] = "(title LIKE ? OR content LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status_filter) {
    $where[] = "status = ?";
    $params[] = $status_filter;
}

$where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$count_sql = "SELECT COUNT(*) as total FROM blog_posts $where_sql";
$total = $db->fetchOne($count_sql, $params)['total'];
$total_pages = ceil($total / $limit);

$sql = "SELECT bp.*, CONCAT(u.first_name, ' ', u.last_name) as author_name
        FROM blog_posts bp
        LEFT JOIN users u ON bp.author_id = u.id
        $where_sql
        ORDER BY bp.created_at DESC
        LIMIT $limit OFFSET $offset";

$posts = $db->fetchAll($sql, $params);

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Blog Management</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Blog</li>
        </ol>
    </nav>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-blog"></i> All Posts</h5>
        <a href="blog-form.php" class="btn btn-primary">
            <i class="fas fa-plus"></i> Create New Post
        </a>
    </div>
    
    <div class="card-body">
        <!-- Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-6">
                    <input type="text" name="search" class="form-control" placeholder="Search posts..." 
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="col-md-4">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="draft" <?php echo $status_filter === 'draft' ? 'selected' : ''; ?>>Draft</option>
                        <option value="published" <?php echo $status_filter === 'published' ? 'selected' : ''; ?>>Published</option>
                        <option value="archived" <?php echo $status_filter === 'archived' ? 'selected' : ''; ?>>Archived</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </div>
            </div>
        </form>
        
        <!-- Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Title</th>
                        <th>Author</th>
                        <th>Category</th>
                        <th>Status</th>
                        <th>Views</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($posts)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4">
                            <i class="fas fa-inbox fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No posts found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($posts as $post): ?>
                        <tr>
                            <td>
                                <img src="../<?php echo htmlspecialchars($post['featured_image'] ?? 'placeholder.jpg'); ?>" 
                                     alt="Post" class="rounded" style="width: 60px; height: 60px; object-fit: cover;">
                            </td>
                            <td>
                                <strong><?php echo htmlspecialchars($post['title']); ?></strong>
                                <br>
                                <small class="text-muted"><?php echo htmlspecialchars(substr($post['excerpt'] ?? '', 0, 60)); ?>...</small>
                            </td>
                            <td><?php echo htmlspecialchars($post['author_name']); ?></td>
                            <td><?php echo htmlspecialchars($post['category'] ?? 'Uncategorized'); ?></td>
                            <td>
                                <?php
                                $badge_class = [
                                    'draft' => 'secondary',
                                    'published' => 'success',
                                    'archived' => 'warning'
                                ][$post['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $badge_class; ?>">
                                    <?php echo ucfirst($post['status']); ?>
                                </span>
                            </td>
                            <td><i class="fas fa-eye"></i> <?php echo number_format($post['views']); ?></td>
                            <td>
                                <?php echo date('M d, Y', strtotime($post['created_at'])); ?>
                                <?php if ($post['status'] === 'published' && $post['published_at']): ?>
                                <br><small class="text-muted">Published: <?php echo date('M d', strtotime($post['published_at'])); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="../blog-details.php?slug=<?php echo $post['slug']; ?>" 
                                       class="btn btn-outline-primary" target="_blank" data-bs-toggle="tooltip" title="View">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="blog-form.php?id=<?php echo $post['id']; ?>" 
                                       class="btn btn-outline-success" data-bs-toggle="tooltip" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php if ($auth->hasPermission('can_delete') || $auth->hasRole('super_admin')): ?>
                                    <button type="button" class="btn btn-outline-danger delete-btn" 
                                            data-id="<?php echo $post['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($post['title']); ?>">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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