0) { $sql = "SELECT `product_image` FROM md_product WHERE company_id = :company_id AND id = :id"; $sth = $pdo2->prepare($sql); $sth->execute([":company_id" => $company_id, ":id" => $id]); $existing_files = $sth->fetchColumn(); $uploader->cleanup($existing_files, ''); } $errors = $uploader->upload('product_image'); if (!empty($errors)) { $answer["success"] = 0; $answer["message"] = $errors[0]; exit(json_encode($answer)); } // Get the single uploaded filename directly $db_image_string = $uploader->getUploadedFiles()[0] ?? ''; } else { // No new file — keep existing, skip cleanup entirely $db_image_string = $data['keep_files'] ?? ''; } dbTransaction($pdo2, function($pdo) use ($data, $company_id, $logging, $id, $db_image_string) { // get existing log $sql = "SELECT `log` FROM md_product WHERE company_id = :company_id AND id = :id"; $sth = $pdo->prepare($sql); $sth->execute([ ":company_id" => $company_id, ":id" => $id ]); $table_log = json_decode($sth->fetchColumn() ?: '[]', true); $table_log[] = $logging; if ($id > 0) { $sql = "UPDATE md_product SET product_name = :product_name, sku = :sku, price = :price, min_stock = :min_stock, reorder_point = :reorder_point, category = :category, product_image = :product_image, `description` = :description, `status` = :status, `log` = :log WHERE id = :id AND company_id = :company_id"; $sth = $pdo->prepare($sql); $sth->execute([ ":id" => $id, ":company_id" => $company_id, ":product_name" => $data["product_name"], ":sku" => $data["sku"], ":price" => $data["price"], ":min_stock" => $data["min_stock"], ":reorder_point" => $data["reorder_point"], ":category" => $data["category"], ":product_image"=> $db_image_string, ":description" => $data["description"], ":status" => $data["status"], ":log" => json_encode($table_log), ]); } else { $sql = "INSERT INTO md_product (company_id, product_name, sku, price, min_stock, reorder_point, category, product_image, `description`, `status`, `log`) VALUES (:company_id, :product_name, :sku, :price, :min_stock, :reorder_point, :category, :product_image, :description, :status, :log)"; $sth = $pdo->prepare($sql); $sth->execute([ ":company_id" => $company_id, ":product_name" => $data["product_name"], ":sku" => $data["sku"], ":price" => $data["price"], ":min_stock" => $data["min_stock"], ":reorder_point" => $data["reorder_point"], ":category" => $data["category"], ":product_image"=> $db_image_string, ":description" => $data["description"], ":status" => $data["status"], ":log" => json_encode($table_log), ]); } }); $answer["success"] = 1; } catch (PDOException $e) { $answer["success"] = 0; $answer["message"] = "Database error, please try again"; } catch (Exception $e) { $answer["success"] = 0; $answer["message"] = $e->getMessage(); $answer["error"] = $e->getMessage(); } exit(json_encode($answer)); ?>