require "wizard/steps.pl" if ($page=~/^step/); # this is a dual-purpose page

#my $products=0, $categories=0, @row, %category=(), @product=();

sub page_config {
    if ($page=~/^step/) {
	nextstep();
	return 0;
	#if (!$cd{'incomplete_products'});
	#return &WRITE|&REGEN|&BUTTONS|&PREVIEW;
    }
    return 0;
}

sub do_page {
    return unless ($cd{'have_products'});

require "./Library/config.pl" ||die;
require "./wizard/productlib.pl" ||die;

local $error=0;


#Config::
&do_config;

#Productlib::
&read_categories;
#Productlib::
&read_products;


#print join("|",@{$category{$_}}),"<br>" foreach (keys %category);


# handle form submission
########################

if (param('item_edit_submit') && param('item')) {
    require "./wizard/imagelib.pl" ||die;
    my ($image,$x,$y);
    if (param('item') eq "new") {
	param('item',$max_items+1);
	push @products,[param('item')];
    }
#	$image="blank" if (!$image);
#    } else {
	($image,$x,$y)=&read_image(param('item'), 'image', $cd{'thumbnail_area'});
#    }
    param('weight',param('weight')."__".param('custaction'));

    my $dbfile=writeto($database_file);
    foreach $row (@products) {
	if ($row->[0] eq param('item')) {
#	    my $temp=param('description');
#	    param(description,$temp);
	    foreach ("name", "description", "price", "product", "weight") {
		$row->[$db{$_}]=munge param("$_");
	    }
	    if ($image) {
		$row->[$db{"image"}]=munge $image;
	    }
	}
	print $dbfile join("|",@{$row}),"\n";
    }
    close($dbfile);
    Delete('item_edit_submit');

#    Delete($_) foreach ('name', 'description', 'price', 'item_edit_submit', 'item');
    # horribly inefficient :(
    &read_categories;
    &read_products;
}

if (param('editcat_submit')) {
    if (defined(param('oldproduct')) && !defined($category{param('oldproduct')})) {
	# fiddle only
	$error="Attempt to delete nonexistent category (while altering category name)!";
    }
    my $oldcat=[];
    if (param('oldproduct')) {
	$oldcat=$category{param('oldproduct')};
	delete $category{param('oldproduct')};
    }
    if (defined($category{param('product')})) {
	$error="A category called ".param('product')." already exists.";
	Delete('product');
    } else {
	$category{param('product')}=$oldcat;
	require "./wizard/imagelib.pl" ||die;
	my ($image,$x,$y,$thumbx,$thumby,$thumb)=read_image("cat_".param('product'), 'image',$cd{'category_area'}||2500);
#    image_thumbnail("$image_dir/$image","$image_dir/$image");
	if ($image) {
	    if ($thumbx) {
		$image=$thumb;
		$x=$thumbx;
		$y=$thumby;
	    }
#	    my $ext=$cd{'thumbnail_ext'}||".jpeg";
#	    (my $thumb=$image)=~s/(\d+)\.(.*?)$/$1s$ext/;
#	    rename("$image_dir/$thumb","$image_dir/$image");
##	unlink("$image_dir/$image");
##	$image=$thumb;
	    param('image',$image);
	    param('width',$x);
	    param('height',$y);
	    foreach (keys %cat) {
		$category{param('product')}->[$cat{$_}]=munge param($_);
	    }
	} else {
	    foreach (keys %cat) {
		$category{param('product')}->[$cat{$_}]=munge param($_) unless ($_ eq 'image' || $_ eq 'width' || $_ eq 'height'); #yuck
	    }
	}

	if (defined(param('oldproduct')) && (param('product') ne param('oldproduct'))) {
	    my $dbfile=writeto($database_file);
	    foreach $row (@products) {
		if ($row->[$db{"product"}] eq param('oldproduct')) {
		    $row->[$db{"product"}]=param('product');
		}
		print $dbfile join("|",@{$row}),"\n";
	    }
	    close($dbfile);
	    
	    foreach (keys %category) {
		if ($category{$_}->[$cat{'parent'}] eq param('oldproduct')) {
		    $category{$_}->[$cat{'parent'}]=param('product');
		}
	    }

	    Delete('product');
	}

	my $catfile=writeto($category_file);
	foreach $row (sort keys %category) {
	    print $catfile $row,"|", join("|",@{$category{$row}}),"\n";
	}
	close($catfile);
    

	# horribly inefficient :(
	read_categories();
	read_products();
	
    }
    Delete('editcat_submit');
}

if (param('deletecat')) {
    if (!$category{param('product')}->[$cat{'products'}]) {
	delete $category{param('product')};
    } else {
	$error= "Attempt to delete non-empty category! (Contains $category{param('product')}->[$cat{'products'}] products)";
    }
    my $catfile=writeto($category_file);
    foreach $row (sort keys %category) {
	print $catfile $row,"|", join("|",@{$category{$row}}),"\n";
    }
    close($catfile);
    &read_categories;
    &read_products;
}

if (param('deleteitem')) {
    my $dbfile=writeto($database_file);
    foreach $row (@products) {
	if ($row->[0] ne param('item')) {
	    print $dbfile join("|",@{$row}),"\n";
	}
    }
    close($dbfile);
    Delete('deleteitem');
    
    # horribly inefficient :(
    &read_categories;
    &read_products;
}


# get next page
###############
if (param('submit')) {
    if (param('item')) {
	Delete($_) foreach("name","description","price","item","image","weight","oldproduct","custaction");#"product"
#	Delete('product') if (!param('cancel'));
    } elsif (param('editcat')) {
	if (param('cancel')) {
	    if (defined(param('oldproduct'))) {
		param('product',param('oldproduct'));
	    } else {
		Delete('product');
	    }
	}
	Delete($_) foreach("description","editcat","oldproduct","image","width","height","weight","parent","custaction");
    } elsif (param('deletecat')) {
	Delete($_) foreach("product","deletecat");
    } elsif (param('deleteitem')) {
	Delete($_) foreach("item","deleteitem");
    }
    Delete('submit');
    Delete('cancel');
}
    Delete('errorok');
    if ($page=~/^step/) { Delete($_) foreach('next','prev','wiz_submit',grep(/^_/,param())) }
    if ($error) {
	print heading('Error'),nexplain($error);
	foreach my $p (param()) {
	    print hidden($p);
	}
	print imgsubmit(errorok,'continue','Continue');
	return;
    }

print dump if ($debug);


# print the page
################

if (param('editcat')) {
    if (param('editcat') eq "new") {
	print heading "Create New Category";
	my $i;
#	for($i=1;defined($category{"New Category".(($i==1)?"":" ($i)")});$i++){}
#	param('product',"New Category".(($i==1)?"":" ($i)"));
	for($i=((scalar keys %category)+1);defined($category{"Category $i"});$i++){}
	param('product',"Category $i");
    } else {
	if (!defined($category{param('product')})) {
	    $error="No such category: ".param('product');
	}
	print heading "Edit Category";
	param('oldproduct',param('product'));
	print hidden('oldproduct');
    }
    require "./Library/imageurl.pl";
    print start_table,Tr([
		    td(["Category name", textfield(-name=>"product", -value=>param('product'))]),
			  td(["Description", textarea(-name=>"description", -value=>(demunge $category{param('product')}->[$cat{'description'}]), -rows=>4, -cols=>35,-wrap=>1)])]);

	print Tr([
		  td(["Image",filefield("image")]),
		    ]);

	print Tr([
		  td(["Parent category",
		      popup_menu({
			  name=>'parent',
			  default=>$category{param('product')}->[$cat{'parent'}],
			  labels=>{''=>'[None]'},values=>['',grep{$_ ne param('product') && !$category{$_}->[$cat{'products'}]} sort keys %category]
			  }),
		      ]),
		  ]);

    if (havepage('cart')) {
	print Tr([
		  td(["Default weight",textfield(-name=>"weight",
						 -value=>$category{param('product')}->[$cat{'weight'}],-size=>6)."kg"]),
		  explain('This is an advanced feature. If most products in this category weigh the same, you can set a standard weight to save you typing it in for each product.'),
		 ]);
    }
    print end_table;
    if (param('editcat') ne 'new') {
	my $image=$category{param('product')}->[$cat{'image'}];
	print "Current image: ",imageurl($image,"../preview$demoid/"),br;
    }

    print hidden('page');
    print hidden('editcat');
    print hidden('submit'=>"yes");
    print imgsubmit('editcat_submit','ok',"OK");
    print imgsubmit('cancel','cancel',"Cancel");

} elsif (param('item')) {
    my @item;
    if (param('item') eq "new") {
	print heading "Create New Product";
	param('name',"Product ".($max_items+1));
	$item[$db{'weight'}]=$category{param('product')}->[$cat{'weight'}] if (param('product'));
    } else {
	print heading "Edit Product";
	foreach $row (@products) {
	    if (($row->[$db{"product_id"}]) eq param('item')) {
		@item=@{$row};
	    }
	}
    }

    $item[$db{'custaction'}]=(havepage('cart'?'b':'i'));
    if ($item[$db{'weight'}]=~s/__(.*)//g) {
	$item[$db{'custaction'}]=$1;
    }

    my $item=param('item');
#    my $image=readlink("$image_dir/$item");
    my $image=$item[$db{'image'}];

    print start_table;
    print Tr([
		    td(["Product Code",dbfield("name",\@item)]),
		    explain('A unique identifier for your product.'),
		    td(["Product Description",dbfunc("description", \@item, \&textarea, -cols=>35, -rows=>4, -wrap=>1)]),
		    td(["Price","&pound;".dbfield("price",\@item,-size=>6)]), #FIXME
	      ]);

    print Tr([
	      td(["Actions",dbfunc("custaction",\@item,\&popup_menu,
				   -values=>[
					     (havepage('cart')?('b'):()),
					     'i',
					     'ip',
					     (havepage('cart')?('bi'):()),
					     's',
					     ],
				   -labels=>{
					     b=>'Buy only',
					     i=>'Info only',
					     bi=>'Buy/Info',
					     ip=>'Info with price',
					     s=>'Out of stock notice',
					     },
				   )
		  ])
	      ]),
		  explain('Actions available to the customer.');

    if (havepage('cart')) {
	print Tr([
		  td(["Weight",dbfield("weight",\@item,-size=>6)."kg"]), #FIXME
		 explain('The weight is only for automatic shipping calculations. If you do not require weight-based shipping, it may be left blank.'),
		 ]);
}
    print Tr([
	      td(["Category",dbfunc("product",\@item,\&popup_menu,-values=>[
									    grep{my $thiscat=$_;!grep{$category{$_}->[$cat{'parent'}] eq $thiscat}keys%category} sort keys %category],
				    
				    -default=>param('product'))]),
	      td(["Image",filefield("image")]),
	      ]);
    print end_table;
#    print image({src=>"../preview/images/$image",border=>2}) if ($image);
    require "./Library/imageurl.pl";
    print "Current image: ".imageurl($image,"../preview$demoid/");

    param('oldproduct',param('product'));
    print hidden('oldproduct');
    print hidden('item');
    print hidden('page');
    print hidden(submit=>"yes");
    print br;
    print imgsubmit('item_edit_submit','ok',"OK");
    print imgsubmit('cancel','cancel',"Cancel");
} elsif (defined(param('product'))) {
    print heading "Category: ".param('product');
    print h4($category{param('product')}->[$cat{'description'}]);

    if ($category{param('product')}->[$cat{'products'}]) {

	print start_table({border=>undef,align=>'center'});
	print th(["Name","Description","Price (&pound;)"]);
	print th(["Weight (kg)"]) if ($cd{'shopping_cart'});
	print th(["Delete"]);
	foreach $row (@products) {
	    if (($row->[$sc_db_index_of_category]) eq param('product')) {
		param('item',$row->[0]);
		print "<TR>";
		print 
		    td(a({href=>url(-query=>1,-relative=>1)},[$row->[$db{"name"}]||'[blank]'])),
		    td([$row->[$db{"description"}]||'[blank]']),
		    td([$row->[$db{"price"}]||'&nbsp;']);
		print td([$row->[$db{"weight"}]||'&nbsp;']) if ($cd{'shopping_cart'});
		
		param("deleteitem","yes");
		param("submit","yes");
		print td(a({href=>url(-query=>1,-relative=>1)},"Delete product"));
		Delete("deleteitem");
		Delete("submit");
		print "</TR>";
	    }
	}
	print end_table;
	print nexplain("Click on a product name to alter the product details. Click 'Delete' to delete a product.");
    } elsif (!grep{$category{$_}->[$cat{'parent'}] eq param('product')}keys %category) {
	print nexplain("There are no products in this category. Click 'Create new product' to create a product.");
    }
#    Delete($_) foreach ('item','product');
    
    if (!grep{$category{$_}->[$cat{'parent'}] eq param('product')}keys %category) {
	# if no subcategories
	param("item","new");
	print br, center a({-href=>url(-query=>1,-relative=>1)},"Create new product");
	Delete("item");
	print nexplain("Click here to create a new product in this category.");
    } else {
	print start_table({border=>undef,align=>'center'});
	print th([
		  "Sub-categories",
#		  "Description",
		  ]);
	my $thiscat=param('product');
	print Tr([
			map{
			    param('product',$_);
			    td([a({href=>url(-query=>1,-relative=>1)},$_),
#				$category{$_}->[$cat{'description'}]
				])				
			    }
			grep{$category{$_}->[$cat{'parent'}] eq $thiscat}keys %category
			]);
	print end_table;
	print br;
	param('product',$thiscat);
    }

    if (!$category{param('product')}->[$cat{'products'}]) {
	param("editcat","new");
	param("parent",param('product'));
	print br, center a({-href=>url(-query=>1,-relative=>1)},"Create new sub-category");
	Delete("parent");
	Delete("editcat");
	print nexplain("Click here to create a new sub-category in this category.");
    }

    param("editcat","yes");
    print br,center a({href=>url(-query=>1,-relative=>1)},"Edit category");
    print nexplain("Click here to alter the category name and description.");
    Delete($_) foreach ('editcat','product');
    print br,center(a({href=>url(-query=>1,-relative=>1)},"Return to list of categories")),
    nexplain("Click here to return to the main category list, where you can create, delete and view categories.");
} else {
    
    if ($page=~/^step/) {
	print stepheading(6);
    } else {
	print heading "Products";
    }
    if ($page!~/^step/) {
	print start_p, "Database contains $products product";
	print "s" unless ($products==1);
	print ", in $categories categor";
	print (($categories-1)?"ies":"y");
	print ".", end_p;
    }
#    print " ($prod_cats prod_cats)";
    my $treeview=!param('notreeview');
    Delete('notreeview');
    if ($categories) {
	my $can_delete=0;
	
	foreach (sort keys %category) {
	    my $thiscat=$_;
	    if (!$category{$_}->[$cat{'products'}] &&
		!grep{$category{$_}->[$cat{'parent'}] eq $thiscat}keys %category) {
		$can_delete=1;
	    }
	}
	if ($treeview) {
	    print style({type=>'text/css'},'li{margin-top:.2em;margin-bottom:.2em;/*border-top: 1px dashed gray;*/clear:both}/*li:first-child{border-top:hidden}*/.info{float:right}');
	    recurse();
	    Delete('product');
	} else {

#	print start_p,"Categories are:";#,li([sort keys(%category)]);
#	print hr;
	    print start_table({border=>undef,align=>'center'});
	    print th(["Name","Parent","Products",$can_delete?"Delete":()]);
	    foreach (sort keys %category) {
		print "<TR>";#start_Tr;
		param("product",$_);
#	    param("editcat","yes");
		print td(a({-href=>url(-query=>1,-relative=>1)},$_||'[blank]'));
##	    Delete("editcat");
##	    if ($category{$_}->[$cat{'products'}]) {
#	    my $temp="(".($category{$_}->[$cat{'products'}]||"no"). " product";
#	    $temp.="s" unless $category{$_}->[$cat{'products'}]==1;
#	    $temp.=")";
#	    print td($temp);
		print td({-align=>'center'},$category{$_}->[$cat{'parent'}]||'[None]');
		print td({-align=>'center'},$category{$_}->[$cat{'products'}]);
#	    print td(a({-href=>url(-query=>1,-relative=>1)},$temp));
#	    } else {
#		print td("(no products)");
		print end_a;
		my $thiscat=$_;
		if (!$category{$_}->[$cat{'products'}] && !grep{$category{$_}->[$cat{'parent'}] eq $thiscat}keys %category) {
		    param("deletecat","yes");
		    param("submit","yes");
		    print td(a({-href=>url(-query=>1,-relative=>1)},"Delete category"));
		    Delete("deletecat");
		    Delete("submit");
		} else {
		    if ($can_delete) {
			print td '&nbsp;';
		    }
		}
		print "</TR>";#end_Tr;
#	    print " ";
#	    print end_li;
	    }
	    print end_table;
#	    print hr;
	    Delete("product");
	}
	    print nexplain("Click on a category name above to view/alter products in that category.".($can_delete?" Click 'Delete category' to remove an empty category.":''));
##	param("item",$max_items+1);
#	param("item","new");
#	print br, center a({-href=>url(-query=>1,-relative=>1)},"Create new product");
#	Delete("item");
#	print explain("Click here to create a new product.");
    } else {
	print br,nexplain("You must create a category before you can start entering products.");
    }
	param("editcat","new");
	print br,br,center(a({-href=>url(-query=>1,-relative=>1)},"Create new category")),
    nexplain("Click here to create a new category.");

    Delete('editcat');
    if (keys %category) {
	if ($treeview) {
	    param('notreeview','yep');
	    print br,br,center(a({-href=>url(-query=>1,-relative=>1)},"Flat view")),
	    nexplain("Click here to view categories as a list.");
	} else {
	    param('notreeview','');
	    print br,br,center(a({-href=>url(-query=>1,-relative=>1)},"Tree view")),
	    nexplain("Click here to view categories hierarchically.");
	}
	Delete('notreeview');
    }
    if ($page=~/^step/) {
	print br,br,br,explain("Click 'Next' when you've finished entering products.");
	print stepsfooter();
    }
}

}


sub recurse {
    use CGI qw/start_ul end_ul start_li end_li/;
    my $parent=shift;
    my $loopcheck=shift;
    my @cats=sort grep {$category{$_}->[$cat{'parent'}] eq $parent} keys %category;
    if (@cats) {
	print start_ul;
	for (@cats) {
	    my $thiscat=$_;
	    print start_li;
	    param("product",$_);
	    if ($category{$_}->[$cat{'products'}]) {
		my $temp="(".($category{$_}->[$cat{'products'}]||"no"). " product";
		$temp.="s" unless $category{$_}->[$cat{'products'}]==1;
		$temp.=")";
		print span{class=>'info'},$temp;


	    } elsif (!grep{$category{$_}->[$cat{'parent'}] eq $thiscat}keys %category) {
		param("deletecat","yes");
		param("submit","yes");
		print span{class=>'info'},a({-href=>url(-query=>1,-relative=>1)},"Delete category");
		Delete("deletecat");
		Delete("submit");
	    }
	    print a({-href=>url(-query=>1,-relative=>1)},$_||'[blank]');
	    recurse($_,++$loopcheck) if $loopcheck<10;
	    print end_li;
	}
	print end_ul;
    }
};


1;
