<%args>
$filename => undef
$user=>undef
$updt=>undef
</%args>
<%init>
if ($user){
	
	if ($filename){
	
		# chave de download
		my $req_key = $m->comp("getreqkey.m", filename=>$filename);
		return 3 unless $req_key;
		
		# no de registos
		my $records =  $m->comp("getreqrecords.m", filename=>$filename);
		
		# creditos correspondentes
		my $req_credits = $m->comp("getreqcredits.m", records=>$records);
	
		my $dbh = $m->comp("/_shared/procs/utils/dbi_connect.m", database=>'guianet');
		
		# actualizacao
		if ($updt){
			
			$dbh->do("insert into tdownloads_updt_history(updatedid,records,reqdate) values('$updt',$records,NOW())");
			return $dbh->errstr if $dbh->err;
			
			$dbh->do("update tdownloads_history set updated='Y' where id='$updt'");
			return $dbh->errstr if $dbh->err;

		# ou download inicial
		}else{
			
			$dbh->do("insert into tdownloads_history(username,reqkey,records,credits,reqdate) values('$user','$req_key',$records,$req_credits,NOW())");
			return $dbh->errstr if $dbh->err;
			
			$dbh->do("update tdownloads set downloads=downloads+1 where reqkey='$req_key'");
			return $dbh->errstr if $dbh->err;
		
			$dbh->do("update tdownloads_credits set credits=credits-$req_credits where username='$user'");
			return $dbh->errstr if $dbh->err;
			
			# update john table
			my ($err, $errstr) = $m->comp("update_credits.m", user=>$user, credits=>$req_credits);
			#return $errstr if ($err);
	
		}
		
		
		return 0;
	
	}else{
		
		return 2;
		
	}
}else{
	
	return 1;
	
}
</%init>
