<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Shopify credentials
$shop = "car-touchup-paint.myshopify.com"; 
$token_file = "shopify_access_token.txt";
$token = '';

// Check if token file exists
if (file_exists($token_file)) {
    $file_content = file_get_contents($token_file);
    
    // Extract token using regex
    if (preg_match('/Access Token:\s*(shpat_[a-zA-Z0-9]+)/', $file_content, $matches)) {
        $token = $matches[1];
    }
    // Alternative: Extract using string functions if regex fails
    else {
        $lines = explode("\n", $file_content);
        foreach ($lines as $line) {
            if (strpos($line, 'Access Token:') !== false) {
                $parts = explode(':', $line, 2);
                if (isset($parts[1])) {
                    $token = trim($parts[1]);
                    break;
                }
            }
        }
    }
}

// Check if token was found
if (empty($token)) {
    http_response_code(400);
    echo json_encode(array(
        "success" => false, 
        "errors" => array("Missing access token. Token file not found or invalid format.")
    ));
    exit();
}

$debug_log = __DIR__ . '/debug_upload.log';
$response = array(
    "success" => false,
    "files"   => array(),
    "errors"  => array()
);

function debug_log($message) {
    global $debug_log;
    $timestamp = date('Y-m-d H:i:s');
    $log_message = "[$timestamp] $message\n";
    file_put_contents($debug_log, $log_message, FILE_APPEND | LOCK_EX);
}

// Handle connection test request
if (isset($_POST['test_connection'])) {
    debug_log("Connection test requested");
    
    if (testShopifyConnection()) {
        $response = array(
            "success" => true,
            "message" => "✅ Connection successful! Token is valid.",
            "shop" => $shop,
            "token_preview" => !empty($token) ? substr($token, 0, 10) . "..." : "No token",
            "api_version" => "2024-10"
        );
    } else {
        $response = array(
            "success" => false,
            "message" => "❌ Connection failed! Check token and permissions.",
            "shop" => $shop,
            "token_preview" => !empty($token) ? substr($token, 0, 10) . "..." : "No token",
            "suggestion" => "Check if token is expired or API permissions are correct"
        );
    }
    
    echo json_encode($response);
    exit();
}

// Test connection to Shopify
function testShopifyConnection() {
    global $shop, $token;
    
    // Use REST API instead of GraphQL for simpler test
    $url = "https://$shop/admin/api/2024-10/shop.json";
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "X-Shopify-Access-Token: $token",
            "Content-Type: application/json"
        ],
        CURLOPT_TIMEOUT => 10
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return $httpCode === 200;
}

// Test connection first
if (!testShopifyConnection()) {
    http_response_code(401);
    echo json_encode(array(
        "success" => false, 
        "errors" => array("Cannot connect to Shopify. Check credentials and token.")
    ));
    exit();
}

// Get product data from POST
$productData = array(
    "brand" => isset($_POST['brand']) ? $_POST['brand'] : '',
    "color_name" => isset($_POST['color_name']) ? $_POST['color_name'] : '',
    "year" => isset($_POST['year']) ? $_POST['year'] : '',
    "paint_codes" => isset($_POST['paint_codes']) ? $_POST['paint_codes'] : '',
    "models" => isset($_POST['models']) ? $_POST['models'] : '',
    "all_models" => isset($_POST['all_models']) && !empty($_POST['all_models']) ? array_map('trim', explode(',', $_POST['all_models'])) : [],
    "alternative_codes" => isset($_POST['alternative_codes']) && !empty($_POST['alternative_codes']) ? array_map('trim', explode(',', $_POST['alternative_codes'])) : [],
    "alternative_descriptions" => isset($_POST['alternative_descriptions']) && !empty($_POST['alternative_descriptions']) ? array_map('trim', explode(',', $_POST['alternative_descriptions'])) : [],
    "price" => isset($_POST['price']) ? $_POST['price'] : '9.95',
    "compare_price" => isset($_POST['compare_price']) ? $_POST['compare_price'] : '0.00',
    "check_duplicates" => isset($_POST['check_duplicates']) ? ($_POST['check_duplicates'] === 'on' || $_POST['check_duplicates'] === 'true') : 'false'
);

