use strict;

return sub
{
	my $dbh = shift;
	
	{
		my $sth = $dbh->prepare("select au.* from jin_api_user au inner join jin_api_gate ag on au.id=ag.id where ag.specusers=0");
		$sth->execute;

		my @names = qw/
			u_all
			u_selected
			u_since
			u_cust_new
			u_cust_packs
			u_cust_prods
			u_affprogs
			u_roles
			u_memberships
			u_insignia
			u_surveys
			u_paid_min
			u_paid_max
			u_generated_min
			u_generated_max
			u_count_sales_from
			u_count_sales_until
		/;

		$dbh->do("delete from zen_id_dbtable");

		my $sth1 = $dbh->prepare("select max(id) from jin_specusers");
		$sth1->execute;
		my $max_id = $sth1->rows > 0 ? $sth1->fetch->[0] : 0;

		$sth1 = $dbh->prepare("insert into jin_specusers set id=?, type='local', title=?, notes=?, " . join(', ', map { "$_=?" } @names));
		my $sth2 = $dbh->prepare("update jin_api_gate set specusers=? where id=?");
	
		while (my $row = $sth->fetchrow_hashref)
		{
			my $new_specusers_id = ++$max_id;
			$sth1->execute($new_specusers_id, $row->{title}, 'Created automatically when converting "Tools / API Users" to "Profile / Delavo API Center"', map { $row->{$_} } @names);
			$sth2->execute($new_specusers_id, $row->{id});
		}
	}

	{
		my $sth = $dbh->prepare("select id from jin_api_gate where find_in_set('importsale',apicalls) and find_in_set('processsale',apicalls)");
		$sth->execute;
		
		unless (my $row = $sth->fetchrow_hashref)
		{
			$dbh->do("delete from zen_id_dbtable");
	
			my $sth1 = $dbh->prepare("select max(id) from jin_api_gate");
			$sth1->execute;
			my $max_id = $sth1->rows > 0 ? $sth1->fetch->[0] : 0;
	
			$sth1 = $dbh->prepare("insert into jin_api_gate set id=?, title='API Connector for Import Sale and Process Sale calls<br>(feel free to rename it or delete it if not needed)', apikey='dummy', apicalls='importsale,processsale'");
			$sth1->execute(++$max_id);
		}
	}


	return;
};
