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

class PluginAlertpayCallback extends PluginCallback
{


    function processCallback()
    {
        if (!isset($GLOBALS['testing'])) {
            $testing = false;
        } else {
            $testing = $GLOBALS['testing'];
        }

        $this->logger->log(4, 'Alertpay callback invoked');

        if ($this->settings->get('plugin_alertpay_Use Test Mode') == '0' && isset($_POST['ap_test']) && $_POST['ap_test'] == '1')
        {
            $this->logger->log(4, "** Alertpay test mode callback but account is in production mode => callback discarded");
            return;
        }

        if (!isset($_POST['ap_purchasetype'])) {
            $this->logger->log(4, 'Alertpay callback ignored: ap_purchasetype is not defined');
            return;
        }

        if (!isset($_POST['ap_securitycode'])) {
            $this->logger->log(4, 'Alertpay callback ignored: ap_securitycode is not defined');
            return;
        }

        $securitycode = $_POST['ap_securitycode'];

        if ($this->settings->get('plugin_alertpay_Security Code') != $securitycode)
        {
            $this->logger->log(4, "** This is a fraud transaction and you must cancel this =>  callback discarded");
            return;
        }

        $apTransType = $_POST['ap_purchasetype'];

        $apTransID = @$_POST['ap_referencenumber']; // Transaction ID (Unique) (not defined for subscription cancellations)

        $apPayStatus = @$_POST['ap_status']; // Payment Status (not defined for subscription cancellations)

        $apPayAmount = @$_POST['ap_totalamount']; // Total paid for this transaction (not defined for subscription cancellations)

        $tInvoiceID = @$_POST['apc_1']; // This custom field corresponds to the invoiceID

        //$tIsRecurring = @$_POST['apc_3']; // This custom field corresponds to the subscription details enabled or not

        $tGenerateInvoice = @$_POST['apc_2']; // This custom field corresponds to the Generate Invoices After Callback Notification

        $this->logger->log(4, "\$AlertpayTransType: $apTransType; \$AlertpayTransID: $apTransID; \$ALertpayPayStatus: $apPayStatus;");

        $this->logger->log(4, "\$AlertpayPayAmount: $apPayAmount; \$tInvoiceID: $tInvoiceID; \$tIsRecurring: $tIsRecurring; \$tGenerateInvoice: $tGenerateInvoice");

         // Create Plugin class object to interact with CE.
        $cPlugin = new Plugin($tInvoiceID, 'alertpay', $this->user);
        
        

//         $newInvoice = false;
// 
//         // Check to see if this Invoice is already paid.
//         // Skip if this is a call for a cancellation
//         if($cPlugin->IsPaid()==1 && $apTransType == 'Subscription') {
//             $this->logger->log(4, 'Previous subscription invoice is already paid');
//             // If it is, then check to see if the GenerateInvoice variable was passed to the script
//             if($tGenerateInvoice && $tIsRecurring) {
//                 // If it was and is TRUE (1), Generate a New Invoice, and set internal Plugin object
//                 // variables to the new invoice's information.
//                 if ($cPlugin->transExists($apTransID)) {
//                     $newInvoice = $cPlugin->retrieveInvoiceForTransaction($apTransID);
//                     if ($newInvoice && $cPlugin->m_Invoice->isPending()) {
//                         $this->logger->log(4, 'Invoice already exists, and is marked as pending');
//                     }
//                 } else {
//                     $this->logger->log(4, 'Generating new invoice');
//                     $newInvoice = $cPlugin->GenerateNewInvoice($apPayAmount,'', $apTransID);
//                 }
//             } else {
//                 $this->logger->log(1, 'Error: exiting Alertpay callback invocation');
//                 exit;
//             }
//         }

        //Add plugin details
        $cPlugin->m_Amount = $apPayAmount;
        $cPlugin->m_TransactionID = $apTransID;
        $cPlugin->m_Action = "charge";
        $cPlugin->m_Last4 = "NA";

//         if($tIsRecurring) {
//                 // Uncomment to test payment failures through subscription cancellations
//                 // if ($ppTransType == 'subscr_cancel') $ppTransType = 'subscr_failed';
//                 if($apTransType == 'Subscription') {
//                     switch($apPayStatus) {
//                        case "Subscription-Payment-Success":
//                             // Payment was succesful/completed.
//                             $transaction = "Paypal payment of $apPayAmount was accepted. Original Signup Invoice: $tInvoiceID (OrderID:".$apTransID.")";
//                             $cPlugin->PaymentAccepted($apPayAmount,$transaction,$apTransID, $testing);
//                             if ($newInvoice) {
//                                 $cPlugin->updateDateRecurringEntry();
//                             }
//                             break;
//                         case "Subscription-Payment-Failed":
//                             // this is caused by lack of funds for example
//                             $subject = 'Gateway recurring payment failed';
//                             $reason = "No Sufficient fund in account"
//                             $message = "Recurring payment for invoice $tInvoiceID, corresponding to package \"{$_POST['ap_itemname']}\" has failed.\n";
//                             $message .= "Reason: $reason.";
//                             $tUser = new User($cPlugin->m_Invoice->m_UserID);
//                             // if createTicket returns false it's because this transaction has already been done
//                                 if (!$cPlugin->createTicket($_POST['ap_subscriptionreferencenumber'], $subject, $message, $tUser)) exit;
//                             // log failed transaction
//                             $transaction = "Recurring subscription payment failed. Reason: $reason.";
//                             $cPlugin->logFailedSubscriptionPayment($transaction, $_POST['ap_subscriptionreferencenumber']);
//                             break;
// 
//                         case "Subscription-Payment-Canceled":
//                             $this->logger->log(4, "Subscription has been cancelled on Alertpay side or seller cancelled it.");
//                             $tUser = new User($cPlugin->m_Invoice->m_UserID);
//                             if ($tUser->getStatus() == USER_STATUS_CANCELLED) {
//                                 $this->logger->log(4, 'User is already cancelled. Ignore callback.');
//                                 exit;
//                             }
//                             $subject = 'Gateway recurring payment cancelled';
//                             $message = "Recurring payment for invoice $tInvoiceID, corresponding to package \"{$_POST['ap_itemname']}\" has been cancelled by customer.";
//                             // If createTicket returns false it's because this transaction has already been done
// 
//                             if (!$cPlugin->createTicket($_POST['ap_subscriptionreferencenumber'], $subject, $message, $tUser)) exit;
// 
//                             // Reset recurringfee entry so that invoice entry gets generated without the IPN call.
//                             // We don't use the nextbilldate in the recurringfee table cause there was a bug in this plugin's
//                             // early implementation that wasn't updating that field. So we calculate it from scratch every time.
//                             // First we need to determine the next due date.
//                             $cycles = array(
//                                 'D' => 'day',
//                                 'M' => 'month',
//                                 'Y' => 'year',
//                             );
//                         // Warning: don't use $_POST['subscr_date'] here: when $_POST['txn_type'] is 'subscr_cancel' this contains
//                         // the cancellation date, not the subscription date.
//                         
//                         /* There are four possible cases that a subscription cancellation can occur.
//                          *   1) The subscription is cancelled before the next due date
//                          *   2) The subscription is cancelled on the due date (before the payment has gone through)
//                          *   3) The subscription is cancelled on the due data (after the payment has gone through)
//                          *   4) The subscription is cancelled after two failed payment attempts (payment overdue)
//                          *
//                          * Cases 1 & 4 are similiar and cases 2 & 3 are similiar.  We need to distinguish between each set of cases.
//                          */
//                         $nextDueDate = $cPlugin->m_Invoice->getDate('timestamp');
//                         if (isset($_POST['period1'])) {
//                             $period = explode(' ', $_POST['period1']);
//                             $nextDueDate = strtotime("+{$period[0]} {$cycles[$period[1]]}", $nextDueDate);
//                         }
//                         $today = mktime(0, 0, 0, date("m") , date("d"), date("Y"));
//                         if ($nextDueDate < $today) {
//                             $period = explode(' ', $_POST['period3']);
//                             while ($nextDueDate < $today) {
//                                 $nextDueDate = strtotime("+{$period[0]} {$cycles[$period[1]]}", $nextDueDate);
//                             }
//                             // If nextduedate is today then we must check to see if the payment has already gone through
//                             if ($nextDueDate == $today) {
//                                 // Cases 2 & 3: if case 2 then do nothing.  if case 3 we must push the date forward one cycle.
//                                 // Check for case 3 by seeing if there is a subscription payment for the proper amount already paid today.
//                                 $query = "SELECT customerid, amount FROM invoice WHERE id=?";
//                                 $result = $this->db->query($query, $tInvoiceID);
//                                 list ($customerId, $amount) = $result->fetch();
//                                 // If there is already an invoice marked paid today for that customer and the same invoice amount
//                                 // then update the nextduedate one cycle in the future.
//                                 $query = "SELECT id FROM invoice WHERE amount<=? AND amount>=? AND UNIX_TIMESTAMP(billdate)=? AND id != ? AND customerid = ?";
//                                 $result = $this->db->query($query, $amount + 0.0001, $amount - 0.0001, $today, $tInvoiceID, $customerId);
//                                 if ($result->getNumRows() == 1) {
//                                     // Case 3
//                                     $nextDueDate = strtotime("+{$period[0]} {$cycles[$period[1]]}", $nextDueDate);
//                                 }
//                             } else {
//                                 // Cases 1 & 4:   if case 1 then do nothing.  if case 4 we must roll back the date one cycle.
//                                 // Check for case 4 by seeing if there is a paid invoice one cycle in the past.
//                                 $lastDueDate = strtotime("-{$period[0]} {$cycles[$period[1]]}", $nextDueDate);
//                                 $query = "SELECT customerid, amount FROM invoice WHERE id=?";
//                                 $result = $this->db->query($query, $tInvoiceID);
//                                 list ($customerId, $amount) = $result->fetch();
//                                 // If there is not already an invoice marked paid on the last due date for that customer and the same invoice amount
//                                 // then update the nextduedate one cycle in the past.
//                                 $query = "SELECT id FROM invoice WHERE amount<=? AND amount>=? AND UNIX_TIMESTAMP(billdate)=? AND customerid = ?";
//                                 $result = $this->db->query($query, $amount + 0.0001, $amount - 0.0001, $lastDueDate, $customerId);
//                                 if ($result->getNumRows() == 0) {
//                                     // Case 4
//                                     $nextDueDate = $lastDueDate;
//                                 }
//                             }
//                         }
//                         $transaction = "Alertpay subscription cancelled by customer. Original Signup Invoice: $tInvoiceID";
//                         $cPlugin->resetRecurring($transaction, $_POST['ap_subscriptionreferencenumber'], $nextDueDate);
//                         break;
//                    }
//                 }
//             } 
                // Add Code for Normal Payment
                switch($apPayStatus) {
                    case "Success":
                        // Payment was succesful/completed.
                        $transaction = "Alertpay payment of $apPayAmount was accepted. Original Signup Invoice: $tInvoiceID (OrderID:".$apTransID.")";
                        $cPlugin->PaymentAccepted($apPayAmount,$transaction,$apTransID, $testing);
                        break;
                    default:
                        $transaction = "Alertpay payment of $apPayAmount was rejected. Original Signup Invoice: $tInvoiceID (OrderID:".$apTransID.")";
                        $cPlugin->PaymentRejected($transaction);
                        break;
                }
           
    }

}

?>
