use strict;

return sub
{
	my $dbh = shift;
	

	my $sth = $dbh->prepare("select id,title,trigger_url,trigger_secret,trigger_method from jin_quest where trigger_url!='' and api_post_quest=''");
	$sth->execute;

	while (my $row = $sth->fetchrow_hashref)
	{
		my $quest = $row;


		$dbh->do("LOCK TABLES zen_id_dbtable WRITE");

		my $sth1 = $dbh->prepare("SELECT curvalue FROM zen_id_dbtable WHERE sqltable='jin_api_post' AND sqlfield='id'");
		$sth1->execute;
		my $api_post_id = $sth1->rows > 0 ? $sth1->fetch->[0] : undef;
	
		unless ($api_post_id)
		{
			$dbh->do("LOCK TABLES zen_id_dbtable WRITE, jin_api_post WRITE");

			$sth1 = $dbh->prepare("SELECT max(id) from jin_api_post");
			$sth1->execute;
			$api_post_id = $sth1->rows > 0 ? $sth1->fetch->[0] : 0;

			$dbh->do("insert into zen_id_dbtable (sqltable,sqlfield,curvalue) values ('jin_api_post','id','$api_post_id')");
		}
	
		$api_post_id++;
	
		$dbh->do("update zen_id_dbtable set curvalue='$api_post_id' where sqltable='jin_api_post' and sqlfield='id'");
		$dbh->do("UNLOCK TABLES");
		
		
		my $params = "quest_id=#{Quest.id}\n";
		$params .= "quest_title=#{Quest.title}\n";
		$params .= "quest_secret=$quest->{trigger_secret}\n";

		$sth1 = $dbh->prepare("select * from jin_quest_item where quest_id=? order by seq");
		$sth1->execute($quest->{id});
	
		my $i = 0;
	
		while (my $row1 = $sth1->fetchrow_hashref)
		{
			$i++;
			
			$params .= "#{field$i}=#{value$i}\n";
			
			if (my $f = $row1->{qsfield})
			{
				$params .= "$f=#{value$i}\n";
			}
		}

		for (qw/
		
			id ctime pack_id aff_user_id aff_camp_id 
			
			user_id
			
			user_email
			user_fname
			user_lname
			user_name
			
			user_address
			user_city
			user_state
			user_zipcode
			user_country
			
			user_phone
			user_company

		/)
		{
			$params .= "order_$_=#{Order.$_}\n";
		}


		for (qw/id amount prod_id paid txn_pgate_type txn_code/)
		{
			$params .= "sale_$_=#{Sale.$_}\n";
		}
		
		my $api_post = {
			id => $api_post_id,
			type => 'quest',
			title => qq(Questionnaire "$quest->{title}"),
			url => $quest->{trigger_url},
			params => $params,
			method => $quest->{trigger_method},
		};

		my @sql_fields = keys %$api_post;
		my $insert_set = join ',', map { "$_=?" } @sql_fields;

		$dbh->do("insert into jin_api_post set events='create',$insert_set", undef, map { $api_post->{$_} } @sql_fields);

		$dbh->do("update jin_quest set api_post_quest=? where id=?", undef, $api_post_id, $quest->{id});
		

		my $sth2 = $dbh->prepare("select * from jin_user_quest where quest_id=? and triggerdata!=''");
		$sth2->execute($quest->{id});
	
		my $sth3 = $dbh->prepare("update jin_user_quest set triggerdata=? where id=?");
	
		while (my $row1 = $sth2->fetchrow_hashref)
		{
			(my $text = $row1->{triggerdata}) =~ s/([%:\r\n])/sprintf('%%%02X', ord($1))/ge;

			$sth3->execute("id:$api_post_id:ok:1:text:$text", $row1->{id});
		}

	}
	
	return;
};
