<?php
require_once __DIR__ . "/../config.php";
require_once __DIR__ . "/../includes/functions.php";

if (empty($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit();
}

$pageTitle = "Produkte verwalten";
$message = "";
$messageType = "";
$categories = getCategories();

function handleImageUpload($fileInputName = "image_file")
{
    if (
        !isset($_FILES[$fileInputName]) ||
        $_FILES[$fileInputName]["error"] === UPLOAD_ERR_NO_FILE
    ) {
        return ["success" => true, "filename" => null];
    }

    $file = $_FILES[$fileInputName];
    if ($file["error"] === UPLOAD_ERR_INI_SIZE || $file["error"] === UPLOAD_ERR_FORM_SIZE) {
        return [
            "success" => false,
            "message" => "Die Datei ist zu groß (maximal 10 MB).",
        ];
    }
    if ($file["error"] !== UPLOAD_ERR_OK) {
        return ["success" => false, "message" => "Upload fehlgeschlagen."];
    }

    $maxBytes = 10 * 1024 * 1024;
    if ((int) ($file["size"] ?? 0) > $maxBytes) {
        return [
            "success" => false,
            "message" => "Die Datei ist zu groß (maximal 10 MB).",
        ];
    }

    $allowedExtensions = ["jpg", "jpeg", "png", "webp", "gif"];
    $originalName = basename($file["name"]);
    $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    if (!in_array($extension, $allowedExtensions, true)) {
        return ["success" => false, "message" => "Ungültiger Dateityp."];
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->file($file["tmp_name"]);
    $allowedMimes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
    if (!in_array($mimeType, $allowedMimes, true)) {
        return [
            "success" => false,
            "message" => "Die Datei ist kein gültiges Bild.",
        ];
    }

    $uploadsDir = rtrim(UPLOADS_DIR, "/\\");
    if (
        !is_dir($uploadsDir) &&
        !mkdir($uploadsDir, 02775, true) &&
        !is_dir($uploadsDir)
    ) {
        return [
            "success" => false,
            "message" => "Upload-Verzeichnis konnte nicht erstellt werden.",
        ];
    }

    if (is_dir($uploadsDir)) {
        @chmod($uploadsDir, 02775);
    }

    if (!is_writable($uploadsDir)) {
        return [
            "success" => false,
            "message" =>
                "Upload-Verzeichnis ist nicht beschreibbar: " . $uploadsDir,
        ];
    }

    $safeBaseName = preg_replace(
        "/[^a-zA-Z0-9_-]/",
        "-",
        pathinfo($originalName, PATHINFO_FILENAME),
    );
    $safeBaseName = trim((string) $safeBaseName, "-");
    if ($safeBaseName === "") {
        $safeBaseName = "bild";
    }

    $targetFilename = $safeBaseName . "." . $extension;
    $targetPath = $uploadsDir . "/" . $targetFilename;
    $counter = 1;
    while (file_exists($targetPath)) {
        $targetFilename = $safeBaseName . "-" . $counter . "." . $extension;
        $targetPath = $uploadsDir . "/" . $targetFilename;
        $counter++;
    }

    if (!move_uploaded_file($file["tmp_name"], $targetPath)) {
        return [
            "success" => false,
            "message" => "Bild konnte nicht gespeichert werden.",
        ];
    }

    return ["success" => true, "filename" => $targetFilename];
}

function buildProductAvailabilityFields(
    $sizesInput,
    $submittedValues = [],
    $existingValues = [],
) {
    $sizes = getProductSizes(["sizes" => (string) $sizesInput]);
    if (empty($sizes)) {
        $sizes = ["Standard"];
    }

    $availabilityLabels = [];
    foreach ($sizes as $size) {
        $fieldName = "availability_" . str_replace([" ", ","], "_", $size);
        if (isset($submittedValues[$fieldName])) {
            $availabilityLabels[$size] = trim(
                (string) $submittedValues[$fieldName],
            );
        } else {
            $availabilityLabels[$size] = trim(
                (string) ($existingValues[$size] ?? ""),
            );
        }
    }

    return [
        "sizes" => implode(",", $sizes),
        "availability_labels" => $availabilityLabels,
    ];
}

function getSubmittedProductCategoryIds($submittedValues)
{
    $selectedCategoryIds = normalizeProductCategoryIds(
        $submittedValues["categories"] ?? [],
    );
    $validCategoryIds = [];

    foreach ($selectedCategoryIds as $categoryId) {
        if (getCategoryById($categoryId) !== null) {
            $validCategoryIds[] = $categoryId;
        }
    }

    return $validCategoryIds;
}

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        $products = getProducts();

        if (empty($categories)) {
            $message = "Bitte zuerst mindestens eine Kategorie anlegen.";
            $messageType = "error";
        } elseif (
            isset($_POST['add_product']) ||
            isset($_POST['update_product'])
        ) {
            $uploadResult = handleImageUpload();
            if (!$uploadResult["success"]) {
                $message = $uploadResult["message"];
                $messageType = "error";
            } else {
                $categoryIds = getSubmittedProductCategoryIds($_POST);
                $existingLabels = [];
                $productId = isset($_POST['product_id'])
                    ? (int) $_POST['product_id']
                    : 0;
                foreach ($products as $product) {
                    if ((int) $product["id"] === $productId) {
                        $existingLabels = $product["availability_labels"] ?? [];
                        break;
                    }
                }

                $sizeData = buildProductAvailabilityFields(
                    $_POST['sizes'] ?? "",
                    $_POST,
                    $existingLabels,
                );

                if (empty($categoryIds)) {
                    $message =
                        "Bitte mindestens eine gültige Kategorie auswählen.";
                    $messageType = "error";
                } else {
                    $record = [
                        "name" => sanitize($_POST['name'] ?? ""),
                        "description" => trim(
                            (string) ($_POST['description'] ?? ""),
                        ),
                        "categories" => $categoryIds,
                        "image" =>
                            $uploadResult["filename"] !== null
                                ? $uploadResult["filename"]
                                : trim((string) ($_POST['image'] ?? "")),
                        "sizes" => $sizeData["sizes"],
                        "availability_labels" =>
                            $sizeData["availability_labels"],
                    ];

                    if ($record["name"] === "") {
                        $message = "Bitte einen Produktnamen eingeben.";
                        $messageType = "error";
                    } elseif (isset($_POST['add_product'])) {
                        $newId = empty($products)
                            ? 1
                            : max(
                                    array_map(function ($product) {
                                        return (int) $product["id"];
                                    }, $products),
                                ) + 1;
                        $record["id"] = $newId;
                        $products[] = $record;
                        if (saveProducts($products)) {
                            logAccess("Admin added product", [
                                "product_id" => $newId,
                                "product_name" => $record["name"],
                            ]);
                            $message = "Produkt wurde angelegt.";
                            $messageType = "success";
                        } else {
                            $message =
                                "Produkt konnte nicht gespeichert werden.";
                            $messageType = "error";
                        }
                    } else {
                        $updated = false;
                        foreach ($products as &$product) {
                            if ((int) $product["id"] === $productId) {
                                $record["id"] = $productId;
                                $product = $record;
                                $updated = true;
                                break;
                            }
                        }
                        unset($product);

                        if ($updated) {
                            if (saveProducts($products)) {
                                logAccess("Admin updated product", [
                                    "product_id" => $productId,
                                    "product_name" => $record["name"],
                                ]);
                                $message = "Produkt wurde aktualisiert.";
                                $messageType = "success";
                            } else {
                                $message =
                                    "Produkt konnte nicht gespeichert werden.";
                                $messageType = "error";
                            }
                        } else {
                            $message = "Produkt nicht gefunden.";
                            $messageType = "error";
                        }
                    }
                }
            }
        }

        if (isset($_POST['delete_product'])) {
            $productId = (int) ($_POST['product_id'] ?? 0);
            $productName = "";
            foreach ($products as $product) {
                if ((int) $product["id"] === $productId) {
                    $productName = $product["name"];
                    break;
                }
            }
            $products = array_values(
                array_filter($products, function ($product) use ($productId) {
                    return (int) $product["id"] !== $productId;
                }),
            );
            if (saveProducts($products)) {
                logAccess("Admin deleted product", [
                    "product_id" => $productId,
                    "product_name" => $productName,
                ]);
                $message = "Produkt wurde gelöscht.";
                $messageType = "success";
            } else {
                $message = "Produkt konnte nicht gelöscht werden.";
                $messageType = "error";
            }
        }
    }
}

