<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/functions.php';

requireLogin();

$pdo = getDB();

// Handle delete action
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $pdo->prepare("DELETE FROM posts WHERE id = ?");
    if ($stmt->execute([$id])) {
        header('Location: posts.php?deleted=1');
        exit;
    }
}

// Get filter parameters
$category_filter = $_GET['category'] ?? '';
$status_filter = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Build query with filters
$sql = "SELECT p.*, c.name as category_name, COALESCE(p.manual_author_name, u.username) as author_name
        FROM posts p
        LEFT JOIN categories c ON p.category_id = c.id
        LEFT JOIN users u ON p.author_id = u.id
        WHERE 1=1";

$params = [];

if ($category_filter) {
    $sql .= " AND p.category_id = ?";
    $params[] = $category_filter;
}

if ($status_filter) {
    $sql .= " AND p.status = ?";
    $params[] = $status_filter;
}

if ($date_from) {
    $sql .= " AND DATE(p.created_at) >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $sql .= " AND DATE(p.created_at) <= ?";
    $params[] = $date_to;
}

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

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

// Get categories for filter dropdown
$categories = getCategories();

$page_title = 'Manage Posts';
include 'includes/admin_header.php';
?>

<?php if (isset($_GET['created'])): ?>
    <div class="alert alert-success">
        Post created successfully!
    </div>
<?php endif; ?>

<?php if (isset($_GET['updated'])): ?>
    <div class="alert alert-success">
        Post updated successfully!
    </div>
<?php endif; ?>

<?php if (isset($_GET['deleted'])): ?>
    <div class="alert alert-success">
        Post deleted successfully!
    </div>
<?php endif; ?>

<div class="posts-header">
    <h2>All Posts</h2>
    <a href="add_post.php" class="btn btn-primary">
        <i class="fas fa-plus"></i> Add New Post
    </a>
</div>

<!-- Filter Form -->
<div class="filter-section">
    <form method="GET" class="filter-form">
        <div class="filter-row">
            <div class="filter-group">
                <label for="category">Category:</label>
                <select name="category" id="category">
                    <option value="">All Categories</option>
                    <?php foreach ($categories as $category): ?>
                        <option value="<?php echo $category['id']; ?>" <?php echo $category_filter == $category['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($category['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="filter-group">
                <label for="status">Status:</label>
                <select name="status" id="status">
                    <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>
                </select>
            </div>

            <div class="filter-group">
                <label for="date_from">From Date:</label>
                <input type="date" name="date_from" id="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
            </div>

            <div class="filter-group">
                <label for="date_to">To Date:</label>
                <input type="date" name="date_to" id="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
            </div>

            <div class="filter-actions">
                <button type="submit" class="btn btn-primary btn-sm">
                    <i class="fas fa-filter"></i> Filter
                </button>
                <a href="posts.php" class="btn btn-secondary btn-sm">
                    <i class="fas fa-times"></i> Clear
                </a>
            </div>
        </div>
    </form>
</div>

<div class="posts-table-wrapper">
    <table class="posts-table">
        <thead>
            <tr>
                <th>Title</th>
                <th>Category</th>
                <th>Author</th>
                <th>Status</th>
                <th>Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($posts as $post): ?>
                <tr>
                    <td>
                        <strong><?php echo htmlspecialchars($post['title']); ?></strong>
                    </td>
                    <td>
                        <span class="category-badge">
                            <?php echo htmlspecialchars($post['category_name'] ?? 'Uncategorized'); ?>
                        </span>
                    </td>
                    <td><?php echo htmlspecialchars($post['author_name']); ?></td>
                    <td>
                        <span class="status-badge status-<?php echo $post['status']; ?>">
                            <?php echo ucfirst($post['status']); ?>
                        </span>
                    </td>
                    <td><?php echo formatDate($post['created_at']); ?></td>
                    <td class="actions" style="white-space: nowrap;">
                        <a href="edit_post.php?id=<?php echo $post['id']; ?>" class="btn btn-sm" style="padding: 2px 4px; font-size: 11px; line-height: 1;" title="Edit">
                            <i class="fas fa-edit" style="font-size: 12px; width: 12px; height: 12px;"></i>
                        </a>
                        <?php if ($post['status'] == 'published'): ?>
                            <a href="../post.php?slug=<?php echo urlencode($post['slug']); ?>" class="btn btn-sm btn-secondary" style="padding: 2px 4px; font-size: 11px; line-height: 1;" target="_blank" title="View">
                                <i class="fas fa-eye" style="font-size: 12px; width: 12px; height: 12px;"></i>
                            </a>
                        <?php endif; ?>
                        <a href="?action=delete&id=<?php echo $post['id']; ?>" class="btn btn-sm btn-danger" style="padding: 2px 4px; font-size: 11px; line-height: 1;" onclick="return confirm('Are you sure you want to delete this post?')" title="Delete">
                            <i class="fas fa-trash" style="font-size: 12px; width: 12px; height: 12px;"></i>
                        </a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php if (empty($posts)): ?>
    <div class="no-posts">
        <i class="fas fa-newspaper"></i>
        <p>No posts found. <a href="add_post.php">Create your first post</a></p>
    </div>
<?php endif; ?>

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