<?php
include "../../root.class.php";

$db = new db_safeguard();

$uploadDir = "uploads/";

foreach ($_FILES['images']['name'] as $index => $imageName) {

    $tmpName = $_FILES['images']['tmp_name'][$index];
    $description = $_POST['descriptions'][$index] ?? '';

    if ($imageName == '')
        continue;

    $safeName = time() . "_" . basename($imageName);
    $targetFile = $uploadDir . $safeName;

    // Check if image already exists (by original name or logic you prefer)
    $check = $db->query(
        "images",
        "SELECT * FROM images WHERE image_name = '{$imageName}' LIMIT 1"
    );

    if ($check->num_rows > 0) {

        // UPDATE existing image description
        $db->query(
            "images",
            "UPDATE images 
             SET description = '{$description}' 
             WHERE image_name = '{$imageName}'"
        );

        echo "Updated: {$imageName}<br>";

    } else {

        // Move uploaded file
        if (move_uploaded_file($tmpName, $targetFile)) {

            $db->query(
                "images",
                "INSERT INTO images (image_name, description)
                 VALUES ('{$imageName}', '{$description}')"
            );

            echo "Uploaded: {$imageName}<br>";
        }
    }
}
