<?php

// load our payments library
use Omnipay\Omnipay;

// load plugin details
$pluginConfig = pluginHelper::pluginSpecificConfiguration('payment');
$pluginSettings = $pluginConfig['data']['plugin_settings'];

if (!isset($_REQUEST['user_level_pricing_id'])) {
    coreFunctions::redirect(WEB_ROOT . '/upgrade.html');
}

if (!isset($_REQUEST['cid'])) {
    coreFunctions::redirect(WEB_ROOT . '/upgrade.html');
}

// require login
if (UserPeer::enableUpgradePage() == 'no') {
    // require login
    $Auth->requireUser(WEB_ROOT . '/login.' . SITE_CONFIG_PAGE_EXTENSION);
}
// page title
$title = UCWords(t('extend', 'extend'));
if ($Auth->level_id <= 1) {
    $title = UCWords(t('upgrade', 'upgrade'));
}
// setup page
define("PAGE_NAME", $title . ' ' . UCWords(t("account_confirmation", "account confirmation")));
define("PAGE_DESCRIPTION", $title . ' ' . t("upgrade_meta_description", "Your Account"));
define("PAGE_KEYWORDS", strtolower($title) . t("upgrade_meta_keywords", ", account, paid, membership, upload, download, site"));
define("TITLE_DESCRIPTION_LEFT", t("upgrade_title_page_description_left", "See below for the various account and payment options."));
define("TITLE_DESCRIPTION_RIGHT", t("upgrade_title_page_description_right", ""));
define("CURRENT_PAGE_KEY", "upgrade");

// prep dates
$monthDropdown = range(1, 12);
$yearDropdown = range(date('Y'), date('Y') + 20);

// load user
$user = UserPeer::loadUserById($Auth->id);
$user_level_pricing_id = (int) $_REQUEST['user_level_pricing_id'];
$fileId = null;
if (isset($_REQUEST['f'])) {
    $file = file::loadByShortUrl($_REQUEST['f']);
    if ($file) {
        $fileId = $file->id;
    }
}

// load the payment gateway data
$gatewayParams = $db->getRow('SELECT plugin_payment_gateways_configured.params, plugin_payment_gateways.class_name FROM plugin_payment_gateways_configured '
        . 'LEFT JOIN plugin_payment_gateways ON plugin_payment_gateways_configured.gateway_id = plugin_payment_gateways.id '
        . 'WHERE plugin_payment_gateways_configured.id = ' . (int) $_REQUEST['cid'] . ' LIMIT 1');
if (!$gatewayParams) {
    coreFunctions::redirect(WEB_ROOT . '/upgrade.html');
}

$card_number = '';
$card_holder_name = '';
$expiry_month = '';
$expiry_year = '';
$cvv = '';

