addBreadcrumb("/products", __("Products")); $user = $core->getUser(); if(isset($id)) { $product = Product::require($id); $product->dts_updated = Database::dts(); $title = __("Update Product"); } else { $product = new Product(); $product->dts_created = Database::dts(); $title = __("Add Product"); } $core->addBreadcrumb($_SERVER["REQUEST_URI"], $title); $request = Request::fromPost(); $submit = $request->int("submit"); if($submit) { try { $user->requireValidCsrfToken(); $supplier_id = $request->int("supplier_id"); $supplier = Supplier::get($supplier_id); if(!$supplier) { throw new RuntimeException(__("Invalid supplier selected.")); } $product->supplier_id = $supplier_id; $product->name = $request->string("name"); $product->sku = $request->string("sku"); $product->type = $request->int("type"); $product->price = $request->decimal("price", 2); $product->url = $request->url("url"); if(!$product->name) { throw new RuntimeException(__("Name is required.")); } if(!$product->type) { throw new RuntimeException(__("Type is required.")); } $product->archived = (int) (bool) $request->int("archived"); $product->commit(); $delete_brochure = $request->int("delete_brochure"); if($delete_brochure && $product->hasBrochure()) { $product->deleteBrochure(); } $brochure = $_FILES["brochure"] ?? null; if($brochure) { $error = $brochure["error"]; if($error === UPLOAD_ERR_OK) { Util::createDirectory($_ENV["DIR_ROOT"] . "/files/product"); move_uploaded_file($brochure["tmp_name"], $product->getBrochurePath()); } else if($error !== UPLOAD_ERR_NO_FILE) { Session::addAlert("danger", __("Brochure upload failed.")); } } Session::addAlert("success", __("Product saved successfully.")); Http::redirect($product->getUpdateUrl()); } catch(RuntimeException $e) { Session::addAlert("danger", $e->getMessage()); } } $core->addScript("/js/product-form.js"); View::include("header"); View::include("product_form", compact("title", "product")); View::include("footer");