<?php
include "../db.php";

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "Invalid request"]);
    exit;
}

$rawBody = file_get_contents("php://input");
$jsonInput = json_decode($rawBody, true);
if (!is_array($jsonInput)) {
    $jsonInput = [];
}

$name = $_POST['name'] ?? ($jsonInput['name'] ?? '');
$price = $_POST['price'] ?? ($jsonInput['price'] ?? '');
$description = $_POST['description'] ?? ($jsonInput['description'] ?? '');
$category = $_POST['category'] ?? ($jsonInput['category'] ?? '');

if (empty($name) || empty($price)) {
    http_response_code(400);
    echo json_encode(["error" => "Missing fields"]);
    exit;
}

$uploadDir = __DIR__ . "/uploads/";
if (!is_dir($uploadDir) && !mkdir($uploadDir, 0777, true)) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to create upload directory"]);
    exit;
}

function findUploadedMerchImageKey() {
    $candidateKeys = ['image', 'file', 'photo', 'imageFile'];
    foreach ($candidateKeys as $key) {
        if (!empty($_FILES[$key]['name']) && ($_FILES[$key]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK) {
            return $key;
        }
    }
    return null;
}

function saveBase64Image($dataUrl, $uploadDir) {
    if (!preg_match('/^data:image\/([A-Za-z0-9.+-]+);base64,(.*)$/', $dataUrl, $matches)) {
        return null;
    }

    $extension = strtolower($matches[1]);
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    if ($extension === 'svg+xml') {
        $extension = 'svg';
    }

    if (!in_array($extension, $allowed, true) && $extension !== 'svg') {
        return null;
    }

    $binary = base64_decode($matches[2], true);
    if ($binary === false) {
        return null;
    }

    $imageName = time() . '_' . uniqid() . '.'.$extension;
    $destination = $uploadDir . $imageName;
    if (file_put_contents($destination, $binary) === false) {
        return null;
    }

    return $imageName;
}

function isObjectPlaceholderString($value) {
    return is_string($value) && preg_match('/^\[object\s+[A-Za-z0-9_]+\]$/', trim($value));
}

$imageName = null;
$imageKey = findUploadedMerchImageKey();

if ($imageKey !== null) {
    $safeOriginalName = preg_replace("/[^A-Za-z0-9_.-]/", "_", basename($_FILES[$imageKey]['name']));
    $imageName = time() . '_' . uniqid() . '_' . $safeOriginalName;
    $destination = $uploadDir . $imageName;

    if (!move_uploaded_file($_FILES[$imageKey]['tmp_name'], $destination)) {
        http_response_code(500);
        echo json_encode(["error" => "Failed to upload image"]);
        exit;
    }
}

if ($imageName === null) {
    $inlineImage = $_POST['image'] ?? ($jsonInput['image'] ?? null);
    if (is_string($inlineImage) && $inlineImage !== '') {
        if (strpos($inlineImage, 'data:image/') === 0) {
            $savedBase64 = saveBase64Image($inlineImage, $uploadDir);
            if ($savedBase64 !== null) {
                $imageName = $savedBase64;
            }
        } elseif (isObjectPlaceholderString($inlineImage)) {
            http_response_code(400);
            echo json_encode(["error" => "Invalid image payload. Send image as multipart file data."]);
            exit;
        } else {
            $imageName = $inlineImage;
        }
    }
}

$stmt = $conn->prepare("INSERT INTO merch_items(name,price,description,image,category) VALUES(?,?,?,?,?)");
if (!$stmt) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to prepare insert query"]);
    exit;
}

$stmt->bind_param("sdsss", $name, $price, $description, $imageName, $category);

if (!$stmt->execute()) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to save merch item", "details" => $stmt->error]);
    exit;
}

echo json_encode(["success" => true, "image" => $imageName]);