// handle submissions
if (isset($_REQUEST['submitted'])) {
    // get form variables
    $card_number = trim($_REQUEST['card_number']);
    $card_holder_name = trim($_REQUEST['card_holder_name']);
    $expiry_month = trim($_REQUEST['expiry_month']);
    $expiry_year = trim($_REQUEST['expiry_year']);
    $cvv = trim($_REQUEST['cvv']);
        
    // create order entry
    $order = OrderPeer::createByPackageId($user->id, $user_level_pricing_id, $fileId);
    if ($order) {
        // prep params
        $gatewayParamsArr = json_decode($gatewayParams['params'], true);

        // setup the payment gateway object
        $gateway = Omnipay::create($gatewayParams['class_name']);
        foreach ($gatewayParamsArr AS $k => $gatewayParam) {
            $funcName = 'set' . ucfirst($k);
            if (method_exists($gateway, $funcName)) {
                $gateway->{$funcName}($gatewayParam);
            }
        }

        // pickup form data
        $formData = [
            'number' => $card_number,
            'firstName' => $card_holder_name,
            'expiryMonth' => $expiry_month,
            'expiryYear' => $expiry_year,
            'cvv' => $cvv,
        ];
        
        /*
        $formData = [
            'number' => '4242424242424242',
            'firstName' => 'MR. WALTER WHITE',
            'expiryMonth' => '6',
            'expiryYear' => '2019',
            'cvv' => '123'
        ];
         */

        // send purchase request
        try {
            $response = $gateway->purchase(
                            [
                                'amount' => $order->amount,
                                'currency' => SITE_CONFIG_COST_CURRENCY_CODE,
                                'card' => $formData
                            ]
                    )->send();
        }
        catch (\Exception $e) {
            // internal error, log exception and display a generic message to the customer
            notification::setError('Error! ' . $e->getMessage());
        }

        // if no errors
        if (notification::isErrors() === false) {
            // process response
            if ($response->isSuccessful()) {
                // payment was successful, upgrade account
                $extendedDays = $order->days;
                $upgradeUserId = $order->upgrade_user_id;

                // log in payment_log
                $dbInsert = new DBObject("payment_log", array("user_id", "date_created", "amount",
                    "currency_code", "from_email", "to_email", "description",
                    "request_log", "payment_method")
                );
                $dbInsert->user_id = $order->user_id;
                $dbInsert->date_created = date("Y-m-d H:i:s", time());
                $dbInsert->amount = $order->amount;
                $dbInsert->currency_code = SITE_CONFIG_COST_CURRENCY_CODE;
                $dbInsert->from_email = $user->email;
                $dbInsert->to_email = $response->getTransactionReference();
                $dbInsert->description = $order->description;
                $dbInsert->request_log = print_r($response, true);
                $dbInsert->payment_method = $gatewayParams['class_name'];
                $dbInsert->insert();

                // update order status to paid
                $dbUpdate = new DBObject("premium_order", array("order_status"), 'id');
                $dbUpdate->order_status = 'completed';
                $dbUpdate->id = $order->id;
                $effectedRows = $dbUpdate->update();
                if ($effectedRows === false) {
                    // failed to update order
                    die('Failed - failed to update order');
                }

                // extend/upgrade user
                $rs = UserPeer::upgradeUserByPackageId($order->user_id, $order);
                if ($rs === false) {
                    // failed to update user
                    notification::setError('Failed - failed to update your account, please contact support.');
                }
                else {
                    // append any plugin includes
                    pluginHelper::includeAppends('payment_ipn_paypal.php', array('order' => $order));

                    // add confirmation message within their account
                    $user = UserPeer::loadUserById($Auth->id);
                    internalNotification::add($order->user_id, 'Thanks for your payment of ' . SITE_CONFIG_COST_CURRENCY_SYMBOL . $order->amount . '. Your premium account will expire on ' . coreFunctions::formatDate(strtotime($user->paidExpiryDate)));

                    // redirect to account home
                    coreFunctions::redirect('account_home.' . SITE_CONFIG_PAGE_EXTENSION);
                }
            }
            elseif ($response->isRedirect()) {
                // redirect to offsite payment gateway
                $response->redirect();
            }
            else {
                // payment failed
                notification::setError('Error! ' . $response->getMessage());
            }
        }
    }
}

// include header
require_once(SITE_TEMPLATES_PATH . '/partial/_header.inc.php');
?>
<script>
    var formSubmitted = false;
    $(document).ready(function () {
        $("#paymentForm").submit(function (event) {
            if (formSubmitted == true) {
                event.preventDefault();
                return;
            }

            $('#submitButton').val('Processing...');
            $('#submitButton').attr('disabled', true);
            $('#submitButton').removeClass('btn-default');
        });
    });
</script>

<?php
if (notification::isErrors()) {
    echo notification::outputErrors();
}
elseif (notification::isSuccess()) {
    echo notification::outputSuccess();
}
?>

