<?php
include 'admin-header.php';
require_once '../includes/image-resizer.php'; // Include our image resizer

// --- NEW: Fetch site settings for API keys ---
$settings_result = $conn->query("SELECT setting_name, setting_value FROM site_settings");
$settings = [];
while ($row = $settings_result->fetch_assoc()) {
    $settings[$row['setting_name']] = $row['setting_value'];
}
// --- END NEW ---

$message = '';
$article_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$edit_article = null;

// --- ACTION HANDLING (SAVE, DELETE GALLERY IMAGE) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // This is needed to keep the page context after an action
    $current_article_id = intval($_POST['article_id'] ?? $article_id);

    // --- ACTION: DELETE A SINGLE GALLERY IMAGE ---
    if (isset($_POST['delete_gallery_image'])) {
        $image_id_to_delete = intval($_POST['image_id']);
        
        $stmt_img = $conn->prepare("SELECT image_url FROM galleries WHERE id = ?");
        $stmt_img->bind_param("i", $image_id_to_delete);
        $stmt_img->execute();
        $result_img = $stmt_img->get_result();
        if($row_img = $result_img->fetch_assoc()) {
            if(!empty($row_img['image_url']) && file_exists('../' . $row_img['image_url'])) {
                unlink('../' . $row_img['image_url']);
            }
        }
        $stmt_del = $conn->prepare("DELETE FROM galleries WHERE id = ?");
        $stmt_del->bind_param("i", $image_id_to_delete);
        $stmt_del->execute();
        $message = '<div class="alert alert-success">Gallery image deleted successfully.</div>';
        $article_id = $current_article_id; // Ensure we stay on the same article's edit page
    }

    // --- ACTION: SAVE (ADD/EDIT) AN ARTICLE ---
    elseif (isset($_POST['save_article'])) {
        $id_to_save = intval($_POST['article_id']);
        $title = trim($_POST['title']);
        $content = $_POST['content'];
        $author = trim($_POST['author']);
        $publish_date = $_POST['publish_date'];
        $view_count = intval($_POST['view_count']);
        $like_count = intval($_POST['like_count']);
        $image_url = $_POST['current_image_url'] ?? '';

        // Handle MAIN featured image upload with resizing
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $target_dir = "../uploads/articles/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
            $image_extension = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
            $target_file = $target_dir . "article-main-" . uniqid() . "." . $image_extension;
            if (resizeImage($_FILES["image"]["tmp_name"], $target_file, 1200, 800)) {
                $image_url = str_replace('../', '', $target_file);
            }
        }

        if ($id_to_save > 0) { // Update existing article
            $stmt = $conn->prepare("UPDATE articles SET title=?, content=?, author=?, publish_date=?, image_url=?, view_count=?, like_count=? WHERE id=?");
            $stmt->bind_param("sssssiii", $title, $content, $author, $publish_date, $image_url, $view_count, $like_count, $id_to_save);
            $message = '<div class="alert alert-success">Article updated successfully. <a href="manage-articles.php">Return to list.</a></div>';
        } else { // Insert new article
            $stmt = $conn->prepare("INSERT INTO articles (title, content, author, publish_date, image_url, view_count, like_count) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssssii", $title, $content, $author, $publish_date, $image_url, $view_count, $like_count);
            $message = '<div class="alert alert-success">Article created successfully. <a href="manage-articles.php">Return to list.</a></div>';
        }
        $stmt->execute();
        $article_id = $id_to_save > 0 ? $id_to_save : $conn->insert_id;
        $stmt->close();

        // Handle MULTIPLE GALLERY IMAGE UPLOAD
        if ($article_id > 0 && isset($_FILES['gallery_images']) && !empty($_FILES['gallery_images']['name'][0])) {
            $target_dir = "../uploads/articles/gallery/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
            foreach ($_FILES['gallery_images']['tmp_name'] as $key => $tmp_name) {
                if ($_FILES['gallery_images']['error'][$key] == 0) {
                    $file_name = "article-gallery-" . $article_id . "-" . uniqid() . "." . basename($_FILES['gallery_images']['name'][$key]);
                    $target_file = $target_dir . $file_name;
                    if (resizeImage($tmp_name, $target_file, 1200, 800)) {
                        $gallery_image_url = str_replace('../', '', $target_file);
                        $stmt_gallery = $conn->prepare("INSERT INTO galleries (item_id, item_type, image_url) VALUES (?, 'article', ?)");
                        $stmt_gallery->bind_param("is", $article_id, $gallery_image_url);
                        $stmt_gallery->execute();
                    }
                }
            }
        }
    }
}