$products = getProducts();
$editingProduct = isset($_GET['edit'])
    ? getProductById((int) $_GET['edit'])
    : null;

$bodyClass = "admin-page";
include __DIR__ . "/../includes/header.php";
?>

<div class="admin-header">
    <h2>Produkte verwalten</h2>
    <div>
        <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
    </div>
</div>

<?php if ($message !== ""): ?>
    <div class="alert alert-<?php echo escape($messageType); ?>">
        <?php echo escape($message); ?>
    </div>
<?php endif; ?>

<?php
$currentProduct = $editingProduct ?: [
    "id" => "",
    "name" => "",
    "description" => "",
    "categories" => [],
    "sizes" => "Standard",
    "availability_labels" => ["Standard" => ""],
    "image" => "",
];
$currentSizes = getProductSizes($currentProduct);
if (empty($currentSizes)) {
    $currentSizes = ["Standard"];
}
?>

<div class="panel panel-lg">
    <h3><?php echo $editingProduct
        ? "Produkt bearbeiten"
        : "Neues Produkt anlegen"; ?></h3>
    <form method="POST" enctype="multipart/form-data">
        <?php echo csrfField(); ?>
        <?php if ($editingProduct): ?>
            <input type="hidden" name="product_id" value="<?php echo (int) $editingProduct[
                "id"
            ]; ?>">
        <?php endif; ?>

        <div class="form-group">
            <label for="name">Name *</label>
            <input type="text" id="name" name="name" required value="<?php echo escape(
                $currentProduct["name"],
            ); ?>">
        </div>

        <div class="form-group">
            <label for="description">Beschreibung</label>
            <textarea id="description" name="description" rows="4"><?php echo escape(
                $currentProduct["description"],
            ); ?></textarea>
        </div>

        <div class="form-group">
            <label for="categories">Kategorien *</label>
            <select id="categories" name="categories[]" multiple size="<?php echo max(
                3,
                min(8, count($categories)),
            ); ?>" required>
                <?php foreach ($categories as $category): ?>
                    <option value="<?php echo escape(
                        $category["id"],
                    ); ?>" <?php echo in_array(
    $category["id"],
    getProductCategoryIds($currentProduct),
    true,
)
    ? "selected"
    : ""; ?>>
                        <?php echo escape($category["label"]); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <small>Für Mehrfachauswahl von Kategorien STRG + Klick.</small>
        </div>

        <div class="form-group">
            <label for="sizes">Größen (kommagetrennt) *</label>
            <input type="text" id="sizes" name="sizes" required value="<?php echo escape(
                $currentProduct["sizes"],
            ); ?>" placeholder="Standard" oninput="updateAvailabilityFields()">
            <small>Für Artikel ohne Varianten z. B. <code>Standard</code> oder <code>Einheitsgröße</code>.</small>
        </div>

        <div id="availability-group">
            <?php foreach ($currentSizes as $size): ?>
                <div class="form-group">
                    <label>Lieferhinweis für Größe "<?php echo escape(
                        $size,
                    ); ?>"</label>
                    <textarea name="availability_<?php echo escape(
                        str_replace([" ", ","], "_", $size),
                    ); ?>" rows="2" placeholder="Optionaler Hinweis"><?php echo escape(
    $currentProduct["availability_labels"][$size] ?? "",
); ?></textarea>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="form-group">
            <label for="image">Bilddateiname</label>
            <input type="text" id="image" name="image" value="<?php echo escape(
                $currentProduct["image"],
            ); ?>">
        </div>

        <div class="form-group">
            <label for="image_file">Oder Bild hochladen</label>
            <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
        </div>

        <button type="submit" name="<?php echo $editingProduct
            ? "update_product"
            : "add_product"; ?>" class="btn">
            <?php echo $editingProduct
                ? "Produkt aktualisieren"
                : "Produkt anlegen"; ?>
        </button>
        <?php if ($editingProduct): ?>
            <a href="products.php" class="btn btn-secondary">Abbrechen</a>
        <?php endif; ?>
    </form>
