
<?php
file_put_contents("debug_test.txt", "Start backend " . date('c') . "\n", FILE_APPEND);

session_start();
require_once('db_config.php');
$conn = get_db_connection();

function clean_input($value) {
    return htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8');
}

if (!isset($_SESSION['username'])) {
    die("User not logged in.");
}
$app_username = $_SESSION['username'];

$responseLog = [];

function logResp($msg) {
    global $responseLog;
    $responseLog[] = $msg;
}

// Rebuild items from POST and FILES
function rehydrate_items_from_post_files() {
    $items = [];
    if (!isset($_POST['items'])) return [];
    foreach ($_POST['items'] as $i => $item) {
        $items[$i] = $item;
        // Images (files) are in $_FILES, deeply nested. PHP is a pain.
        $imgPaths = [];
        if (isset($_FILES['items']['name'][$i]['images'])) {
            $imgCount = count($_FILES['items']['name'][$i]['images']);
            for ($j = 0; $j < $imgCount; $j++) {
                $name = $_FILES['items']['name'][$i]['images'][$j];
                $tmp_name = $_FILES['items']['tmp_name'][$i]['images'][$j];
                $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
                if ($tmp_name && in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                    $uploadDir = "uploads/";
                    $newName = uniqid() . "_" . preg_replace('/\s+/', '_', $name);
                    if (move_uploaded_file($tmp_name, $uploadDir . $newName)) {
                        $imgPaths[] = $uploadDir . $newName;
                    }
                }
            }
        }
        $items[$i]['image_paths'] = implode(",", $imgPaths);
        $items[$i]['imgPaths'] = $imgPaths;
    }
    return $items;
}

// ========== MAIN LOGIC ==========
$items = rehydrate_items_from_post_files();

foreach ($items as $i => $item) {
    $title = clean_input($item['title'] ?? '');
    $category = clean_input($item['category'] ?? '');
    $subcategory = clean_input($item['subcategory'] ?? '');
    $description = $item['description'] ?? ''; // allow HTML
    $brand = clean_input($item['brand'] ?? '');
    $model = clean_input($item['model'] ?? '');
    $uk_shoe_size = clean_input($item['uk_shoe_size'] ?? '');
    $colour = clean_input($item['colour'] ?? '');
    $department = clean_input($item['department'] ?? '');
    $type = clean_input($item['type'] ?? '');
    $material = clean_input($item['material'] ?? '');
    $style = clean_input($item['style'] ?? '');
    $schedule_start = clean_input($item['schedule_start'] ?? '');
    $price = clean_input($item['price'] ?? '');
    $ebay = !empty($item['ebay']) ? 1 : 0;
    $depop = !empty($item['depop']) ? 1 : 0;
    $ebay_format = clean_input($item['ebay_format'] ?? '');

    $image_paths = $item['image_paths'] ?? '';

    // Add to DB
    $stmt = $conn->prepare(
        "INSERT INTO listings (app_username, title, category, subcategory, description, brand, model, uk_shoe_size, colour, department, type, material, style, schedule_start, price, ebay, depop, image_paths)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt->bind_param(
        "sssssssssssssssiiis",
        $app_username,
        $title,
        $category,
        $subcategory,
        $description,
        $brand,
        $model,
        $uk_shoe_size,
        $colour,
        $department,
        $type,
        $material,
        $style,
        $schedule_start,
        $price,
        $ebay,
        $depop,
        $image_paths
    );
    $stmt->execute();
    $item_id = $stmt->insert_id;

    // ========== EBAY UPLOAD ==========
    if ($ebay) {
        $xml = build_ebay_xml($item, $item['imgPaths']);

        // Save debug XML
        file_put_contents("xml_debug/item_{$item_id}.xml", $xml);

        // POST to eBay API (replace with actual)
        $ebayResp = ebay_api_post($xml);

        $ebay_item_id = $ebayResp['ItemID'] ?? "";
        $ebay_response = $ebayResp['response'] ?? json_encode($ebayResp);

        $conn->query("UPDATE listings SET ebay_item_id = '" . $conn->real_escape_string($ebay_item_id) . "', ebay_response = '" . $conn->real_escape_string($ebay_response) . "' WHERE id = $item_id");

        logResp("<b>eBay Result for $title</b><br>Item ID: $ebay_item_id<br>Response:<pre>" . htmlspecialchars($ebay_response) . "</pre>");
    }

    // ========== DEPOP PLACEHOLDER ==========
    if ($depop) {
        logResp("<b>Depop upload logic not implemented.</b>");
    }
}

echo implode("<hr>", $responseLog);

// ---- Helper eBay Post Example ----
function build_ebay_xml($item, $imgPaths) {
    $xml = "<AddItemRequest>
        <Title>{$item['title']}</Title>
        <Description>{$item['description']}</Description>
        <Price>{$item['price']}</Price>
        <ImageList>";
    foreach ($imgPaths as $img) {
        $xml .= "<Image>" . htmlspecialchars($img) . "</Image>";
    }
    $xml .= "</ImageList>
    </AddItemRequest>";
    return $xml;
}

// Simulated eBay API call
function ebay_api_post($xml) {
    // Replace with real cURL POST to eBay Trading API
    // Simulate a successful response:
    return [
        "ItemID" => "1234567890",
        "response" => "Success: Listed!"
    ];
}
if (empty($responseLog)) {
    echo "No items processed.<br>POST:<pre>" . htmlspecialchars(print_r($_POST, true)) . "</pre><br>FILES:<pre>" . htmlspecialchars(print_r($_FILES, true)) . "</pre>";
}

?>
