<?php
// add_slider.php - Final Version

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

$response = ['status' => 'error', 'message' => 'Invalid request.'];

// Check if the 'image_urls' field was sent from the app
if (isset($_POST['image_urls'])) {
    
    // The data from the app is a JSON string like: "[\"http://url1.com/a.jpg\",\"http://url2.com/b.jpg\"]"
    $jsonPayload = $_POST['image_urls'];
    
    // Decode the JSON string into a normal PHP array
    $imageUrls = json_decode($jsonPayload, true); // The 'true' is important

    // Check if the JSON was decoded successfully and is an array
    if (json_last_error() === JSON_ERROR_NONE && is_array($imageUrls)) {

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

            if ($stmt) {
                $successCount = 0;

                // Loop through each URL in the array and insert it into the database
                foreach ($imageUrls as $url) {
                    $title = ""; // Title is empty as requested
                    
                    // Bind the URL and title to the SQL statement
                    $stmt->bind_param("ss", $url, $title);
                    
                    if ($stmt->execute()) {
                        $successCount++;
                    }
                }
                $stmt->close();

                if ($successCount > 0) {
                    $response['status'] = 'success';
                    $response['message'] = $successCount . ' sliders added successfully.';
                } else {
                    $response['message'] = 'Database error: Failed to execute insert statement.';
                }
            } else {
                $response['message'] = 'Database error: Could not prepare statement.';
            }
        } else {
            $response['message'] = 'No image URLs were provided.';
        }
    } else {
        $response['message'] = 'Invalid JSON data was received from the app.';
    }
} else {
    $response['message'] = "Required 'image_urls' field is missing from the request.";
}

// Send the final response back to the app
echo json_encode($response);
$conn->close();
?>