</div>

<script>
function updateAvailabilityFields() {
    const sizesInput = document.getElementById('sizes');
    const group = document.getElementById('availability-group');
    const currentValues = {};

    group.querySelectorAll('textarea').forEach((textarea) => {
        currentValues[textarea.name] = textarea.value;
    });

    const sizes = sizesInput.value
        .split(',')
        .map((size) => size.trim())
        .filter((size, index, all) => size && all.indexOf(size) === index);

    const finalSizes = sizes.length > 0 ? sizes : ['Standard'];
    let html = '';

    finalSizes.forEach((size) => {
        const safeName = size.replace(/[ ,]/g, '_');
        const fieldName = 'availability_' + safeName;
        const currentValue = Object.prototype.hasOwnProperty.call(currentValues, fieldName) ? currentValues[fieldName] : '';
        html += '<div class="form-group">';
        html += '<label>Lieferhinweis für Größe "' + size.replace(/"/g, '&quot;') + '"</label>';
        html += '<textarea name="' + fieldName + '" rows="2" placeholder="Optionaler Hinweis">' + currentValue.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</textarea>';
        html += '</div>';
    });

    group.innerHTML = html;
}
</script>

<h3>Alle Produkte</h3>
<?php if (empty($products)): ?>
    <p>Keine Produkte vorhanden.</p>
<?php else: ?>
    <div class="table-responsive">
        <table class="responsive-table">
            <thead>
                <tr>
                    <th class="product-id-column">ID</th>
                    <th>Name</th>
                    <th>Kategorien</th>
                    <th>Größen</th>
                    <th>Lieferhinweise</th>
                    <th>Aktionen</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($products as $product): ?>
                    <tr>
                        <td data-label="ID" class="product-id-column"><?php echo (int) $product[
                            "id"
                        ]; ?></td>
                        <td data-label="Name"><?php echo escape(
                            $product["name"],
                        ); ?></td>
                        <td data-label="Kategorien"><?php echo escape(
                            implode(
                                ", ",
                                getCategoryLabels(
                                    getProductCategoryIds($product),
                                ),
                            ),
                        ); ?></td>
                        <td data-label="Größen"><?php echo escape(
                            implode(", ", getProductSizes($product)),
                        ); ?></td>
                        <td data-label="Lieferhinweise">
                            <?php
                            $labels = [];
                            foreach (
                                $product["availability_labels"] ?? []
                                as $size => $label
                            ) {
                                if (trim((string) $label) !== "") {
                                    $labels[] = $size . ": " . $label;
                                }
                            }
                            echo empty($labels)
                                ? "Keine"
                                : escape(implode(" | ", $labels));
                            ?>
                        </td>
                        <td data-label="Aktionen">
                            <a href="?edit=<?php echo (int) $product[
                                "id"
                            ]; ?>" class="btn btn-small">Bearbeiten</a>
                            <form method="POST" class="inline-form" onsubmit="return confirm('Produkt wirklich löschen?');">
                                <?php echo csrfField(); ?>
                                <input type="hidden" name="product_id" value="<?php echo (int) $product[
                                    "id"
                                ]; ?>">
                                <button type="submit" name="delete_product" class="btn btn-secondary btn-small">Löschen</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<?php include __DIR__ . "/../includes/footer.php"; ?>
