<?php
header('Content-Type: application/json');

// --- 1. INCLUDE DATABASE CONNECTION ---
// This file provides the $conn (MySQLi) object
require_once 'db_connect.php'; 

$imageUrl = isset($_POST['image_url']) ? $_POST['image_url'] : '';

if (!empty($imageUrl)) {
    // --- 2. PREPARE AND EXECUTE UPDATE ---
    // This updates the single most recent banner entry
    $stmt = $conn->prepare("UPDATE popup_banners SET image_url = ? ORDER BY id DESC LIMIT 1");
    $stmt->bind_param("s", $imageUrl);

    if ($stmt->execute()) {
        // Check if a row was actually changed
        if ($conn->affected_rows > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Popup banner updated successfully.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No changes made or banner not found.']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to update popup banner.']);
    }
    $stmt->close();
} else {
    echo json_encode(['status' => 'error', 'message' => 'Image URL is required.']);
}

// --- 3. CLOSE CONNECTION ---
$conn->close();
?>