// Validate required fields
$requiredFields = array('brand', 'color_name', 'year', 'paint_codes', 'models');
foreach ($requiredFields as $field) {
    if (empty($productData[$field])) {
        http_response_code(400);
        echo json_encode(array(
            "success" => false, 
            "errors" => array("Missing required field: " . $field),
            "validation_error" => true
        ));
        exit;
    }
}

// === GraphQL function to search for existing product ===
function searchProductByFingerprintTag($brand, $colorName, $paintCodes) {
    global $shop, $token;

    $tag = buildDuplicateTag($brand, $colorName, $paintCodes);

    $query = [
        'query' => '
        {
            products(first: 1, query: "tag:' . $tag . '") {
                edges {
                    node {
                        id
                    }
                }
            }
        }'
    ];

    $url = "https://$shop/admin/api/2024-10/graphql.json";

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($query),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "X-Shopify-Access-Token: $token"
        ],
        CURLOPT_TIMEOUT => 20
    ]);

    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code === 200) {
        $data = json_decode($res, true);
        if (!empty($data['data']['products']['edges'][0]['node']['id'])) {
            return basename($data['data']['products']['edges'][0]['node']['id']);
        }
    }

    return null;
}

// === Helper function to build duplicate tag ===
function buildDuplicateTag($brand, $colorName, $paintCodes) {
    $normalized = strtolower(
        trim($brand) . '|' .
        trim($colorName) . '|' .
        normalizePaintCode($paintCodes)
    );
    return 'fp_' . substr(hash('sha256', $normalized), 0, 24);
}

// === Helper function to normalize paint code ===
function normalizePaintCode($code) {
    return strtolower(preg_replace('/[^a-z0-9]/i', '', $code));
}

// === Function to add year range tags ===
function addYearTags($productData, $tags) {
    $year = $productData['year'];
    
    // Check if it's a year range (e.g., "2013 - 2024")
    if (strpos($year, '-') !== false || strpos($year, 'to') !== false) {
        // Clean the year string
        $year = str_replace(['to', 'TO', 'To'], '-', $year);
        $yearParts = explode('-', $year);
        
        if (count($yearParts) >= 2) {
            $startYear = trim($yearParts[0]);
            $endYear = trim($yearParts[1]);
            
            // Validate years are numeric
            if (is_numeric($startYear) && is_numeric($endYear)) {
                $startYear = (int)$startYear;
                $endYear = (int)$endYear;
                
                // Add individual year tags
                for ($year = $startYear; $year <= $endYear; $year++) {
                    $tags[] = "Year: " . $year;
                }
                
                // Add decade tags
                $startDecade = floor($startYear / 10) * 10;
                $endDecade = floor($endYear / 10) * 10;
                
                for ($decade = $startDecade; $decade <= $endDecade; $decade += 10) {
                    $tags[] = "Decade: " . $decade . "s";
                }
            }
        }
    } else {
        // Single year
        $cleanYear = trim($year);
        if (is_numeric($cleanYear)) {
            $yearNum = (int)$cleanYear;
            $tags[] = "Year: " . $yearNum;
            $decade = floor($yearNum / 10) * 10;
            $tags[] = "Decade: " . $decade . "s";
        }
    }
    
    return $tags;
}

