<?php
error_reporting(E_ALL);
ini_set('display_errors', 0); // Disable for production
ini_set('log_errors', 1);
ini_set('error_log', '/var/log/php_errors.log'); // Ensure writable path

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: GET");
header('Content-Type: application/json');

try {
    // Include database connection and validation
    require_once 'config.php';
    require_once 'validate_api_key.php';

    // Verify database connection
    if (!$conn) {
        error_log('Database connection is null');
        echo json_encode(['error' => 'Database connection failed']);
        http_response_code(500);
        exit;
    }

    // Validate API key
    $headers = getallheaders();
    $apiKey = $headers['Authorization'] ?? '';
    $user = validateApiKey($conn, $apiKey);
    if (!$user) {
        error_log('Unauthorized: Invalid or missing API key');
        echo json_encode(['error' => 'Unauthorized']);
        http_response_code(401);
        exit;
    }

    $user_id = $user['user_id'];
    error_log('Authenticated user_id: ' . $user_id);

    // Check for product_ids
    if (empty($_GET['product_ids'])) {
        error_log('Product IDs are required');
        echo json_encode(['error' => 'Product IDs are required']);
        http_response_code(400);
        exit;
    }

    $product_ids = trim($_GET['product_ids']);
    error_log('Product IDs requested: ' . $product_ids);

    // Parse product IDs
    $product_id_array = array_map('intval', array_filter(explode(',', $product_ids)));
    if (empty($product_id_array)) {
        error_log('No valid product IDs provided');
        echo json_encode(['error' => 'No valid product IDs provided']);
        http_response_code(400);
        exit;
    }

    // Verify products exist and belong to the user
    $placeholders = implode(',', array_fill(0, count($product_id_array), '?'));
    $stmt = $conn->prepare("
        SELECT p.product_id 
        FROM products p 
        JOIN shops s ON p.shop_id = s.shop_id 
        WHERE p.product_id IN ($placeholders) AND s.user_id = ?
    ");
    if (!$stmt) {
        error_log('Prepare failed for product check: ' . $conn->error);
        echo json_encode(['error' => 'Database query preparation failed: ' . $conn->error]);
        http_response_code(500);
        exit;
    }
    $stmt->execute(array_merge($product_id_array, [$user_id]));
    $valid_product_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if (empty($valid_product_ids)) {
        error_log('No valid products found for user: ' . $user_id . ', product_ids: ' . $product_ids);
        echo json_encode([]);
        http_response_code(200);
        exit;
    }

    // Fetch images
    $placeholders = implode(',', array_fill(0, count($valid_product_ids), '?'));
    $stmt = $conn->prepare("
        SELECT pi.product_id, pi.image_id, pi.image_name
        FROM product_images pi
        WHERE pi.product_id IN ($placeholders)
    ");
    if (!$stmt) {
        error_log('Prepare failed for image fetch: ' . $conn->error);
        echo json_encode(['error' => 'Database query preparation failed: ' . $conn->error]);
        http_response_code(500);
        exit;
    }
    $stmt->execute($valid_product_ids);

    $images = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $product_id = $row['product_id'];
        if (!isset($images[$product_id])) {
            $images[$product_id] = [];
        }
        $image_path = UPLOAD_DIR . $row['image_name'];
        if (file_exists($image_path)) {
            $image_url = BASE_URL . $row['image_name'];
            error_log('Found image: ' . $image_url);
            $images[$product_id][] = [
                'image_id' => $row['image_id'],
                'url' => $image_url
            ];
        } else {
            error_log('Image file not found: ' . $image_path);
        }
    }

    // Ensure all product IDs have an entry
    foreach ($valid_product_ids as $id) {
        if (!isset($images[$id])) {
            $images[$id] = [];
        }
    }

    error_log('Fetched ' . count($images) . ' product image sets for product_ids: ' . $product_ids);
    echo json_encode($images);
    http_response_code(200);

} catch (Exception $e) {
    error_log('Error fetching images: ' . $e->getMessage());
    echo json_encode(['error' => 'Error fetching images: ' . $e->getMessage()]);
    http_response_code(500);
} finally {
    if (isset($conn)) {
        $conn->close();
    }
}
?>