-- DROP MATERIALIZED VIEW v_esales_printproduct;
-- REFRESH MATERIALIZED VIEW v_esales_printproduct;
-- CREATE MATERIALIZED VIEW v_esales_printproduct
CREATE MATERIALIZED VIEW v_esales_printproduct AS
SELECT	main.id,
		main.product_id,
		main.path,
		main.article_number,
		main.title,
		main.group_id,
		main.group_name,
		main.type_id,
		main.type_name,
		main.price,
		main.image,
		main.thumbnail,
		main.width,
		main.height,
		CASE
			WHEN main.width::integer > main.height::integer THEN 'landscape'::text
			WHEN main.width::integer < main.height::integer THEN 'portrait'::text
			ELSE 'square'::text
		END AS orientation
  FROM	(
	  		SELECT	pp.printid AS id,
					pp.productid AS product_id,
					(SELECT path FROM "product-products" WHERE productid = pp.productid LIMIT 1) AS path,
					(
						SELECT	value FROM "product-products_fields" WHERE productid = pp.productid
						   AND	fieldid = (SELECT fieldid FROM "product-fields" WHERE field = 'artNo' LIMIT 1)
					) AS article_number,
					(
						SELECT	value FROM "product-products_fields" WHERE productid = pp.productid
						   AND	fieldid = (SELECT fieldid FROM "product-fields" WHERE field = 'name' LIMIT 1)
					) AS title,
					pp.groupid AS group_id,
					(
						SELECT	"group"
						  FROM	"product-groups"
						 WHERE	groupid = pp.groupid
						 LIMIT 1
					) AS group_name,
					pp.typeid AS type_id,
					(
						SELECT	type
						  FROM	"product-types"
						 WHERE	typeid = pp.typeid
						 LIMIT 1
					) AS type_name,
					(
						(
							SELECT	min(price) AS min
							  FROM	"product-printprices"
							 WHERE	groupid = pp.groupid
					 	) * COALESCE(
							(
								SELECT	1 + designers.pricepremium / 100
								  FROM	designers
								 WHERE	designers.designerid = (
									 SELECT designerid FROM "product-products" WHERE productid = pp.productid LIMIT 1)
							), 1)
					) AS price,
					('//images.photowall.com/products/' || pp.productid) || '.jpg' AS image,
					('//images.photowall.com/products/' || pp.productid) || '.jpg?w=80' AS thumbnail,
					(SELECT value FROM "product-products_fields" WHERE productid = pp.productid AND fieldid = 5 LIMIT 1) AS width,
					(SELECT value FROM "product-products_fields" WHERE productid = pp.productid AND fieldid = 3 LIMIT 1) AS height
			  FROM	"product-printproducts" pp
	) main;

-- DROP INDEX v_categorytree_i18n_id_locale_id;
CREATE UNIQUE INDEX v_esales_printproduct_id
 ON v_esales_printproduct (id);

CREATE INDEX v_esales_printproduct_product_id
 ON v_esales_printproduct (product_id);