// === IMPROVED: Function to generate HTML description ===
function generateDescription($productData) {
    $brand = htmlspecialchars($productData['brand'], ENT_QUOTES, 'UTF-8');
    $models = htmlspecialchars($productData['models'], ENT_QUOTES, 'UTF-8');
    $colorName = htmlspecialchars($productData['color_name'], ENT_QUOTES, 'UTF-8');
    $year = htmlspecialchars($productData['year'], ENT_QUOTES, 'UTF-8');
    $paintCodes = htmlspecialchars($productData['paint_codes'], ENT_QUOTES, 'UTF-8');
    
    $description = <<<HTML
<h2>{$brand} {$models} Touch Up Paint – {$colorName} ({$year}, Paint Code {$paintCodes})</h2>

<p>Restore your {$brand}'s iconic finish with our factory-matched {$colorName} touch up paint kit. Designed for precision and ease, this kit makes it simple to repair scratches, chips, and paint blemishes at home — without costly body shop visits.</p>

<h3>✅ Why Choose Our {$brand} {$models} {$colorName} Kit?</h3>

<ul>
<li><strong>Exact OEM Colour Match (Paint Code {$paintCodes})</strong>: Engineered to seamlessly blend with your original factory finish.</li>
<li><strong>Fast-Drying Formula</strong>: Complete touch ups quickly — no long wait times.</li>
<li><strong>DIY-Friendly</strong>: Available in pen, brush, or spray options for any repair size. Easy enough for beginners, trusted by pros.</li>
<li><strong>Durable, High-Gloss Finish</strong>: Provides long-lasting protection with a smooth, showroom-quality shine.</li>
<li><strong>Complete Solution</strong>: Optional primer and clear coat available for maximum durability and a factory-perfect look.</li>
</ul>

<h3>Perfect Fit For</h3>
<p>{$brand} {$models} ({$year}) finished in {$colorName} (Paint Code {$paintCodes}).</p>

<p>✨ <strong>Keep your {$brand} looking flawless</strong> with our premium touch up paint kit — the smart, affordable solution to restore factory-new shine.</p>

<p>🔗 <strong>Order your {$brand} {$colorName} (Paint Code {$paintCodes}) touch up paint kit today</strong> and bring back your car's perfect finish.</p>

<div style="background-color: #f8f9fa; padding: 20px; border-left: 4px solid #007bff; margin: 20px 0;">
<h4 style="margin-top: 0; color: #0056b3;">Key Features:</h4>
<ul style="margin-bottom: 0;">
<li>Perfect color match guarantee</li>
<li>Professional-grade formula</li>
<li>Easy application for beginners</li>
<li>Long-lasting protection</li>
<li>Fast shipping available</li>
</ul>
</div>

<p><em>Note: This is a touch-up paint kit designed for small repairs. For larger areas, we recommend professional application.</em></p>
HTML;
    
    return $description;
}

