<?php

include "./infusion-config.php";

$config   = "<pre>";
$config  .= print_r($_POST, true);
$config  .= "</pre>";
$fp       = fopen('./cbreceipts/'. $_POST['txn_id'] . '-' . $_POST['payment_status'] . ".txt", "w+");
//$fp       = fopen( "358.txt", "w+");
fwrite($fp, $config);
fclose($fp);

//--------------------------------------------------------------------------------
/*
// Test array para pruebas.
// Customer fields

$ccustemail   		 	= 'victor.asburgos@gmail.com';
$ccustfullname       	= ucwords(strtolower('victor burgos'));    	// Customer's full name 	1-510 Characters
$ccustfirstname		 	= ucwords(strtolower('VICTOR'));	// Customer's first name 	0-255 Characters
$ccustlastname 		 	= ucwords(strtolower('burgos AGUDELO'));    	// Customer's last name 	0-255 Characters
$ccustaddr1    			= 'Calle 1 2 y 3';  				// Customer's shipping address: field 1 	0-255 Characters ** Only populated for vendor notifications
$ccustaddr2    			= 'Segunda casa con ñ';  				// Customer's shipping address: field 2 	0-255 Characters ** Only populated for vendor notifications
$ccustcity    			= 'San José';  				// Customer's shipping address: City 	0-255 Characters ** Only populated for vendor notifications
$ccuststate    			= '';  				// Customer state 	0-2 Characters
$ccustzip    			= '10109';  					// Customer zip/postal code 	0-16 Characters
$ccustcounty    		= 'Costa Rica'; 				// Customer's shipping address: County 	0-255 Characters ** Only populated for vendor notifications
$ccustcc    			= 'CR';  					// Customer country code 	0-2 Characters
$ccustshippingzip		= '';  			// Customer's shipping address: Zip/postal code 	0-255 Characters ** Only populated for vendor notifications
$ccustshippingcountry   = ''; 		// Customer's shipping address: Country 	0-255 Characters ** Only populated for vendor notifications
$ccustshippingstate 	= '';  		// Customer's shipping address: State 	0-2 Characters ** Only populated for vendor notifications

// Status field
$ctransaction			= 'SALE';  				// Action taken 	4-15 Characters * See "Transaction Types"

// Product fileds 
$cprodtitle				= 'Titulo del Curso de infra 2010'; 				// Title of product at time of purchase 	0-255 Characters
$cproditem				= 'CI2010'; 					// ClickBank product number 	1-5 Characters

// Order fields
$ctransreceipt			= 'ZGQQ6LE9'; 				// ClickBank receipt number 	8-13 Characters
$cprodtype				= 'STANDARD'; 					// Type of product on transaction (STANDARD or RECURRING) 	8-11 Characters
$ctranspaymentmethod	= 'PYPL'; 		// Method of payment by customer 	0-4 Characters See "Payment Methods"
$corderamount			= 10000; 				// Order total amount (in pennies (1000 = $10.00)) 	3-10 Characters
$corderamountUSD		= round( ($corderamount/100), 2 ); 		// Se divide por 100 para que de el valor en dólares y se redondea para que de 2 decimales.
$caccountamount			= ''; 			// Amount paid to party receiving notification (in pennies (1000 = $10.00)) 	3-10 Characters
$cfuturepayments		= ''; 			// Number of payments remaining 	0-2 Characters ** Only populated for vendor notifications
$crebillfrequency		= ''; 
$cupsellreceipt			= ''; 			// Parent receipt number for upsell transaction 	8-13 Characters ** Only populated when purchase is an upsell
$ccurrency				= ''; 				// Customer's payment currency 	3 Characters
$corderlanguage			= ''; 
$ctranstime				= ''; 				// The Epoch time the transaction occurred (not included in cverify) 	10 Characters
$ctaxamount				= ''; 
$cshippingamount		= '';

// Subscription/recurring fileds
$crebillstatus			= ''; 				// Status of subscription (empty, ACTIVE, COMPLETED, or CANCELED) 	0-10 Characters ** Only populated when purchase is an upsell
$crebillamnt			= ''; 				// Recurring payment amount (in pennies (1000 = $10.00)) 	0-10 Characters ** Only populated for vendor notifications
$cnextpaymentdate		= '';  			// Date of next payment (epoch time) 	0-10 Characters ** Only populated for vendor notifications
$cprocessedpayments		= ''; 		// Number of recurring payments made 	0-2 Characters ** Only populated for vendor notifications

// Affiliate and other fields
$ctransaffiliate		= ''; 			// Affiliate on transaction 	0-10 Characters
$ctid					= ''; 						// Tracking ID 	0 - 255 Characters
$cverify				= ''; 					// Used to verify the validity of the previous fields 	8 Characters
$cnoticeversion			= ''; 
$cbf					= ''; 
$cbfid					= ''; 
$cvendthru				= ''; 					// Extra information passed to order form with duplicated information removed 	0-1024 Characters
$ctransvendor			= ''; 				// Vendor on transaction 	5-10 Characters
$ctransrole				= ''; 				// Recipient's role in the transaction 	6-9 Characters
$cbfpath				= ''; 
*/

