<?php
// add_banner.php - Debug Version

header('Content-Type: application/json');
require 'db_connect.php';

function write_log($message) {
    error_log("AddSliderDebug: " . $message);
}

$response = ['status' => 'error', 'message' => 'Invalid request'];
write_log("Script execution started.");

if (isset($_POST['image_urls'])) {
    $jsonPayload = $_POST['image_urls'];
    write_log("Received raw payload in 'image_urls': " . $jsonPayload);

    $imageUrls = json_decode($jsonPayload);

    if (json_last_error() !== JSON_ERROR_NONE) {
        write_log("JSON Decode Error: " . json_last_error_msg());
        $response['message'] = 'Invalid JSON data received.';
        echo json_encode($response);
        exit;
    }

    if (is_array($imageUrls) && !empty($imageUrls)) {
        write_log("Successfully decoded JSON into an array with " . count($imageUrls) . " items.");

        $sql = "INSERT INTO sliders (image_url, title) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);

        if (!$stmt) {
             write_log("FATAL: Failed to prepare statement. DB Error: " . $conn->error);
             $response['message'] = 'Database statement preparation failed.';
             echo json_encode($response);
             exit;
        }

        $successCount = 0;
        $failureCount = 0;
        foreach ($imageUrls as $url) {
            $title = ""; // Title is empty as requested
            $stmt->bind_param("ss", $url, $title);
            if ($stmt->execute()) {
                $successCount++;
            } else {
                $failureCount++;
                write_log("Failed to insert URL: " . $url . ". DB Error: " . $stmt->error);
            }
        }
        $stmt->close();
        
        write_log("Finished inserting. Success: " . $successCount . ", Failures: " . $failureCount);

        if ($successCount > 0) {
            $response['status'] = 'success';
            $response['message'] = $successCount . ' sliders added successfully.';
        } else {
            $response['message'] = 'Failed to add any sliders to the database.';
        }
    } else {
        write_log("Decoded JSON is empty or not an array.");
        $response['message'] = 'No image URLs provided in the request.';
    }
} else {
    write_log("'image_urls' field not found in POST data.");
}

write_log("Script finished. Sending response: " . json_encode($response));
echo json_encode($response);
$conn->close();
?>