// === MAIN FUNCTION: Create product with REST API ===
function createProductWithREST($productData) {
  global $shop, $token;
    
$productData['paint_codes'] = str_replace("'", "", $productData['paint_codes']);

// Format the title
$title = $productData['brand'] . " " . $productData['models'] . " " . 
         $productData['color_name'] . " " . $productData['year'] . " " . 
         str_replace(', ', ', ', $productData['paint_codes']);

// === TAGS LIKE: 2007, Year_2007, 475, BMW, C4R, Color_Black, Make_BMW, Metallic, Model_B6Alpina, Sapphire ===
$tags = array();

// 1. Plain brand (e.g., "BMW")
$tags[] = $productData['brand'];

// 2. Make_Brand (e.g., "Make_BMW")
$tags[] = "Make_" . $productData['brand'];

// 3. Model_ModelName (e.g., "Model_B6Alpina")
$modelTag = "Model_" . str_replace(' ', '_', $productData['models']);
$modelTag = preg_replace('/[^a-zA-Z0-9_]/', '_', $modelTag);
$modelTag = preg_replace('/_+/', '_', $modelTag);
$tags[] = $modelTag;

// 4. Color_ColorName (e.g., "Color_Black")
$colorTag = "Color_" . str_replace(' ', '_', $productData['color_name']);
$colorTag = preg_replace('/[^a-zA-Z0-9_]/', '', $colorTag); // Remove special chars
$colorTag = preg_replace('/_+/', '_', $colorTag);
$colorTag = rtrim($colorTag, '_');
$tags[] = $colorTag;

// 5. Detect color type and add as plain tag (e.g., "Metallic")
$colorType = detectColorType($productData['color_name']);
$tags[] = $colorType;

// 6. Uppercase brand (e.g., "ACURA")
$tags[] = strtoupper($productData['brand']);

// 8. Alternative codes as plain tags (e.g., "475", "C4R")
if (!empty($productData['alternative_codes'])) {
    foreach ($productData['alternative_codes'] as $code) {
        $cleanCode = trim($code);
        $cleanCode = preg_replace('/[^a-zA-Z0-9]/', '', $cleanCode);
        if (!empty($cleanCode)) {
            $tags[] = $cleanCode;
        }
    }
}

// 9. Alternative descriptions as plain tags (e.g., "Sapphire")
if (!empty($productData['alternative_descriptions'])) {
    foreach ($productData['alternative_descriptions'] as $desc) {
        $cleanDesc = trim($desc);
        // Clean and add as plain tag
        $cleanDesc = preg_replace('/[^a-zA-Z0-9]/', '', $cleanDesc);
        if (!empty($cleanDesc)) {
            $tags[] = $cleanDesc;
        }
    }
}

// 10. Process year for tags
$year = trim($productData['year']);

// Check for year range (e.g., "2013-2024" or "2013 to 2024")
if (preg_match('/(\d{4})\s*[-to]+\s*(\d{4})/i', $year, $matches)) {
    $startYear = (int)$matches[1];
    $endYear = (int)$matches[2];
    
    // Add individual years and Year_ tags
    for ($yearNum = $startYear; $yearNum <= $endYear; $yearNum++) {
        $tags[] = $yearNum; // Plain year like "2007"
        $tags[] = "Year_" . $yearNum; // Year_ tag like "Year_2007"
    }
} elseif (is_numeric($year)) {
    // Single year
    $yearNum = (int)$year;
    $tags[] = $yearNum; // Plain year like "2007"
    $tags[] = "Year_" . $yearNum; // Year_ tag like "Year_2007"
}

// 11. Paint codes as plain tags (e.g., "B588P", "475")
$paintCodesArray = explode(',', $productData['paint_codes']);
foreach ($paintCodesArray as $code) {
    $cleanCode = trim($code);
    $cleanCode = preg_replace('/[^a-zA-Z0-9]/', '', $cleanCode);
    if (!empty($cleanCode)) {
        $tags[] = $cleanCode;
    }
}

// 12. Add fingerprint tag for duplicate checking
$fingerprintTag = buildDuplicateTag(
    $productData['brand'],
    $productData['color_name'],
    $productData['paint_codes']
);
$tags[] = $fingerprintTag;

// Clean and deduplicate tags
$tags = array_filter($tags);
$tags = array_map('strval', $tags);
$tags = array_values(array_unique($tags));

// Create SKU
$sku = $productData['brand'] . "_" .
       str_replace(' ', '_', $productData['color_name']) . "_" .
       preg_replace('/[^0-9]/', '', $productData['year']);
$sku = substr($sku, 0, 100);

// Create product with REST API
$product = [
    'product' => [
        'title' => $title,
        'body_html' => generateDescription($productData),
        'vendor' => 'Color Swatches',
        'product_type' => 'Color Swatch',
        'status' => 'active',
        'tags' => implode(', ', $tags),
        'variants' => [[
            'sku' => $sku,
            'price' => $productData['price'],
            'compare_at_price' => $productData['compare_price'],
            'inventory_policy' => 'continue',
            'inventory_management' => null
        ]]
    ]
];
    
    $url = "https://$shop/admin/api/2024-10/products.json";
    
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($product),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "X-Shopify-Access-Token: $token"
        ],
        CURLOPT_TIMEOUT => 30
    ]);
    
    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    debug_log("REST Product creation response code: " . $code);
    debug_log("Tags used: " . implode(', ', $tags));
    debug_log("REST Product creation response: " . substr($res, 0, 500));
    
    if ($code === 201) {
        $result = json_decode($res, true);
        
        // Add metafields after product creation
        $productId = $result['product']['id'];
        addProductMetafields($productId, $productData);
        
        return [
            'success' => true,
            'product_id' => $productId,
            'variant_id' => $result['product']['variants'][0]['id'],
            'tags' => $tags, // Return tags for debugging
            'details' => $result
        ];
    }
    
    $error = ['Product creation failed with code: ' . $code];
    $result = json_decode($res, true);
    
    if (isset($result['errors'])) {
        $error = $result['errors'];
    }
    
    return ['success' => false, 'error' => $error, 'raw_response' => $res];
}