/**
 * verify transaction, return 0 or 1
**/
function pk_cbsn_ipnVerification() 

{
return 1;
}

// Lista de paises con el código
$countries = array('AF' => 'Afghanistan', 'AL' => 'Albania', 'DZ' => 'Algeria', 'AD' => 'Andorra', 'AO' => 'Angola', 'AG' => 'Antigua and Barbuda', 'AR' => 'Argentina', 'AM' => 'Armenia', 'AU' => 'Australia', 'AT' => 'Austria', 'AZ' => 'Azerbaijan', 'BS' => 'The Bahamas', 'BH' => 'Bahrain', 'BD' => 'Bangladesh', 'BB' => 'Barbados', 'BY' => 'Belarus', 'BE' => 'Belgium', 'BZ' => 'Belize', 'BJ' => 'Benin', 'BT' => 'Bhutan', 'BO' => 'Bolivia', 'BA' => 'Bosnia and Herzegovina', 'BW' => 'Botswana', 'BR' => 'Brazil', 'BN' => 'Brunei', 'BG' => 'Bulgaria', 'BF' => 'Burkina Faso', 'BI' => 'Burundi', 'KH' => 'Cambodia', 'CM' => 'Cameroon', 'CA' => 'Canada', 'CV' => 'Cape Verde', 'CF' => 'Central African Republic', 'TD' => 'Chad', 'CL' => 'Chile', 'CN' => 'China', 'CO' => 'Colombia', 'KM' => 'Comoros', 'CG' => 'Congo, Republic of the', 'CD' => 'Congo, Democratic Republic of the', 'CR' => 'Costa Rica', 'CI' => 'Cote d\'Ivoire', 'HR' => 'Croatia', 'CU' => 'Cuba', 'CY' => 'Cyprus', 'CZ' => 'Czech Republic', 'DK' => 'Denmark', 'DJ' => 'Djibouti', 'DM' => 'Dominica', 'DO' => 'Dominican Republic', 'TL' => 'Timor-Leste', 'EC' => 'Ecuador', 'EG' => 'Egypt', 'SV' => 'El Salvador', 'GQ' => 'Equatorial Guinea', 'ER' => 'Eritrea', 'EE' => 'Estonia', 'ET' => 'Ethiopia', 'FJ' => 'Fiji', 'FI' => 'Finland', 'FR' => 'France', 'GA' => 'Gabon', 'GM' => 'Gambia', 'GE' => 'Georgia', 'DE' => 'Germany', 'GH' => 'Ghana', 'GR' => 'Greece', 'GD' => 'Grenada', 'GT' => 'Guatemala', 'GN' => 'Guinea', 'GW' => 'Guinea-Bissau', 'GY' => 'Guyana', 'HT' => 'Haiti', 'HN' => 'Honduras', 'HU' => 'Hungary', 'IS' => 'Iceland', 'IN' => 'India', 'ID' => 'Indonesia', 'IR' => 'Iran', 'IQ' => 'Iraq', 'IE' => 'Ireland', 'IL' => 'Israel', 'IT' => 'Italy', 'JM' => 'Jamaica', 'JP' => 'Japan', 'JO' => 'Jordan', 'KZ' => 'Kazakhstan', 'KE' => 'Kenya', 'KI' => 'Kiribati', 'KP' => 'Korea, North', 'KR' => 'Korea, South', 'ZZ' => 'Kosovo', 'KW' => 'Kuwait', 'KG' => 'Kyrgyzstan', 'LA' => 'Laos', 'LV' => 'Latvia', 'LB' => 'Lebanon', 'LS' => 'Lesotho', 'LR' => 'Liberia', 'LY' => 'Libya', 'LI' => 'Liechtenstein', 'LT' => 'Lithuania', 'LU' => 'Luxembourg', 'MK' => 'Macedonia', 'MG' => 'Madagascar', 'MW' => 'Malawi', 'MY' => 'Malaysia', 'MV' => 'Maldives', 'ML' => 'Mali', 'MT' => 'Malta', 'MH' => 'Marshall Islands', 'MR' => 'Mauritania', 'MU' => 'Mauritius', 'MX' => 'Mexico', 'FM' => 'Micronesia, Federated States of', 'MD' => 'Moldova', 'MC' => 'Monaco', 'MN' => 'Mongolia', 'ME' => 'Montenegro', 'MA' => 'Morocco', 'MZ' => 'Mozambique', 'MM' => 'Myanmar (Burma)', 'NA' => 'Namibia', 'NR' => 'Nauru', 'NP' => 'Nepal', 'NL' => 'Netherlands', 'NZ' => 'New Zealand', 'NI' => 'Nicaragua', 'NE' => 'Niger', 'NG' => 'Nigeria', 'NO' => 'Norway', 'OM' => 'Oman', 'PK' => 'Pakistan', 'PW' => 'Palau', 'PA' => 'Panama', 'PG' => 'Papua New Guinea', 'PY' => 'Paraguay', 'PE' => 'Peru', 'PH' => 'Philippines', 'PL' => 'Poland', 'PT' => 'Portugal', 'QA' => 'Qatar', 'RO' => 'Romania', 'RU' => 'Russia', 'RW' => 'Rwanda', 'KN' => 'Saint Kitts and Nevis', 'LC' => 'Saint Lucia', 'VC' => 'Saint Vincent and the Grenadines', 'WS' => 'Samoa', 'SM' => 'San Marino', 'ST' => 'Sao Tome and Principe', 'SA' => 'Saudi Arabia', 'SN' => 'Senegal', 'RS' => 'Serbia', 'SC' => 'Seychelles', 'SL' => 'Sierra Leone', 'SG' => 'Singapore', 'SK' => 'Slovakia', 'SI' => 'Slovenia', 'SB' => 'Solomon Islands', 'SO' => 'Somalia', 'ZA' => 'South Africa', 'SS' => 'South Sudan', 'ES' => 'Spain', 'LK' => 'Sri Lanka', 'SD' => 'Sudan', 'SR' => 'Suriname', 'SZ' => 'Swaziland', 'SE' => 'Sweden', 'CH' => 'Switzerland', 'SY' => 'Syria', 'TW' => 'Taiwan', 'TJ' => 'Tajikistan', 'TZ' => 'Tanzania', 'TH' => 'Thailand', 'TG' => 'Togo', 'TO' => 'Tonga', 'TT' => 'Trinidad and Tobago', 'TN' => 'Tunisia', 'TR' => 'Turkey', 'TM' => 'Turkmenistan', 'TV' => 'Tuvalu', 'UG' => 'Uganda', 'UA' => 'Ukraine', 'AE' => 'United Arab Emirates', 'GB' => 'United Kingdom', 'US' => 'United States of America', 'UY' => 'Uruguay', 'UZ' => 'Uzbekistan', 'VU' => 'Vanuatu', 'VA' => 'Vatican City (Holy See)', 'VE' => 'Venezuela', 'VN' => 'Vietnam', 'YE' => 'Yemen', 'ZM' => 'Zambia', 'ZW' => 'Zimbabwe');


	if(pk_cbsn_ipnVerification()||'TEST'==$_POST['ctransaction']) // Si la verificación está igual, se hace lo siguiente.
	{
	

	  // Transaction and Notification-Related Variables
        $business               = $_POST['business'];                   // Email address or account ID of the payment recipient
        $txn_id                 = $_POST['txn_id'];                     // Unique Transaction ID. The merchant's original transaction identification number for the payment from the buyer, against which the case was registered.
        $txn_type               = $_POST['txn_type'];                   // The kind of transaction for which the IPN message was sent, ex: web_accept
        $country                = $countries[$_POST['residence_country']]; // Usa array de paises para crear el nombre completo del país.

        // Buyer Information Variables
        $payer_email            = $_POST['payer_email'];
        $first_name             = ucwords(strtolower($_POST['first_name']));    // Customer's first name    0-255 Characters
        $last_name              = ucwords(strtolower($_POST['last_name']));     // Customer's last name     0-255 Characters

        // Buyer Information Variables
        $payer_id               = $_POST['payer_id'];                   // Unique customer ID. Length: 13 characters

        // Payment Information Variables
        $mc_gross               = $_POST['mc_gross'];                   // Full amount of the customer's payment, before transaction fee is subtracted. Equivalent to payment_gross for USD payments. If this amount is negative, it signifies a refund or reversal, and either of those payment statuses can be for the full or partial amount of the original transaction
        $mc_fee                 = $_POST['mc_fee'];                     // Transaction fee associated with the payment. mc_gross minus mc_fee equals the amount deposited into the receiver_email account. Equivalent to payment_fee for USD payments. If this amount is negative, it signifies a refund or reversal, and either of those payment statuses can be for the full or partial amount of the original transaction fee.
        $deposited_amount       = $mc_gross - $mc_fee;                  // mc_gross minus mc_fee equals the amount deposited into the receiver_email account
        $payment_date           = $_POST['payment_date'];               // Time/Date stamp generated by PayPal, in the following format: HH:MM:SS Mmm DD, YYYY PDT. Length: 28 characters
        $payment_status         = $_POST['payment_status'];             // Ver Valores payment_status abajo
        $payer_status           = $_POST['payer_status'];               // verified – Customer has a verified PayPal account. unverified – Customer has an unverified PayPal account.
        $quantity               = $_POST['quantity'];                   // Quantity as entered by your customer or as passed by you, the merchant.
        $payment_type           = $_POST['payment_type'];               // echeck: This payment was funded with an eCheck. instant: This payment was funded with PayPal balance, credit card, or Instant Transfer.
        $item_name              = $_POST['item_name'];                  // Ex: Curso de Infraestructura 2010
        $item_number            = strtolower($_POST['item_number']);    // Ex: Ci-2010



		/*
		------------------
		Transaction Types var $ctransaction
		------------------
		SALE 				The purchase of a standard product or the initial purchase of recurring billing product.
		BILL 				A rebill for a recurring billing product.
		RFND 				The refunding of a standard or recurring billing product. Recurring billing products that are refunded also result in a "CANCEL-REBILL" action.
		CGBK 				A chargeback for a standard or recurring product.
		INSF 				An eCheck chargeback for a standard or recurring product.
		CANCEL-REBILL 		The cancellation of a recurring billing product. Recurring billing products that are canceled do not result in any other action.
		UNCANCEL-REBILL 	Reversing the cancellation of a recurring billing product.
		TEST 				Triggered by using the test link on the site page.
		------------------
		Payment MethodsT
		------------------
		here are a number of values you can receive in the "ctranspaymentmethod" parameter. These values are listed below.

		PYPL,    VISA,    MSTR,    DISC,    AMEX,    SWIT,    SOLO,    JCBC,    DNRS,    ENRT,    AUST,    BLME,    STVA,    MAES


		*/
		// Ids de Action Sets a ejecutar en infusionsoft según el producto, por defecto no tienen números asociados, poner el id del action set, ejemplo: 'SALE'=>206, para que funcione



		echo 'pasmos por el if de los productos<br>';


		// Proceso de infusionsoft
		require_once "isdk.php";
		$myApp = new iSDK;
		$myApp->cfgCon($infusion_app);
		echo 'nos conectamos a infusionsoft <br>' ;
				echo $cbsecret_key;

  #             IF (isset($payer_email) AND ($payer_email) <> "") : // Verifica que la variable de correo esté definida y que no esté vacía.
			// $contacts = $app->dsQuery("Table",Limit of records,Page#,Query,ReturnFieldsArray);
          $arrCONTACT = $myApp->dsQuery('Contact', 1, 0, array("Email" => $payer_email), array("Id")); // Vamos a verificar que si el contacto ya existe en infusionsoft, dsQuery Performs a query across the given table based on the query data

		  $infFIELDS                    = array(); // Define un nuevo array para guardar los datos del cliente.
		  
		  $infFIELDS['_cb'.$cproditem.'aff']       = $ctransaffiliate;
		  $infFIELDS['_cb'.$cproditem.'receipt']       = $ctransreceipt;


		  $infFIELDS['FirstName']       = $first_name;
          $infFIELDS['LastName']        = $last_name;
          $infFIELDS['Country']         = $country;
    	


			// Evalua qué tipo de notificación está enviando clickbank.
		  	// Establecemos variables como falso por defecto.
			$createORDER    = false;
            #$manualPMT      = false;
            $manualPMT      = true; 
            IF ( $payment_status  == 'Completed') :
                // Completed: The payment has been completed, and the funds have been added successfully to your account balance.
                $createORDER  = true;
                $manualPMT    = true;
                $asID         = $arrACTIONSET['SALE'];
            ELSEIF ( $payment_status == 'Refunded') :
                // Refunded: You refunded the payment.
                $asID         = $arrACTIONSET['RFND'];
            ELSEIF ( $payment_status == 'Reversed') :
                // Reversed: A payment was reversed due to a chargeback or other type of reversal. The funds have been removed from your account balance and returned to the buyer. The reason for the reversal is specified in the ReasonCode element.
                $asID         = $arrACTIONSET['CGBK'];   
            ELSE:
                //If the http post we receive is something else, we run this action set
                $asID         = $arrACTIONSET['UNK'];
            ENDIF;


			// Si es necesario crear una orden, la creamos y agregamos el ítem a la orden.
			/* http://help.infusionsoft.com/api-docs/invoiceservice
							Parameter Name 		Type 		Definition
							privateKey 			string 		Your Infusionsoft API key
			$conID			contactId 			int 		The Id number of the contact record this order will be connected to
			$ctransreceipt	description 		string 		The name this order will display. This is also the hyperlink to the order found on the contact's order tab
			$orderDATE		orderDate 			dateTime 	Date of order
			$leadAFF		leadAffiliateId 	int 		The Id number of the affiliate you would like placed as the lead affiliate. 0 if no affiliate should be attached
			$saleAFF		saleAffiliateId 	int 		The Id number of the affiliate you would like placed as the sale affiliate. 0 if no affiliate should be attached
			*/
$leadAFF      = 0; // Blank order
            $saleAFF      = 0; // Blank order
            $itemID       = 0; // Order item
            $itemQTY      = 1; // Order item
            $itemTYPE     = 4; // Order item
            $currentDate  = date("d-m-Y");
            $pDate = $myApp->infuDate($currentDate);  
            // Notas para describir el pago  
#            $payDESC        = "Paypal Transaction ID: " . $txn_id ; // manualPmt
            $payDESC        = "Transaction ID: " . $_REQUEST['chargeid'] ; // manualPmt
            $bypassCOMM       = false; // manualPmt A boolean which tells the system if this payment should count towards what the affiliate has earned. This is almost always false.
 #           IF ($createORDER) :
  #              $orderID      = $myApp->blankOrder($conID, $item_number, $pDate, $leadAFF, $saleAFF); // Al final se devuelve un número de orden para usar en el siguiente paso.
                /** 
                * @todo Por algún motivo no se puede poner automáticamente el $item_number al agregar el item a la orden
                *       No estoy seguro porque no funcion, ver si se pude solucionar: http://help.infusionsoft.com/api-docs/invoiceservice#addOrderItem
                */
   #             $orderItemID  = $myApp->addOrderItem($orderID, $item_number, $itemTYPE, (float)$deposited_amount, $itemQTY, $item_number, $item_name);
#                IF (is_bool($orderItemID)) :   // Si la orden se crea correctamente, entonces infusionsoft devuelve TRUE y en este caso hacemos el pago manual.   
                    IF ($manualPMT) :
$orderID="4343";
$orderID=$_REQUEST['orderid'];
echo $orderID;
#$deposited_amount="101";
$deposited_amount=$_REQUEST['amt']/100;
echo $deposited_amount;                  
       $myApp->manualPmt($orderID, (float)$deposited_amount, $pDate, 'CF     ', $payDESC, $bypassCOMM);
                    ENDIF;
#                ENDIF;
 #           ENDIF;
          $asRESULT = $myApp->runAS((int)$conID, (int)$asID);
 #       ENDIF;
#	} else {
		// Error en verificación, no se hace nada.
	}
	  $config  = "<pre>";
        $config .= print_r($_POST, true);
        $config .= 'Resultado Busqueda de contacto: ';
        isset($arrCONTACT) ? $config .= print_r($arrCONTACT, true) : '';
        $config .= 'Resultado Busqueda de orderID: ';        
        isset($orderID) ? $config .= print_r($orderID, true):'';
        $config .= 'Resultado Busqueda de orderItemID: ';
        isset($orderItemID) ? $config .= print_r($orderItemID, true):'';
        $config .= 'Resultado ActionSet: ';
        isset($asRESULT) ? $config .= print_r($asRESULT, true):'';
        $config .= "</pre>";
        $handle =  fopen( dirname ( __FILE__ ) . '/' . $_POST['txn_id'] . '-' . $_POST['payment_status'] . '.txt' , 'a');
        fwrite($handle, $config);
        fclose($handle);

?>
