<?php
/**
 * CMS - Blog Posts Management
 * List, create, edit, and delete blog posts
 */

require_once '../config/config.php';
requireLogin();
requireAdmin();

$pageTitle = 'Blog Posts Management';
$success = '';
$error = '';

$db = getDB();

// Handle delete action
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    validateCSRF();
    
    $postId = (int)$_GET['id'];
    
    try {
        $stmt = $db->prepare("DELETE FROM cms_posts WHERE id = ?");
        $stmt->execute([$postId]);
        
        $success = 'Blog post deleted successfully.';
        logAudit($_SESSION['user_id'], 'delete', 'cms_posts', $postId, 'Deleted blog post');
    } catch (PDOException $e) {
        $error = 'Error deleting post: ' . $e->getMessage();
    }
}

// Handle status change
if (isset($_GET['action']) && $_GET['action'] === 'toggle_status' && isset($_GET['id'])) {
    validateCSRF();
    
    $postId = (int)$_GET['id'];
    
    try {
        // Get current status
        $stmt = $db->prepare("SELECT status FROM cms_posts WHERE id = ?");
        $stmt->execute([$postId]);
        $currentStatus = $stmt->fetchColumn();
        
        // Toggle status
        $newStatus = ($currentStatus === 'published') ? 'draft' : 'published';
        
        $stmt = $db->prepare("UPDATE cms_posts SET status = ? WHERE id = ?");
        $stmt->execute([$newStatus, $postId]);
        
        $success = "Post status changed to: $newStatus";
        logAudit($_SESSION['user_id'], 'update', 'cms_posts', $postId, "Changed status to $newStatus");
    } catch (PDOException $e) {
        $error = 'Error updating status: ' . $e->getMessage();
    }
}

// Get filter parameters
$statusFilter = $_GET['status'] ?? 'all';
$searchQuery = $_GET['search'] ?? '';

// Build query
$sql = "SELECT p.*, u.first_name, u.last_name
        FROM cms_posts p
        LEFT JOIN users u ON p.author_id = u.id
        WHERE 1=1";

$params = [];

if ($statusFilter !== 'all') {
    $sql .= " AND p.status = ?";
    $params[] = $statusFilter;
}

if (!empty($searchQuery)) {
    $sql .= " AND (p.title LIKE ? OR p.content LIKE ?)";
    $params[] = "%$searchQuery%";
    $params[] = "%$searchQuery%";
}

$sql .= " ORDER BY p.created_at DESC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$posts = $stmt->fetchAll();

// Get statistics
$stmt = $db->query("SELECT COUNT(*) FROM cms_posts WHERE status = 'published'");
$publishedCount = $stmt->fetchColumn();

$stmt = $db->query("SELECT COUNT(*) FROM cms_posts WHERE status = 'draft'");
$draftCount = $stmt->fetchColumn();

$stmt = $db->query("SELECT COUNT(*) FROM cms_posts");
$totalCount = $stmt->fetchColumn();

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4" style="margin-top: 56px;">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2"><i class="fas fa-newspaper"></i> Blog Posts Management</h1>
                <div class="btn-toolbar">
                    <a href="cms-posts-edit.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> New Post
                    </a>
                </div>
            </div>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="card border-left-success shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                        Published Posts
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $publishedCount; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-left-warning shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                        Draft Posts
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $draftCount; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-edit fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-left-primary shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                        Total Posts
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $totalCount; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-newspaper fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Filters -->
            <div class="card shadow mb-4">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">Status Filter</label>
                            <select name="status" class="form-select">
                                <option value="all" <?php echo $statusFilter === 'all' ? 'selected' : ''; ?>>All Posts</option>
                                <option value="published" <?php echo $statusFilter === 'published' ? 'selected' : ''; ?>>Published</option>
                                <option value="draft" <?php echo $statusFilter === 'draft' ? 'selected' : ''; ?>>Draft</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Search</label>
                            <input type="text" name="search" class="form-control" placeholder="Search posts..." 
                                   value="<?php echo e($searchQuery); ?>">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-search"></i> Filter
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Posts Table -->
            <div class="card shadow">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">Blog Posts</h6>
                </div>
                <div class="card-body">
                    <?php if (empty($posts)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-newspaper fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No blog posts found. Create your first post!</p>
                            <a href="cms-posts-edit.php" class="btn btn-primary">
                                <i class="fas fa-plus"></i> Create Post
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Title</th>
                                        <th>Author</th>
                                        <th>Status</th>
                                        <th>Published Date</th>
                                        <th>Views</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($posts as $post): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo e($post['title']); ?></strong>
                                            <?php if ($post['featured']): ?>
                                                <span class="badge bg-warning">Featured</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo e($post['first_name'] . ' ' . $post['last_name']); ?></td>
                                        <td>
                                            <span class="badge bg-<?php echo $post['status'] === 'published' ? 'success' : 'warning'; ?>">
                                                <?php echo ucfirst($post['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($post['published_at']): ?>
                                                <?php echo date('M d, Y', strtotime($post['published_at'])); ?>
                                            <?php else: ?>
                                                <span class="text-muted">Not published</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo number_format($post['views']); ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="cms-posts-edit.php?id=<?php echo $post['id']; ?>" 
                                                   class="btn btn-outline-primary" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="?action=toggle_status&id=<?php echo $post['id']; ?>&csrf_token=<?php echo $_SESSION['csrf_token']; ?>" 
                                                   class="btn btn-outline-info" 
                                                   title="Toggle Status"
                                                   onclick="return confirm('Change post status?')">
                                                    <i class="fas fa-toggle-on"></i>
                                                </a>
                                                <?php if ($post['status'] === 'published'): ?>
                                                <a href="../public/post.php?slug=<?php echo $post['slug']; ?>" 
                                                   class="btn btn-outline-success" 
                                                   title="View Post" 
                                                   target="_blank">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <?php endif; ?>
                                                <a href="?action=delete&id=<?php echo $post['id']; ?>&csrf_token=<?php echo $_SESSION['csrf_token']; ?>" 
                                                   class="btn btn-outline-danger" 
                                                   title="Delete"
                                                   onclick="return confirm('Are you sure you want to delete this post?')">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<style>
.border-left-primary {
    border-left: 0.25rem solid #4e73df !important;
}

.border-left-success {
    border-left: 0.25rem solid #1cc88a !important;
}

.border-left-warning {
    border-left: 0.25rem solid #f6c23e !important;
}
</style>

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