// === Function to add metafields using REST API ===
function addProductMetafields($productId, $productData) {
    global $shop, $token;
    
    $metafields = [
        ['namespace' => 'custom', 'key' => 'paint_code', 'value' => $productData['paint_codes'], 'type' => 'single_line_text_field'],
        ['namespace' => 'custom', 'key' => 'vehicle_year', 'value' => $productData['year'], 'type' => 'single_line_text_field'],
        ['namespace' => 'custom', 'key' => 'vehicle_make', 'value' => $productData['brand'], 'type' => 'single_line_text_field'],
        ['namespace' => 'custom', 'key' => 'color_name', 'value' => $productData['color_name'], 'type' => 'single_line_text_field']
    ];
    
    foreach ($metafields as $metafield) {
        $url = "https://$shop/admin/api/2024-10/products/$productId/metafields.json";
        $data = ['metafield' => $metafield];
        
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "X-Shopify-Access-Token: $token"
            ],
            CURLOPT_TIMEOUT => 10
        ]);
        
        curl_exec($ch);
        curl_close($ch);
        usleep(500000); // 0.5 second delay to avoid rate limiting
    }
}

// === GraphQL function to upload image ===
function uploadImageToProduct($productId, $imageUrl) {
    global $shop, $token;

    $mutation = [
        'query' => '
        mutation productCreateMedia($productId: ID!, $media: [CreateMediaInput!]!) {
          productCreateMedia(productId: $productId, media: $media) {
            media {
              ... on MediaImage {
                id
                status
              }
            }
            userErrors {
              field
              message
            }
          }
        }',
        'variables' => [
            'productId' => "gid://shopify/Product/{$productId}",
            'media' => [[
                'mediaContentType' => 'IMAGE',
                'originalSource' => $imageUrl
            ]]
        ]
    ];

    $url = "https://{$shop}/admin/api/2024-10/graphql.json";

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($mutation),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "X-Shopify-Access-Token: {$token}",
        ],
        CURLOPT_TIMEOUT => 60,
    ]);

    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return json_decode($res, true);
}

// === Helper function to save temporary image ===
function saveTempImage($imageData, $extension = 'jpg') {
    $uploadDir = __DIR__ . '/tmp_images/';

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $fileName = 'product_' . uniqid() . '.' . $extension;
    $filePath = $uploadDir . $fileName;

    file_put_contents($filePath, $imageData);
    $result = array();
    $result['path'] = $filePath;
    $result['url'] = 'development.hatinco.com/vehicle-car-details/v2/tmp_images/'.$fileName;
    return $result;
}

// === Function to get Shopify product images ===
function getShopifyProductImages($productGid) {
    global $shop, $token;

    $query = [
        'query' => '
        query GetProductImages($id: ID!) {
          product(id: $id) {
            media(first: 10) {
              nodes {
                ... on MediaImage {
                  id
                  image {
                    url
                    altText
                  }
                }
              }
            }
          }
        }',
        'variables' => [
            'id' => $productGid
        ]
    ];

    $url = "https://{$shop}/admin/api/2024-10/graphql.json";

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($query),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "X-Shopify-Access-Token: {$token}"
        ],
    ]);

    $res = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($res, true);

    $images = [];
    
    if (isset($data['data']['product']['media']['nodes']) && is_array($data['data']['product']['media']['nodes'])) {
        foreach ($data['data']['product']['media']['nodes'] as $node) {
            if (isset($node['image']['url']) && !empty($node['image']['url'])) {
                $images[] = $node['image']['url'];
            }
        }
    }
    return $images;
}

// Handle upload
if (empty($_FILES['images']) && empty($_POST['images'])) {
    http_response_code(400);
    echo json_encode(array(
        "success" => false, 
        "errors" => array("No images provided."),
        "validation_error" => true
    ));
    exit;
}

