<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';


// --- Page-Specific Logic Starts Here ---

// 2. HANDLE DELETE ACTION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_article') {
    $article_id = filter_input(INPUT_POST, 'article_id', FILTER_VALIDATE_INT);
    if ($article_id) {
        // You might want to also delete the associated image file from the server here
        $stmt = $conn->prepare("DELETE FROM articles WHERE id = ?");
        $stmt->bind_param("i", $article_id);
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Article deleted successfully.";
        } else {
            $_SESSION['error_message'] = "Error deleting article.";
        }
        $stmt->close();
    }
    header("Location: manage-articles.php");
    exit();
}

// 3. FETCH ARTICLES FOR DISPLAY
$records_per_page = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

$where_clauses = []; $params = []; $types = '';

// Search by title
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "title LIKE ?";
    $like_term = "%{$search_term}%";
    $params[] = $like_term;
    $types .= 's';
}

// Filter by status
$status_filter = $_GET['status'] ?? '';
if ($status_filter === 'published') {
    $where_clauses[] = "is_published = 1";
} elseif ($status_filter === 'draft') {
    $where_clauses[] = "is_published = 0";
}

$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(' AND ', $where_clauses) : '';

// Count for pagination
$count_sql = "SELECT COUNT(id) as total FROM articles $where_sql";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

// Fetch articles for display
$fetch_sql = "SELECT id, title, publish_date, is_published, view_count, like_count FROM articles $where_sql ORDER BY publish_date DESC LIMIT ? OFFSET ?";
$params[] = $records_per_page; $params[] = $offset; $types .= 'ii';
$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$articles_result = $stmt_fetch->get_result();


// 4. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<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">Manage Articles</h1>
    <a href="edit-article.php" class="btn btn-primary">
        <i class="bi bi-pencil-square me-1"></i> Write New Article
    </a>
</div>

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter Articles</div>
    <div class="card-body">
        <form action="manage-articles.php" method="GET" class="row g-3">
            <div class="col-md-6"><input type="text" name="search" class="form-control" placeholder="Search by title..." value="<?php echo htmlspecialchars($search_term); ?>"></div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">All Statuses</option>
                    <option value="published" <?php if($status_filter == 'published') echo 'selected'; ?>>Published</option>
                    <option value="draft" <?php if($status_filter == 'draft') echo 'selected'; ?>>Draft</option>
                </select>
            </div>
            <div class="col-md-3 d-grid d-md-flex gap-2"><button type="submit" class="btn btn-primary flex-grow-1">Filter</button><a href="manage-articles.php" class="btn btn-secondary flex-grow-1">Clear</a></div>
        </form>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover">
        <thead class="table-dark align-middle">
            <tr>
                <th>Title</th>
                <th>Publish Date</th>
                <th class="text-center">Status</th>
                <th class="text-center">Stats</th>
                <th class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($articles_result->num_rows > 0): while ($article = $articles_result->fetch_assoc()): ?>
            <tr>
                <td class="fw-bold"><?php echo htmlspecialchars($article['title']); ?></td>
                <td><?php echo date('M d, Y', strtotime($article['publish_date'])); ?></td>
                <td class="text-center">
                    <?php if ($article['is_published']): ?>
                        <span class="badge bg-success">Published</span>
                    <?php else: ?>
                        <span class="badge bg-secondary">Draft</span>
                    <?php endif; ?>
                </td>
                <td class="text-center">
                    <span class="badge bg-light text-dark" title="Views"><i class="bi bi-eye-fill"></i> <?php echo $article['view_count'] ?? 0; ?></span>
                    <span class="badge bg-light text-dark" title="Likes"><i class="bi bi-heart-fill"></i> <?php echo $article['like_count'] ?? 0; ?></span>
                </td>
                <td class="text-end">
                    <div class="d-inline-flex gap-1">
                        <a href="../article-details.php?id=<?php echo $article['id']; ?>" class="btn btn-sm btn-outline-primary" title="View Live Article" target="_blank"><i class="bi bi-box-arrow-up-right"></i></a>
                        <a href="edit-article.php?id=<?php echo $article['id']; ?>" class="btn btn-sm btn-warning" title="Edit"><i class="bi bi-pencil-fill"></i></a>
                        <form method="POST" action="manage-articles.php" onsubmit="return confirm('Are you sure you want to delete this article?');">
                            <input type="hidden" name="action" value="delete_article">
                            <input type="hidden" name="article_id" value="<?php echo $article['id']; ?>">
                            <button type="submit" class="btn btn-sm btn-danger" title="Delete"><i class="bi bi-trash-fill"></i></button>
                        </form>
                    </div>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="5" class="text-center p-4">No articles found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if($total_pages > 1): ?>
<nav><ul class="pagination justify-content-center mt-4">
    <?php $query_params = $_GET; for ($i = 1; $i <= $total_pages; $i++): $query_params['page'] = $i; ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a></li>
    <?php endfor; ?>
</ul></nav>
<?php endif; ?>

<?php include 'admin-footer.php'; ?>
