####### SETUP ######

// duration of the subscription in days
$days = 30;

// ambrasubs subscription type ID
$type = 1;

// the price for the subscription (same you add to the PayPal button in the form!)
$price = 5.00;

// optional: If a user is already logged in and registered, he doesn't need to enter the data again.
// So please provide the url to the subscription main page that holds a PayPal button.
// You can copy the url directly from your menu-item.
$ambraUrl = '';

// optional: e.g. Google conversion tracking code
$trackingCode = '';

###################

if($ambraUrl != '' && JFactory::getUser()->get('id',-1) > 0){
 header('Location: ' . $ambraUrl);
 exit;
}

if($trackingCode != '' && JRequest::getInt('ff_page',0) == 2){
  echo $trackingCode;
}

$expires = date('Y-m-d H:i:s', strtotime('now + '.$days.' days'));

$db = JFactory::getDBO();
$db->setQuery("Select * From #__facileforms_records Where name = ".$db->Quote($this->formrow->name)." And paypal_tx_id <> ''");
$list = $db->loadObjectList();
$listSize = count($list);

for($i = 0; $i < $listSize;$i++){
	$db->setQuery("Select * From #__ambrasubs_payments Where payment_type = 'paypalbf' And payment_id = " . $db->Quote($list[$i]->paypal_tx_id));
        if(count($db->loadObjectList()) == 0){
          $db->setQuery("Insert Into #__ambrasubs_payments ( payment_type, payment_id, created_by, payment_datetime, payment_amount, created_datetime ) Values ( 'paypalbf', ".$db->Quote($list[$i]->paypal_tx_id).", ".$list[$i]->user_id.", ".$db->Quote($list[$i]->paypal_payment_date).", '".$price."', '".date('Y-m-d H:i:s')."' )");
          $db->query();
          $paymentid = $db->insertid();
	  $db->setQuery("Insert Into #__ambrasubs_users2types ( userid, typeid, paymentid, status, expires_datetime ) Values ( ".$list[$i]->user_id.", ".$type.", ".$paymentid.", 1, '".$expires."' )");
          $db->query();
        }
}