<?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');

// Shopify credentials
$shop  = "car-touchup-paint.myshopify.com"; 
$token = "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";

$response = [
    "success" => false,
    "files"   => [],
    "errors"  => []
];

// Get product data from POST
$productData = [
    "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'] : '',
    "price" => isset($_POST['price']) ? $_POST['price'] : '9.95',
    "compare_price" => isset($_POST['compare_price']) ? $_POST['compare_price'] : '0.00'
];


// Validate required fields
$requiredFields = ['brand', 'color_name', 'year', 'paint_codes', 'models'];
foreach ($requiredFields as $field) {
    if (empty($productData[$field])) {
        http_response_code(400);
        echo json_encode(["success" => false, "errors" => ["Missing required field: " . $field]]);
        exit;
    }
}

// === Create product with complete data ===
function createNewProduct($base64String = null) {
    global $shop, $token, $productData;
    
    $productData['paint_codes'] = str_replace("'", "", $productData['paint_codes']);
    // Format the title
    $title = $productData['brand'] . " All Models " . $productData['color_name'] . " " . $productData['year'] . " " . str_replace(', ', ', ', $productData['paint_codes']);
    
    // Format description using template
    $description = $productData['brand'] . " Touch Up Paint – " . $productData['color_name'] . " (" . $productData['year'] . ", Paint Code " . $productData['paint_codes'] . ")

Restore your " . $productData['brand'] . "'s iconic finish with our factory-matched " . $productData['color_name'] . " 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.

✅ Why Choose Our " . $productData['brand'] . " " . $productData['color_name'] . " Kit?

Exact OEM Colour Match (Paint Code " . $productData['paint_codes'] . "): Engineered to seamlessly blend with your original factory finish.

Fast-Drying Formula: Complete touch ups quickly — no long wait times.

DIY-Friendly: Available in pen, brush, or spray options for any repair size. Easy enough for beginners, trusted by pros.

Durable, High-Gloss Finish: Provides long-lasting protection with a smooth, showroom-quality shine.

Complete Solution: Optional primer and clear coat available for maximum durability and a factory-perfect look.

Perfect Fit For

" . $productData['brand'] . " " . $productData['models'] . " (" . $productData['year'] . ") finished in " . $productData['color_name'] . " (Paint Code " . $productData['paint_codes'] . ").

✨ Keep your " . $productData['brand'] . " looking flawless with our premium touch up paint kit — the smart, affordable solution to restore factory-new shine.

🔗 Order your " . $productData['brand'] . " " . $productData['color_name'] . " (Paint Code " . $productData['paint_codes'] . ") touch up paint kit today and bring back your car's perfect finish.";

    // Prepare tags
    $tags = [
        $productData['brand'],
        "Color_" . str_replace(' ', '_', $productData['color_name']),
        "Model_" . str_replace(' ', '_', $productData['models']),
        "year_" . $productData['year'],
        strtoupper($productData['brand'])
    ];
    
    // Add paint codes as individual tags
    $paintCodeTags = array_map(function($code) {
        return str_replace(['-', ' '], '', trim($code));
    }, explode(',', $productData['paint_codes']));
    
    $tags = array_merge($tags, $paintCodeTags);
    $tagsString = implode(', ', $tags);

    $data = [
        "product" => [
            "title" => $title,
            "body_html" => "<p>" . nl2br(trim($description)) . "</p>",
            "vendor" => "Color Swatches",
            "product_type" => "Color Swatch",
            "status" => "active",
            "tags" => $tagsString,
            "variants" => [
                [
                    "price" => $productData['price'],
                    "compare_at_price" => $productData['compare_price'],
                    "sku" => $productData['brand'] . "_" . str_replace(' ', '_', $productData['color_name']) . "_" . $productData['year'],
                    "weight" => 0.4409,
                    "weight_unit" => "lb",
                    "inventory_management" => null,
                    "inventory_policy" => "deny"
                ]
            ],
            "metafields" => [
                [
                    "namespace" => "custom",
                    "key" => "paint_code",
                    "value" => $productData['paint_codes'],
                    "type" => "string"
                ],
                [
                    "namespace" => "custom",
                    "key" => "vehicle_year",
                    "value" => $productData['year'],
                    "type" => "string"
                ],
                [
                    "namespace" => "custom",
                    "key" => "vehicle_make",
                    "value" => $productData['brand'],
                    "type" => "string"
                ],
                [
                    "namespace" => "custom",
                    "key" => "color_name",
                    "value" => $productData['color_name'],
                    "type" => "string"
                ]
            ]
        ]
    ];

    $url = "https://".$shop."/admin/api/2024-01/products.json";

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "X-Shopify-Access-Token: ".$token,
            "Accept: application/json"
        ],
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_TIMEOUT => 30,
    ]);

    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code == 201) {
        $result = json_decode($res, true);
        return $result['product']['id'];
    }
    
    error_log("Product creation failed: " . $res);
    return null;
}

// === Upload image to a product ===
function uploadProductImage($productId, $base64String) {
    global $shop, $token;

    $data = [
        "image" => [
            "attachment" => $base64String
        ]
    ];

    $url = "https://".$shop."/admin/api/2024-01/products/".$productId."/images.json";

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "X-Shopify-Access-Token: ".$token,
            "Accept: application/json"
        ],
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_TIMEOUT => 30,
    ]);

    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ["http_code" => $code, "response" => json_decode($res, true)];
}
function ensureBase64($imageData) {
    // Check if the string looks like a valid base64-encoded string
    if (base64_encode(base64_decode($imageData, true)) === $imageData) {
        // Already base64
        return $imageData;
    }

    // Not base64, so encode it
    return base64_encode($imageData);
}

// === Handle upload ===
if (empty($_FILES['images']) && empty($_POST['images'])) {
    http_response_code(400);
    echo json_encode(["success" => false, "errors" => ["No images provided."]]);
    exit;
}

// Process uploaded files
if (isset($_FILES['images'])) {
    foreach ($_FILES['images']['tmp_name'] as $i => $tmpName) {
        if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
            $imageData = file_get_contents($tmpName);
            $base64 = ensureBase64($imageData);
            
            $productId = createNewProduct($base64);
            if ($productId) {
                $upload = uploadProductImage($productId, $base64);
                $response["files"][] = [
                    "product_id" => $productId,
                    "upload" => $upload,
                    "filename" => $_FILES['images']['name'][$i]
                ];
            } else {
                $response["errors"][] = "Could not create product for image: " . $_FILES['images']['name'][$i];
            }
        }
    }
}

if (count($response["files"]) > 0) {
    $response["success"] = true;
}

echo json_encode($response);
?>