<div class="row">   

    <form id="paymentForm" method="POST" action="upgrade_confirmation.<?php echo SITE_CONFIG_PAGE_EXTENSION; ?>?cid=<?php echo (int) $_REQUEST['cid']; ?>" class="form-horizontal" role="form">
        <fieldset>
            <div class="form-group">
                <label class="col-sm-3 control-label" for="card_holder_name">Name on Card</label>
                <div class="col-sm-9">
                    <input type="text" class="form-control" name="card_holder_name" id="card_holder_name" placeholder="Card Holder's Name" value="<?php echo validation::safeOutputToScreen($card_holder_name); ?>"/>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label" for="card_number">Card Number</label>
                <div class="col-sm-9">
                    <input type="text" class="form-control" name="card_number" id="card_number" placeholder="Debit/Credit Card Number" maxlength="20" value="<?php echo validation::safeOutputToScreen($card_number); ?>"/>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label" for="expiry_month">Expiration Date</label>
                <div class="col-sm-9">
                    <div class="row">
                        <div class="col-xs-3">
                            <select class="form-control col-sm-2" name="expiry_month" id="expiry_month">
                                <option>Month</option>
                                <?php
                                foreach ($monthDropdown AS $monthDropdownItem) {
                                    echo '<option value="' . $monthDropdownItem . '"';
                                    if($expiry_month == $monthDropdownItem) {
                                        echo ' SELECTED';
                                    }
                                    echo '>' . str_pad($monthDropdownItem, 2, "0", STR_PAD_LEFT) . ' - ' . date('F', mktime(0, 0, 0, $monthDropdownItem, 10)) . '</option>';
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-xs-3">
                            <select class="form-control" name="expiry_year">
                                <option>Year</option>
                                <?php
                                foreach ($yearDropdown AS $yearDropdownItem) {
                                    echo '<option value="' . $yearDropdownItem . '"';
                                    if($expiry_year == $yearDropdownItem) {
                                        echo ' SELECTED';
                                    }
                                    echo '>' . $yearDropdownItem . '</option>';
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label" for="cvv">Card CVV</label>
                <div class="col-sm-3">
                    <input type="password" class="form-control" name="cvv" id="cvv" placeholder="Security Code" maxlength="3" autocomplete="off" value="<?php echo validation::safeOutputToScreen($cvv); ?>"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-3 col-sm-9">
                    <input id="submitButton" type="submit" class="btn btn btn-default" value="Submit Payment"/>
                    <input name="submitted" type="hidden" value="1"/>
                    <input name="user_level_pricing_id" type="hidden" value="<?php echo (int) $user_level_pricing_id; ?>"/>
<?php
if (isset($_REQUEST['i'])) {
    echo '<input type="hidden" name="i" value="' . htmlentities($_REQUEST['i']) . '" />';
}
if (isset($_REQUEST['f'])) {
    echo '<input type="hidden" name="f" value="' . htmlentities($_REQUEST['f']) . '" />';
}
?>
                </div>
            </div>
        </fieldset>
    </form>




                    <?php if ($Auth->loggedIn()): ?>
        <h2><?php echo t("account_status", "account status"); ?></h2>
        <div style="padding-bottom: 12px;">
            <table class="table table-bordered table-striped">
                <tbody>
                    <tr>
                        <td style="width: 280px;">
    <?php echo UCWords(t('account_type', 'account type')); ?>:
                        </td>
                        <td>
    <?php echo t('account_type_' . str_replace(' ', '_', $Auth->level), UCWords($Auth->level)); ?>
                        </td>
                    </tr>

    <?php
    $userType = $db->getValue('SELECT level_type FROM user_level WHERE id = ' . $user->level_id . ' LIMIT 1');
    if (in_array($userType, array('paid', 'admin', 'moderator'))):
        ?>
                        <tr>
                            <td>
        <?php echo UCWords(t('reverts_to_free_account', 'reverts to free account')); ?>:
                            </td>
                            <td>
                        <?php echo(in_array($userType, array('admin', 'moderator'))) ? UCWords(t('never', 'never')) : coreFunctions::formatDate($user->paidExpiryDate); ?>
                            </td>
                        </tr>
                    <?php endif ?>
                </tbody>
            </table>
        </div>
<?php endif; ?>
    <h2><?php echo t("account_benefits", "account benefits"); ?></h2>
                        <?php
                        include_once(SITE_TEMPLATES_PATH . '/partial/_upgrade_benefits.inc.php');
                        ?>
</div>
<?php
// include footer
require_once(SITE_TEMPLATES_PATH . '/partial/_footer.inc.php');
?>