// Fetch article for editing if an ID is provided
if ($article_id > 0) {
    $stmt = $conn->prepare("SELECT * FROM articles WHERE id = ?");
    $stmt->bind_param("i", $article_id);
    $stmt->execute();
    $edit_article = $stmt->get_result()->fetch_assoc();
}
?>
<script src="https://cdn.tiny.cloud/1/<?php echo htmlspecialchars($settings['tinymce_api_key'] ?? 'no-api-key'); ?>/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: '#articleContent',
    plugins: 'code lists link image table fullscreen',
    toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright | indent outdent | bullist numlist | code | table | link image | fullscreen'
  });
</script>

<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"><?php echo $edit_article ? 'Edit Article' : 'Add New Article'; ?></h1>
    <a href="manage-articles.php" class="btn btn-secondary">← Back to Articles List</a>
</div>
<?php echo $message; ?>

<form method="POST" enctype="multipart/form-data">
    <input type="hidden" name="article_id" value="<?php echo $edit_article['id'] ?? 0; ?>">
    <div class="row">
        <div class="col-lg-8">
            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <div class="mb-3"><label class="form-label">Article Title</label><input type="text" name="title" class="form-control form-control-lg" value="<?php echo htmlspecialchars($edit_article['title'] ?? ''); ?>" required></div>
                    <div class="mb-3"><label class="form-label">Content</label><textarea id="articleContent" name="content" class="form-control" rows="20"><?php echo htmlspecialchars($edit_article['content'] ?? ''); ?></textarea></div>
                </div>
            </div>
             <?php if ($edit_article): ?>
            <div class="card shadow-sm">
                <div class="card-header">Image Gallery</div>
                <div class="card-body">
                    <div class="row">
                    <?php 
                    $gallery_result = $conn->query("SELECT * FROM galleries WHERE item_id = " . $edit_article['id'] . " AND item_type = 'article'");
                    if ($gallery_result && $gallery_result->num_rows > 0): 
                        while($img = $gallery_result->fetch_assoc()): 
                    ?>
                        <div class="col-xl-3 col-lg-4 col-md-4 col-6 mb-3 text-center">
                            <img src="../<?php echo htmlspecialchars($img['image_url']); ?>" class="img-thumbnail mb-2" style="height: 120px; width:100%; object-fit: cover;">
                            <form method="POST" onsubmit="return confirm('Delete this image?');">
                                <input type="hidden" name="article_id" value="<?php echo $edit_article['id']; ?>">
                                <input type="hidden" name="image_id" value="<?php echo $img['id']; ?>">
                                <button type="submit" name="delete_gallery_image" class="btn btn-danger btn-sm">Delete</button>
                            </form>
                        </div>
                    <?php endwhile; else: echo '<p class="text-muted text-center">No gallery images uploaded yet.</p>'; endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <div class="col-lg-4">
            <div class="card shadow-sm">
                <div class="card-header fw-bold">Publishing Options</div>
                <div class="card-body">
                    <div class="mb-3"><label class="form-label">Author</label><input type="text" name="author" class="form-control" value="<?php echo htmlspecialchars($edit_article['author'] ?? 'DXP Staff'); ?>"></div>
                    <div class="mb-3"><label class="form-label">Publish Date</label><input type="date" name="publish_date" class="form-control" value="<?php echo $edit_article['publish_date'] ?? date('Y-m-d'); ?>"></div>
                     <div class="mb-3">
                        <label class="form-label">View Count</label>
                        <input type="number" name="view_count" class="form-control" value="<?php echo $edit_article['view_count'] ?? 0; ?>">
                    </div>
                     <div class="mb-3">
                        <label class="form-label">Like Count</label>
                        <input type="number" name="like_count" class="form-control" value="<?php echo $edit_article['like_count'] ?? 0; ?>">
                    </div>
                     <div class="mb-3">
                        <label class="form-label">Featured Image</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                        <input type="hidden" name="current_image_url" value="<?php echo htmlspecialchars($edit_article['image_url'] ?? ''); ?>">
                        <?php if (!empty($edit_article['image_url'])): ?><div class="mt-2"><img src="../<?php echo htmlspecialchars($edit_article['image_url']); ?>" class="img-fluid img-thumbnail"></div><?php endif; ?>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Add Gallery Images</label>
                        <input type="file" class="form-control" name="gallery_images[]" multiple accept="image/*">
                    </div>
                    <div class="d-grid"><button type="submit" name="save_article" class="btn btn-primary btn-lg">Save Article</button></div>
                </div>
            </div>
        </div>
    </div>
</form>

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