<?php
function plugin_paypal_variables() {
    /* Specification
        itemkey     - used to identify variable in your other functions
        type          - text,textarea,yesno,password
        description - description of the variable, displayed in ClientExec
    */

    $variables = array (
        "Plugin Name" => array (
            "type"=>"hidden",
            "description"=>"How CE sees this plugin (not to be confused with the Signup Name)",
            "value"=>"Paypal"
            ),
        "In Signup" => array (
            "type"=>"yesno",
            "description"=>"Select YES if you want to include this payment processor in the signup script.",
            "value"=>"0"
            ),
        "User ID" => array (
            "type"=>"text",
            "description"=>"ID used to identify you to PayPal.<br>NOTE: This ID is required if you have selected PayPal as a payment gateway for any of your clients.",
            "value"=>""
            ),
        "Signup Name" => array (
            "type"=>"text",
            "description"=>"Select the name to display in the signup process for this payment type. Example: eCheck or Credit Card.",
            "value"=>"Credit Card, eCheck, or Paypal"
            ),
        "Generate Invoices After Callback Notification" => array (
            "type"=>"hidden",
            "description"=>"Select YES if you prefer CE to only generate invoices upon notification of payment via the callback supported by this processor.  Setting to NO will generate invoices normally but require you to manually mark them paid as you receive notification from processor.",
            "value"=>"1"
            ),
        "Invoice After Signup" => array (
            "type"=>"yesno",
            "description"=>"Select YES if you want an invoice sent to the customer after signup is complete.",
            "value"=>"1"
            ),
        'Use PayPal Sandbox'    => array(
            'type'          => 'yesno',
            'description'   => 'Select YES if you want to use Paypal\'s testing server, so no actual monetary transactions are made. You need to have a developer account with Paypal, and be logged-in in the developer panel in another browser window for the transaction to be successful.',
            'value'         => '0',
        ),
        'Force customers to use PayPal subscriptions'    => array(
            'type'          => 'yesno',
            'description'   => 'Select YES if you want to force customers to use PayPal subscriptions in signup.',
            'value'         => '0',
        ),
    );
    return $variables;
}

