<?php include_once "include/default-values.php" ?>
<?php

function checkImg($files)
{
    $validExtensions = ["jpg", "jpeg", "png", "gif", "webp"];

    foreach ($files['pic']['name'] as $key => $name) {
        $tmpName = $files['pic']['tmp_name'][$key];
        $fileExtension = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        if (!in_array($fileExtension, $validExtensions) || getimagesize($tmpName) === false) {
            return false;
        }
    }

    // All images are valid
    return true;
}

$message = "";

$keptValues = [];

// isset($_POST) kan nogle gange false trigger
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $validImgs = checkImg($_FILES);
    if (!$validImgs) {
        $message .= "Invalid images! \n";
    } else if ($_POST["button"] === "create") {
        $targetDirectory = "assets/img/";
        $uploadedFiles = [];
        $successfullUpload = true;

        foreach ($_FILES['pic']['tmp_name'] as $key => $tmp_name) {
            $image = $_FILES['pic']['name'][$key];
            $temp = $_FILES['pic']['tmp_name'][$key];

            // Generate a unique file name to prevent overwriting
            $uniqueName = strtolower(str_replace(" ", "", trim(uniqid() . "_" . $image)));

            $targetPath = $targetDirectory . $uniqueName;

            if (move_uploaded_file($temp, $targetPath)) {
                $uploadedFiles[] = $uniqueName; // Store the uploaded file names in the array
            } else {
                $successfullUpload = false;
            }
        }
        if (!$successfullUpload) {
            $message .= "Upload failed! \n";
        } else {
            $name = $_POST["name"];
            $price = $_POST["price"];
            $stars = $_POST["stars"];
            $stock = $_POST["stock"];
            $stiff = $_POST["stiff"];
            $supp = implode(" ", $_POST["supp"]);
            $desc = $_POST["desc"];
            $pics = implode(" ", $uploadedFiles);
            try {
                $db_con->query("INSERT INTO `products` (`PID`, `PName`, `PStars`, `PDesc`, `PStiff`, `PSupp`, `PPrice`, `PPic`, `PStock`) VALUES (NULL, '$name', '$stars', '$desc', '$stiff', '$supp', '$price', '$pics', '$stock');");
                unset($_POST);
                header("Location: " . $siteroot . "shop.php");
                exit();
            } catch (Exception $e) {
                $message .= $e->getMessage() . " \n";
            }
        }
    }
    $keptValues["name"] = $_POST["name"];
    $keptValues["price"] = $_POST["price"];
    $keptValues["stars"] = $_POST["stars"];
    $keptValues["stock"] = $_POST["stock"];
    $keptValues["stiff"] = $_POST["stiff"];
    $keptValues["supp"] = $_POST["supp"];
    $keptValues["desc"] = $_POST["desc"];
} else {
    unset($_POST);
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EDEA - Create Product</title>
    <link rel="stylesheet" href="<?= $siteroot; ?>css/style.css">
    <link rel="stylesheet" href="<?= $siteroot; ?>css/forms.css">
</head>

<body>
    <?php include "include/header.php"; ?>
    <main>
        <h1>Opret Produkt</h1>
        <?php
        if (strlen($message) > 0) echo "<pre class='error'>ERROR! $message</pre>";
        ?>
        <form method="POST" enctype="multipart/form-data">
            <div class="input-data required">
                <input type="text" id="name" name="name" value="<?= $keptValues["name"] ?>" required>
                <div class="underline"></div>
                <label for="name">Produkt navn</label>
            </div>
            <div class="input-data">
                <input type="number" id="price" name="price" min="0" value="<?= $keptValues["price"] ?>">
                <div class="underline"></div>
                <label for="price">Pris</label>
            </div>
            <div class="input-data">
                <input type="number" id="stars" name="stars" min="1" max="6" value="<?= $keptValues["stars"] ?>">
                <div class="underline"></div>
                <label for="stars">Stjerner</label>
            </div>
            <div class="input-pictures">
                <label for="pic">Billeder</label>
                <input type="file" class="picture-input" id="pic" name="pic[]" multiple value="<?= $keptValues["pic"] ?>" accept=".jpg, .jpeg, .png, .gif, .webp">
                <ul class="image-preview"></ul>
            </div>
            <div class="input-data">
                <input type="number" id="stock" name="stock" min="0" value="<?= $keptValues["stock"] ?>">
                <div class="underline"></div>
                <label for="stock">Lager</label>
            </div>
            <div class="input-data">
                <input type="number" id="stiff" name="stiff" min="0" max="100" value="<?= $keptValues["stiff"] ?>">
                <div class="underline"></div>
                <label for="stiff">Stivhed</label>
            </div>
            <div class="input-select">
                <label for="supp">Support (ctrl click for flere)</label>
                <select name="supp[]" id="supp" multiple>
                    <option value="Enkeltspring" selected>Enkeltspring</option>
                    <option value="Doublespring">Doublespring</option>
                    <option value="Triplespring">Triplespring</option>
                    <option value="Quadspring">Quadspring</option>
                </select>
                <div class="underline"></div>
            </div>
            <div class="input-data textarea required">
                <textarea type="text" id="desc" name="desc" value="" required><?= $keptValues["desc"] ?></textarea>
                <div class="underline"></div>
                <label for="desc">Produkt beskrivelse</label>
            </div>
            <div class="input-submit">
                <button name="button" value="create">Opret</button>
            </div>
        </form>
    </main>
    <?php include "include/footer.php"; ?>
    <script src="<?= $siteroot; ?>js/forms.js"></script>
</body>

</html>