<?php
require_once 'modules/admin/models/PluginCallback.php';
require_once 'modules/billing/models/class.gateway.plugin.php';

class PluginStormpayCallback extends PluginCallback
{
    
    function processCallback()
    {
        // get ANY POST or GET transfer here
        $_Vars = (strtoupper($REQUEST_METHOD) == "POST") ? $_POST : $_GET;
        
        // ignore browser GET requests
        if (!isset($_Vars['transaction_id'])) {
            return;
        }
        
        $transaction_id = $_Vars[transaction_id];           // the UNIQUE transaction ID at StormPay (can be used to uniquely reference this particular transaction form all other StormPay transactions)
        
        // Now get each of the expected IPN variables from here. Please see the Integration Manual for more details...
        $status = trim($_Vars[status]);                 // the values can be...
                                                            // "SUCCESS" or "ERROR" (NO IPN is POSTed if Customer Cancels transaction or is unable to log in)
                                                            // "REFUND" - money sent BACK to the SENDER (payer_email) from a PREVIOUS payment they made to the RECEIVER (payee_email)
                                                            // "CANCEL" - for a cancelled subscription  (and this will have $0 amount/credit, transaction_id = 0, and the transaction_date is simply the "cancel_date" - which is also sent
                                                            // "CHARGEBACK" - on a payment you  previously received
                                                            // "TEST" - the status is ALWAYS test when you specify the "test_mode" variable in your Buy button link codes and it is properly received by StormPay
    
        $transaction_date = $_Vars[transaction_date];       // the Date/Time of the transaction (timestamp) - in the case of a cancelled subscription, this will simply be the date/time of the cancellation
        $cancel_date = $_Vars[cancel_date];                 // IF a subscription was CANCELLED then you will get a "cancel_date" - in date/time format
        $refund_date = $_Vars[refund_date];                 // IF this is a REFUND then you will get a "refund_date" - in date/time format
        $chargeback_date = $_Vars[chargeback_date];         // IF this is a CHARGEBACK then you will get a "chargeback_date" - in date/time format
        $secret_code = $_Vars[secret_code];                 // BLANK if you did NOT set your SECRETE CODE in the "Profile / Setup" at the "IPN Configuration" section
        $vendor_id = (integer)$_Vars[vendor_id];            // if sent in a Button Link Codes
        $vendor_email = $_Vars[vendor_email];               // if sent in a button link code
        $associates = $_Vars[associates];                   // if sent in a button link code (see Integration Manual for details)
        $credit = (float)$_Vars[credit];                    // The TOTAL (GROSS) amount PAID to you (INCLUDING any Tax and/or Shipping sent in your Link Codes, as the case may be)
        $amount = (float)$_Vars[amount];                    // SAME value as the credit
        $donation = (float)$_Vars[donation];                // SAME value as the credit - the TOTAL (GROSS) amount PAID to you as a DONATION(for charity, gifting, etc)
    
        $transaction_type = $_Vars[transaction_type];   // "The SAME as the transaction "Type" stored in the transaction record at StormPay.
                                                            // The values would be...
                                                            // "Payment" - for all direct payments at the StormPay site, AND for all payments from a "Single Item" Buy buy button and "Shopping Cart" Check Out buton.
                                                            // "Subscription" - for ALL subscription payments (incuding the initial subscription Buy button "registration", and all subsequent recurrent (re-occuring) payments)
                                                            // "Donation" - for any money sent through a Donaion button.
    
        $transaction_fee = (float)$_Vars[transaction_fee];  // the TRANSACTION FEES charged by StormPay for this transaction. (IF a fee is charged at the time of the transaction)
                                                            // The RECEIVER ("payee_email") pays the transaction fees.
                                                            // Hence, the actual amount credited to the PAYEE's StormPay Account BALANCE is = ("amount" - "transaction_fee")
                                                            // IF the "payee_email" is NOT yet registered at StormPay, this variable is NOT sent as the "transaction_fee" is DELAYED until the "payee_email" is registered AND confirmed.
    
        $unit_price = (float)$_Vars[unit_price];            // IF a unit price is sent in the button Link code OR if the transaction was form an "Open Amount" or "Donation" Buy Button
    
        $quantity = trim($_Vars[quantity]);                 // This value MIGHT be BLANK if NOT sent in your link Codes (i.e. in the case of a transaction that originate from your Buy button).
                                                            // This variable is NOT available for Shopping Cart transactions involving more than 1 item.
                                                            // If you did NOT send this value in your Link Codes (as the case may be), in some cases StormPay will assume a default value of 1,
                                                            // If this value is returned as BLANK (or zero) and this is NOT a Shopping Cart transaction, then you may assume a (default) quantity of 1 (as the case may be)
    
        $tax = (float)$_Vars[tax];                          // IF sent in the buy button Link Code, or if user add it in the "open_amount" request
        $s_and_h = (float)$_Vars[s_and_h];                  // IF sent in the buy button Link Code, or if user add it in the "open_amount" request
        $shipping = (float)$_Vars[shipping];                // SAME as the "s_and_h" variable. Handled exactly like the "s_and_h" variable and BOTH are sent back with the SAME value
    
        $user_id = $_Vars[user_id];                         // IF sent in the buy button Link Code (is also APPENDED to the END of the "return_URL" value IF the "return_URL" was supplied)
                                                                // the "user_id" may be sent in your link codes as "affid" but it will ALWAYS be passed back to you as "user_id"
    
        $payee_email = $_Vars[payee_email];                 // ALWAYS present - the person RECEIVING the payment, OR in the case of a CANCEL or CHARGEBACK the person who was the original payee
        $payer_email = $_Vars[payer_email];                 // ALWAYS present - the person SENDING the payment, OR in the case of a CANCEL or CHARGEBACK the person who was the original payer (payor)
    
        $payer_name = $_Vars[payer_name];                   // ALWAYS present - the NAME of person SENDING the payment in the format - "name or business name (payer@somedomain.com)"
                                                                //                  OR in the case of a CANCEL or CHARGEBACK the name of the person who was the original payer (payor)
                                                                // PLEASE NOTE: This field may contain only an e-mail address enclosed in brackets - "(payer@somedomain.com)",
                                                                //              IF the SENDER does NOT wish to have their personal name or business name sent out.
    
        $category = $_Vars[category];                       // will be BLANK or = "Miscellaneous" IF a recognised "category" was NOT sent in your Link Code
    
        $product_name = $_Vars[product_name]; 
        $item_number=$_Vars[user1];                                                 //user defined varaible contains Item number
        
        $retry_id = (int)$_Vars[retry_id];                  // This is a UNIQUE ID set on IPN DATA for retry POST (this is NOT a transaction id).
                                                            // You ALREADY have the "transaction_id" which you can use
                                                            // to PREVENT duplication (on SUCCESS, REFUND and CHARGEBACK).
                                                            // However, in the event that you did previously received and
                                                            // processed a particular set of IPN data, but StormPay did not
                                                            // get a "proper" HTTP/1.1 202 reply from you, and continue to
                                                            // POST to your server-side script, the existence of the "retry_id"
                                                            // (and he "retry_count" below) would also let you know that
                                                            // StormPay had made at least 1 previous attempt to post
                                                            // the SAME set of IPN data to your server-side script.
                                                            // So especially in the case of a CANCEL (or ERROR) post, which
                                                            // may not have a transaction_id for you to check for duplicates,
                                                            // you can use the "retry_id" to know if you already received that
                                                            // SAME set of IPN data.
                                                            // Again, the "retry_id" is NOT the transaction id. Is is ONLY
                                                            // a UNIQUE identifier on a particular set of IPN data set for
                                                            // RE-TRY POSTing of the IPN data to your script. Set because of
                                                            // previous failed POST attempt OR lack of a "proper" HTTP/1.1 202
                                                            // reply from your script on previous POSTing.
    
        $retry_count = (int)$_Vars[retry_count];        // The amount of RE-TRIES on HTTP POST on the SAME set of IPN
                                                            // data sent to your server-side (IPN) processor.
                                                            // IPN will be POSTed (retried) a MAXIMUM 5 times (if necessary)
    
        // the values retrieved above this line can be stored to a DATABASE from this point on

        $txn_id=$transaction_id;//redefined varaible with new name
        $payment_amount = $_POST['mc_currency'] == "USD" ? $amount : $amount;

        //Create plug in class to interact with CE
        $cPlugin = new Plugin($item_number, 'stormpay', $this->user);
        $cPlugin->setAmount($payment_amount);
        $cPlugin->setAction('charge');
        
        // TODO check that txn_id has not been previously processed
        // TODO check that receiver_email is an email address in your Stormpay account
        switch ($status) {
            case "SUCCESS":
                    $transaction = " Stormpay Payment of $payment_amount was accepted (Stormpay ID:".$txn_id.")";
                    $cPlugin->PaymentAccepted($payment_amount,$transaction);
                    break;
            case "Pending":
                    $transaction = " Stormpay Payment of $payment_amount is pending (Stormpay ID:".$txn_id.")";        
                    $cPlugin->PaymentPending($transaction,$txn_id);
                    break;
            case "ERROR":
                    $transaction = " Stormpay Payment of $payment_amount failed (Stormpay ID:".$txn_id.")";                
                    $cPlugin->PaymentRejected($transaction);
                    break;
            case "TEST":
                    $transaction = " Stormpay Payment Test of $payment_amount Successfull (Stormpay ID:".$txn_id.")";                
                    $cPlugin->PaymentAccepted($payment_amount,$transaction);
                    break;
            case "CANCEL":
                    $transaction = " Stormpay Payment of $payment_amount Cancelled (Stormpay ID:".$txn_id.")";                
                    $cPlugin->PaymentRejected($transaction);
                    break;
            case "REFUND":
                    $transaction = " Stormpay Payment of $payment_amount Refunded (Stormpay ID:".$txn_id.")";                
                    $cPlugin->PaymentRejected($transaction);
                    break;  
        }
    }
}

?>
