<?php
session_start();

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Include the database connection
require 'db_connection.php';

// Handle delete action
if (isset($_GET['delete_id'])) {
    $deleteId = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM articles WHERE id = ?");
    $stmt->bind_param('i', $deleteId);

    if ($stmt->execute()) {
        echo "Article deleted successfully.";
    } else {
        echo "Error deleting article: " . $stmt->error;
    }
}

// Handle edit form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['article_id'])) {
    $articleId = intval($_POST['article_id']);
    $title = htmlspecialchars($_POST['title']);
    $details = htmlspecialchars($_POST['details']);
    $url = !empty($_POST['url']) ? htmlspecialchars($_POST['url']) : null;

    // Handle file uploads (optional for editing)
    $stmt = $conn->prepare("SELECT images FROM articles WHERE id = ?");
    $stmt->bind_param('i', $articleId);
    $stmt->execute();
    $result = $stmt->get_result();
    $existingImages = json_decode($result->fetch_assoc()['images'], true) ?? [];

    $imagePaths = $existingImages; // Preserve existing images
    if (isset($_FILES['images']['tmp_name'][0]) && $_FILES['images']['error'][0] === UPLOAD_ERR_OK) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmpName) {
            if ($_FILES['images']['size'][$key] > 0) {
                $imageName = basename($_FILES['images']['name'][$key]);
                $imagePath = 'uploads/' . uniqid() . '_' . $imageName;
                move_uploaded_file($tmpName, $imagePath);
                $imagePaths[] = $imagePath;
            }
        }
    }

    // Update the article
    $stmt = $conn->prepare("UPDATE articles SET title = ?, details = ?, url = ?, images = ? WHERE id = ?");
    $stmt->bind_param(
        'ssssi',
        $title,
        $details,
        $url,
        json_encode($imagePaths),
        $articleId
    );

    if ($stmt->execute()) {
        echo "Article updated successfully.";
    } else {
        echo "Error updating article: " . $stmt->error;
    }
}

// Fetch all articles
$result = $conn->query("SELECT * FROM articles");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Articles</title>
</head>
<body>
    <h1>Manage Articles</h1>

    <!-- List Articles -->
    <h2>Articles</h2>
    <?php if ($result->num_rows > 0): ?>
        <table border="1">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Details</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($article = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?= htmlspecialchars($article['title']) ?></td>
                        <td><?= htmlspecialchars($article['details']) ?></td>
                        <td>
                            <a href="?edit_id=<?= $article['id'] ?>">Edit</a> |
                            <a href="?delete_id=<?= $article['id'] ?>" onclick="return confirm('Are you sure you want to delete this article?')">Delete</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p>No articles found.</p>
    <?php endif; ?>

    <!-- Edit Article -->
    <?php if (isset($_GET['edit_id'])): ?>
        <?php
        $editId = intval($_GET['edit_id']);
        $stmt = $conn->prepare("SELECT * FROM articles WHERE id = ?");
        $stmt->bind_param('i', $editId);
        $stmt->execute();
        $result = $stmt->get_result();
        $article = $result->fetch_assoc();
        ?>
        <?php if ($article): ?>
            <h2>Edit Article</h2>
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="article_id" value="<?= $article['id'] ?>">
                
                <label for="title">Title:</label><br>
                <input type="text" id="title" name="title" value="<?= htmlspecialchars($article['title']) ?>" required><br><br>

                <label for="details">Details:</label><br>
                <textarea id="details" name="details" rows="5" required><?= htmlspecialchars($article['details']) ?></textarea><br><br>

                <label for="url">URL:</label><br>
                <input type="url" id="url" name="url" value="<?= htmlspecialchars($article['url']) ?>"><br><br>

                <label>Existing Images:</label><br>
                <?php foreach (json_decode($article['images'], true) as $image): ?>
                    <img src="<?= $image ?>" alt="Article Image" width="100"><br>
                <?php endforeach; ?>
                <br>

                <label>Upload New Images (optional):</label><br>
                <input type="file" name="images[]" multiple><br><br>

                <button type="submit">Update Article</button>
            </form>
        <?php else: ?>
            <p>Article not found.</p>
        <?php endif; ?>
    <?php endif; ?>
</body>
</html>
