<?php 
include ('header.php');
?>


<?php
// Check connection
if ($connect->connect_error) {
    die("Connection failed: " . $connect->connect_error);
}

// Handle deletion if 'delete' button is clicked
if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    // Delete the article from the database
    $delete_sql = "DELETE FROM news WHERE id = ?";
    $stmt = $connect->prepare($delete_sql);
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        echo "<p>Article deleted successfully.</p>";
    } else {
        echo "<p>Error deleting article.</p>";
    }
    $stmt->close();
}

// Select all news articles from the database, ordered by 'created_at' descending (newest first)
$sql = "SELECT * FROM news ORDER BY created_at DESC";  // Make sure 'created_at' is the correct field name
$result = $connect->query($sql);
?>

<div class="container mt-5">
    <h2>All News Articles</h2>
    
    <?php if ($result->num_rows > 0): ?>
        <table class="table table-bordered">
            <thead>
                <tr>
                     <th>Image</th>
                    <th>Category</th>
                    <th>Title</th>
                    <th>Description</th>
                   
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td>
                            <?php if (!empty($row['image'])): ?>
                                <img src="<?php echo $row['image']; ?>" alt="News Image" width="200">
                            <?php else: ?>
                                <img src="https://via.placeholder.com/50" alt="No Image" width="50">
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($row['category']); ?></td>
                        <td><?php echo htmlspecialchars($row['name']); ?></td>
                        <td><?php echo nl2br(substr($row['description'], 0, 80)); ?>...</td>
                     
                        <td>
                            <!-- Delete Button -->
                            <a href="?delete_id=<?php echo $row['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this article?');">Delete</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p>No news found.</p>
    <?php endif; ?>
</div>