function plugin_paypal_singlepayment($params, $test = false) {
    //Function needs to build the url to the payment processor, then redirect
    $stat_url = substr($params['clientExecURL'],-1,1) == "//" ? $params['clientExecURL']."plugins/gateways/paypal/callback.php" : $params['clientExecURL']."/plugins/gateways/paypal/callback.php";
    if ($params['plugin_paypal_Use PayPal Sandbox'] == '1') {
        $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
    } else {
        $paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
    }

    $strRet = "<html>\n";
    $strRet .= "<head></head>\n";
    $strRet .= "<body>\n";
    $strRet .= "<form name=frmPayPal action=\"$paypal_url\" method=\"post\">\n";
    $strRet .= "<input type=hidden name=\"business\" value=\"".$params["plugin_paypal_User ID"]."\">\n";

    //determine if this is a single payment
    if (!$params['billingCycle'] && !$params['invoiceDomainBillingCycle']) $params['usingRecurringPlugin']=0;
    //echo "<pre>";print_r($params);echo "</pre>\n";

    $subscriptionsUsed = false;
    $initialTrial = true;
    // don't use subscriptions if it's a package with a setup fee and no package fee
    if($params['usingRecurringPlugin'] == '1' && !($params['invoiceSetup'] && !$params['invoicePackageUnproratedFee']))
    {
        // if it's just a domain charge without package fees, use the domain name billing cycle
        if ($params['invoiceDomainBillingCycle'] && !$params['invoicePackageUnproratedFee']) {
            $billingCycle = $params['invoiceDomainBillingCycle'];
        } else {
            $billingCycle = $params['billingCycle'];
        }

        // paypal only accepts two decimals
        $initialAmount = sprintf('%.2f', $params["invoiceTotal"]);

        // if invoicePackageUnproratedFee is 0, it means this is not a package invoice, so the invoiceTotal will be the same charge always
        $tRecurringTotal = 0;
        if (!$params['invoicePackageUnproratedFee']) {
            $tRecurringTotal = sprintf('%.2f', $params["invoiceTotal"]);
        } else {
            if ($params['recurringDiscount']) {
                $tRecurringTotal += $params['recurringDiscount'];
            }
            $tRecurringTotal += $params['invoicePackageUnproratedFee'] * (1 + $params['invoiceTaxRate'] / 100);
            $tRecurringTotal = sprintf('%.2f', $tRecurringTotal);
        }

        $todayDate = mktime(0, 0, 0);
        if ($params['invoiceProratingDays']) {
            // If prorating, next payment will be on the prorate day at least
            $today = date('d');
            $month = date('m');
            if ($today < $GLOBALS['gSettingsArray']['Prorate To Day']) {
               $tmpNextBill = mktime(0,0,0, $month, $GLOBALS['gSettingsArray']['Prorate To Day']);
            } else {
               $tmpNextBill = mktime(0,0,0,$month + 1, $GLOBALS['gSettingsArray']['Prorate To Day']);
            }

            $includeFollowingPayment = $GLOBALS['gSettingsArray']['Include Following Payment'];
            // If including following payment is set as well, then move the next payment un billing cycle later
            if (    ($includeFollowingPayment == 0 && $params['invoiceProratingDays'] <= 10)
                    || ($includeFollowingPayment == 2 && $params['billingCycle'] != 1)
                    || ($includeFollowingPayment == 1))
            {

                // use strtotime to take care of 30/31 days in a month and leap years
                if ($params['billingCycle'] == 12) { // 12 months == 1 year
                   $tmpNextBill = strtotime('+1 year', $tmpNextBill);
                } else { // X month
                   $tmpNextBill = strtotime('+'.$params['billingCycle'].' month', $tmpNextBill);
                }
            }

            // 86400 is the number of secs in a day
            $initialPeriodLength = floor(($tmpNextBill- $todayDate) / 86400);
            $initialPeriodUnits = 'D';
        } else {
            // special case: about to pay an invoice with a future due date
            // First we normalize the timestamps to midnight
            $dueDate = mktime(0, 0, 0, date('m', $params['invoiceDueDate']), date('d', $params['invoiceDueDate']), date('Y', $params['invoiceDueDate']));
            if ($todayDate < $dueDate) {
                if ($billingCycle == 12) { // 12 months == 1 year
                    // In this case we can't create an initial trial period so that following payments are made on the due date,
                    // because that would imply a initial trial period longer than 90 days which is not allowed by Paypal.
                    // For example if client pays 5 days in advance we would have an initial trial period of 365+5 = 370
                    $initialTrial = false;
                } else { // X month
                   $dueDate = strtotime("+$billingCycle month", $dueDate);
                    $initialPeriodLength = floor(($dueDate - $todayDate) / 86400);
                    $initialPeriodUnits = 'D';
                }
            } else {
                $initialPeriodLength = $billingCycle;
                $initialPeriodUnits = 'M';
            }
        }

        // Special case: using prorating and including following payment with billing cycles greater than monthly
        // implies a trial period of more than 90 days, which is not supported by paypal.
        // In this case we must fallback to not use subscriptions :(
        if ($initialPeriodLength <= 90) {
            $subscriptionsUsed = true;

            $strRet .= "<INPUT type=hidden name=\"cmd\" value=\"_xclick-subscriptions\">\n";

            // Trial Period 1 used for initial signup payment.
            // So we can include the total cost of Domain + Hosting + Setup.
            if ($initialTrial) {
                $strRet .= "<input type=hidden name=\"a1\" value=\"$initialAmount\">\n";
                $strRet .= "<input type=hidden name=\"p1\" value=\"".$initialPeriodLength."\">\n";
                $strRet .= "<input type=hidden name=\"t1\" value=\"$initialPeriodUnits\">\n";
            }

            // Normal Billing cycle information including Recurring Payment (only the cost of service).
            $strRet .= "<input type=hidden name=\"a3\" value=\"".$tRecurringTotal."\">\n";
            $strRet .= "<input type=hidden name=\"p3\" value=\"$billingCycle\">\n";
            $strRet .= "<input type=hidden name=\"t3\" value=\"M\">\n";

            // Recurring and retry options. Set retry until Paypal's system gives up. And set recurring indefinately.)
            $strRet .= "<input type=hidden name=\"src\" value=\"1\">\n";
            $strRet .= "<input type=hidden name=\"sra\" value=\"1\">\n";

            $strRet .= "<input type=hidden name=\"item_name\" value=\"".$params["companyName"]." - Subscription\">\n";
        }

    }
    if (!$subscriptionsUsed) {
        $params['usingRecurringPlugin'] = 0;
        $strRet .= "<input type=hidden name=\"cmd\" value=\"_ext-enter\">\n";
        $strRet .= "<input type=hidden name=\"redirect_cmd\" value=\"_xclick\">\n";
        $strRet .= "<input type=hidden name=\"item_name\" value=\"".$params["companyName"]." Invoice\">\n";
        $strRet .= "<input type=hidden name=\"item_number\" value=\"".$params['invoiceNumber']."\">\n";
        $strRet .= "<INPUT type=hidden name=\"amount\" value=\"".sprintf("%.2f", $params["invoiceTotal"])."\">\n";
    }

    //Need to check to see if user is coming from signup
    if ($params['isSignup']==1) {
        $returnURL=$params["clientExecURL"]."/signup.php?step=6&pass=1";
        $returnURL_Cancel=$params["clientExecURL"]."/signup.php?step=6&pass=0";
    }else {
        $returnURL=$params["clientExecURL"];
        $returnURL_Cancel=$params["clientExecURL"];
    }

    $strRet .= "<input type=hidden name=\"custom\" value=\"".$params['invoiceNumber']."_".$params['usingRecurringPlugin']."_".$params["plugin_paypal_Generate Invoices After Callback Notification"]."\">\n";

    $strRet .= "<INPUT type=hidden name=\"return\" value=\"".$returnURL."\">\n";
    $strRet .= "<input type=hidden name=\"cancel_return\" value=\"".$returnURL_Cancel."\">\n";
    $strRet .= "<input type=hidden name=\"notify_url\" value=\"".$stat_url."\">\n";
    $strRet .= "<INPUT type=hidden name=\"first_name\" value=\"".$params["userFirstName"]."\">\n";
    $strRet .= "<INPUT type=hidden name=\"last_name\" value=\"".$params["userLastName"]."\">\n";
    $strRet .= "<INPUT type=hidden name=\"address1\" value=\"".$params["userAddress"]."\">\n";
    $strRet .= "<INPUT type=hidden name=\"city\" value=\"".$params["userCity"]."\">\n";
    $strRet .= "<INPUT type=hidden name=\"state\" value=\"".$params["userState"]."\">\n";
    $strRet .= "<INPUT type=hidden name=\"zip\" value=\"".$params["userZipcode"]."\">\n";
    $strRet .= "<INPUT type=hidden name=\"no_shipping\" value=\"1\">\n";
    $strRet .= "<INPUT type=hidden name=\"no_note\" value=\"1\">\n";
    $strRet .= "<INPUT type=hidden name=\"currency_code\" value=\"".$params["currencytype"]."\">\n";
    //die($strRet);
    $strRet .= "<script language=\"JavaScript\">\n";
    $strRet .= "document.forms['frmPayPal'].submit();\n";
    $strRet .= "</script>\n";
    $strRet .= "</form>\n";
    $strRet .= "</body>\n</html>\n";

    if ($test) {
        return $strRet;
    } else {
        echo $strRet;
        exit;
    }
}
?>
