<?php
// Start output buffering to catch any stray output
ob_start();

// --- Step 1: Configuration and Setup ---
error_reporting(E_ALL);
ini_set('display_errors', 0); 
ini_set('log_errors', 1);

// Include the database connection, which should provide the $conn object
require 'db_connect.php'; 

// Set the response header to JSON
header('Content-Type: application/json');
$response = [];

// Clear any output from included files (like db_connect.php)
ob_clean(); 

// --- Step 2: Validate Environment ---
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: Database connection is not available.';
    echo json_encode($response);
    exit; 
}

// --- Step 3: Validate Incoming JSON Data ---
if (!isset($_POST['products_json']) || empty(trim($_POST['products_json']))) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = "Required field 'products_json' is missing or empty.";
    echo json_encode($response);
    exit;
}

$products = json_decode($_POST['products_json'], true);

if (json_last_error() !== JSON_ERROR_NONE || !is_array($products)) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'Invalid JSON format or not an array.';
    $response['json_error'] = json_last_error_msg();
    echo json_encode($response);
    exit;
}

// --- Step 4: Prepare Database Statement ---
// Note: The column `image_url` in your SQL is assumed based on your `add_product.php` script.
// If it's different (e.g., `image_path`), change it here.
$sql = "INSERT INTO products (name, category, brand_id, models, description, specification, regular_price, offer_price, image_url, gallery_images) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: Could not prepare the database statement.';
    echo json_encode($response);
    exit;
}

// --- Step 5: Loop Through Products and Execute INSERT ---
$success_count = 0;
$failure_count = 0;
$errors = [];

foreach ($products as $index => $product) {
    // Assign and sanitize data for each product
    $name = trim($product['name'] ?? '');
    $category = trim($product['category'] ?? '');
    $brand_id = (int)($product['brandId'] ?? 0); // Note: JSON key is often camelCase
    $models = trim($product['models'] ?? '');
    $description = trim($product['description'] ?? '');
    $specification = trim($product['specification'] ?? '');
    $regular_price = (float)($product['regularPrice'] ?? 0.0); // Note: JSON key is often camelCase
    $offer_price = (float)($product['offerPrice'] ?? 0.0); // Note: JSON key is often camelCase
    $image_path = trim($product['imagePath'] ?? ''); // Note: JSON key is often camelCase
    $gallery_images = trim($product['galleryImages'] ?? ''); // Note: JSON key is often camelCase

    // Basic validation for each product in the loop
    if (empty($name) || empty($category) || $brand_id === 0) {
        $failure_count++;
        $errors[] = "Skipped product at index {$index} due to missing name, category, or brand_id.";
        continue; // Skip this product and move to the next
    }
    
    // Bind parameters to the prepared statement for the current product
    $stmt->bind_param(
        "ssisssddss", 
        $name, 
        $category, 
        $brand_id, 
        $models, 
        $description, 
        $specification, 
        $regular_price, 
        $offer_price, 
        $image_path,
        $gallery_images
    );

    if ($stmt->execute()) {
        $success_count++;
    } else {
        $failure_count++;
        $errors[] = "Failed to insert product '{$name}': " . $stmt->error;
    }
}

$stmt->close();

// --- Final Step: Clean Output and Send JSON Response ---
if ($failure_count > 0) {
    $response['status'] = 'partial_success';
    $response['message'] = 'Some products could not be uploaded.';
    $response['success_count'] = $success_count;
    $response['failure_count'] = $failure_count;
    $response['errors'] = $errors;
} else {
    $response['status'] = 'success';
    $response['message'] = 'All products uploaded successfully!';
    $response['success_count'] = $success_count;
}

$json_output = json_encode($response);

// Discard anything in the buffer (warnings, spaces)
ob_clean(); 

// Send only the final JSON response
echo $json_output;

$conn->close();
exit;
?>