0) { $size_data[$sizes[$i]] = (int)$quantities[$i]; } } // Update stock quantity based on sizes $stock_quantity = array_sum($size_data); } // Validate inputs if (empty($name) || empty($description) || empty($price) || empty($stock_quantity)) { $error_message = 'Please fill in all required fields.'; } elseif (!is_numeric($price) || $price <= 0) { $error_message = 'Please enter a valid price.'; } elseif ($stock_quantity < 0) { $error_message = 'Stock quantity cannot be negative.'; } elseif ($category === 'clothes' && empty($size_data)) { $error_message = 'Please add at least one size with quantity.'; } else { try { // Handle image upload $image_path = null; if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) { $upload_dir = '../../uploads/products/'; if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); } $file_extension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif']; if (!in_array($file_extension, $allowed_extensions)) { throw new Exception('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.'); } $image_path = uniqid() . '.' . $file_extension; $upload_path = $upload_dir . $image_path; if (!move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) { throw new Exception('Failed to upload image.'); } } if (empty($error_message)) { $pdo->beginTransaction(); // Get admin's user ID from session $owner_id = $_SESSION['user_id']; $stmt = $pdo->prepare(" INSERT INTO products (owner_id, name, description, price, category, Sub_Cat, stock_quantity, image_path, size_data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) "); $stmt->execute([ $owner_id, $name, $description, $price, $category, $subcategory, $stock_quantity, $image_path, $size_data ? json_encode($size_data) : null ]); $pdo->commit(); $success_message = 'Product added successfully!'; // Clear form $name = $description = $price = $category = $subcategory = ''; $stock_quantity = 0; } } catch (Exception $e) { $pdo->rollBack(); $error_message = $e->getMessage(); } } } ?>