// Process uploaded files
if (isset($_FILES['images'])) {
    foreach ($_FILES['images']['tmp_name'] as $i => $tmpName) {
        if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
            $existingProductId = null;
            
            // Check duplicates only if enabled
            if ($productData['check_duplicates']) {
                debug_log("Checking for duplicates...");
                $existingProductId = searchProductByFingerprintTag(
                    $productData['brand'],
                    $productData['color_name'],
                    $productData['paint_codes']
                );
                
                if ($existingProductId) {
                    debug_log("Duplicate found: " . $existingProductId);
                    $response["files"][] = array(
                        "product_id" => $existingProductId,
                        "filename" => $_FILES['images']['name'][$i],
                        "status" => "existing",
                        "is_duplicate" => true,
                        "message" => "Duplicate product found - SKIPPED creation",
                        "action_taken" => "skipped"
                    );
                    continue;
                } else {
                    debug_log("No duplicate found");
                }
            }
            
            // Product doesn't exist, create new one
            $imageData = file_get_contents($tmpName);
            $tempImage = saveTempImage($imageData);
            
            // Clean the URL
            $clean_image_url = "https://" . $tempImage['url'];
            
            // Create product with REST API
            $creationResult = createProductWithREST($productData);

            if ($creationResult['success']) {
                $productId = $creationResult['product_id'];
                
                // Upload image
                $uploadResult = uploadImageToProduct($productId, $clean_image_url);
                sleep(2);
                
                // Get the uploaded image URL
                $productGid = "gid://shopify/Product/{$productId}";
                $shopify_img_url = getShopifyProductImages($productGid);
                
                // Clean up temp file
                if (file_exists($tempImage['path'])) {
                    unlink($tempImage['path']);
                }
                
                $response["files"][] = array(
                    "product_id" => $productId,
                    "variant_id" => $creationResult['variant_id'],
                    "price" => $productData['price'],
                    "filename" => $_FILES['images']['name'][$i],
                    "status" => "created",
                    "is_duplicate" => false,
                    "upload_result" => $uploadResult,
                    "shopify_img_url" => !empty($shopify_img_url) ? $shopify_img_url[0] : null,
                    "tags" => isset($creationResult['tags']) ? $creationResult['tags'] : [],
                    "action_taken" => "created_and_image_uploaded"
                );
                
                $response["success"] = true;
            } else {
                debug_log("Product creation failed for: " . $_FILES['images']['name'][$i]);
                $response["files"][] = array(
                    "filename" => $_FILES['images']['name'][$i],
                    "status" => "failed",
                    "error_details" => $creationResult['error'],
                    "raw_response" => isset($creationResult['raw_response']) ? $creationResult['raw_response'] : null,
                    "http_code" => isset($creationResult['http_code']) ? $creationResult['http_code'] : null,
                    "action_taken" => "creation_failed"
                );
                $response["errors"][] = "Could not create product for image: " . $_FILES['images']['name'][$i];
            }
        } else {
            $uploadError = "File upload error: " . $_FILES['images']['error'][$i];
            debug_log($uploadError);
            $response["files"][] = array(
                "filename" => $_FILES['images']['name'][$i],
                "status" => "upload_error",
                "error" => $uploadError,
                "action_taken" => "upload_failed"
            );
            $response["errors"][] = $uploadError;
        }
    }
}

// Add summary information
$response["summary"] = array(
    "total_files" => isset($_FILES['images']) ? count($_FILES['images']['name']) : 0,
    "successful_uploads" => count(array_filter($response["files"], function($file) {
        return in_array($file['status'], ['created', 'existing']);
    })),
    "failed_uploads" => count(array_filter($response["files"], function($file) {
        return in_array($file['status'], ['failed', 'upload_error']);
    })),
    "timestamp" => date('Y-m-d H:i:s'),
    "product_data_received" => $productData
);

// Set success flag if any files were processed successfully
if (count($response["files"]) > 0 && $response["summary"]["successful_uploads"] > 0) {
    $response["success"] = true;
}

echo json_encode($response, JSON_PRETTY_PRINT);





// === Function to detect color type (Metallic, Solid, Pearl, etc.) ===
function detectColorType($colorName) {
    $colorName = strtolower($colorName);
    
    if (strpos($colorName, 'metallic') !== false || strpos($colorName, 'metal') !== false) {
        return 'Metallic';
    } elseif (strpos($colorName, 'pearl') !== false) {
        return 'Pearl';
    } elseif (strpos($colorName, 'matte') !== false) {
        return 'Matte';
    } elseif (strpos($colorName, 'crystal') !== false) {
        return 'Crystal';
    } elseif (strpos($colorName, 'chrome') !== false) {
        return 'Chrome';
    } else {
        return 'Solid';
    }
}
?>