<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Blog Management';

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    if ($auth->hasPermission('can_delete') || $auth->hasRole('super_admin')) {
        $id = (int)$_POST['id'];
        
        $post = $db->fetchOne("SELECT featured_image FROM blog_posts WHERE id = ?", [$id]);
        if ($post && $post['featured_image']) {
            $file_path = BLOG_UPLOAD_DIR . '/' . basename($post['featured_image']);
            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }
        
        $db->execute("DELETE FROM blog_posts WHERE id = ?", [$id]);
        $_SESSION['success'] = "Post deleted successfully";
        header('Location: blog.php');
        exit;
    }
}

// Get posts
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 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>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="fas fa-newspaper"></i> Blog Posts
            <span class="badge bg-primary"><?php echo number_format($total); ?></span>
        </h5>
        <?php if ($auth->hasPermission('can_create') || $auth->hasRole('super_admin')): ?>
        <a href="blog-form.php" class="btn btn-primary">
            <i class="fas fa-plus"></i> New Post
        </a>
        <?php endif; ?>
    </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..." 
                           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>
        
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Title</th>
                        <th>Author</th>
                        <th>Status</th>
                        <th>Views</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($posts as $post): ?>
                    <tr>
                        <td>
                            <img src="../<?php echo htmlspecialchars($post['featured_image'] ?? 'assets/img/placeholder.jpg'); ?>" 
                                 alt="Featured" style="width: 60px; height: 60px; object-fit: cover; border-radius: 8px;">
                        </td>
                        <td>
                            <strong><?php echo htmlspecialchars($post['title']); ?></strong>
                            <br>
                            <small class="text-muted"><?php echo htmlspecialchars($post['category'] ?? 'Uncategorized'); ?></small>
                        </td>
                        <td><?php echo htmlspecialchars($post['author_name']); ?></td>
                        <td>
                            <span class="badge bg-<?php 
                                echo $post['status'] === 'published' ? 'success' : 
                                    ($post['status'] === 'draft' ? 'warning' : 'secondary'); 
                            ?>">
                                <?php echo ucfirst($post['status']); ?>
                            </span>
                        </td>
                        <td><?php echo number_format($post['views']); ?></td>
                        <td><?php echo date('M d, Y', strtotime($post['created_at'])); ?></td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <?php if ($auth->hasPermission('can_edit') || $auth->hasRole('super_admin')): ?>
                                <a href="blog-form.php?id=<?php echo $post['id']; ?>" class="btn btn-outline-success">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php endif; ?>
                                
                                <?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-title="<?php echo htmlspecialchars($post['title']); ?>">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<form method="POST" id="deleteForm" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="id" id="deleteId">
    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
</form>

<script>
    $('.delete-btn').click(function() {
        const id = $(this).data('id');
        const title = $(this).data('title');
        
        Swal.fire({
            title: 'Delete Post?',
            html: `Delete <strong>${title}</strong>?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $('#deleteId').val(id);
                $('#deleteForm').submit();
            }
        });
    });
</script>

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