<?php
// setup includes
require_once('../../../core/includes/master.inc.php');

// require login
$Auth->requireUser('login.php');

// check to make sure the current user has an affiliate id
$affKey = $db->getValue("SELECT affiliate_id FROM plugin_reward_affiliate_id WHERE user_id = " . (int) $Auth->id . " LIMIT 1");
if (!$affKey)
{
    $foundKey = true;

    // create key
    while ($foundKey == true)
    {
        $affKey   = MD5(time() . $Auth->id);
        $affKey   = substr($affKey, 0, 16);
        $foundKey = $db->getValue("SELECT user_id FROM plugin_reward_affiliate_id WHERE affiliate_id = " . $db->quote($affKey) . " LIMIT 1");
    }

    // update db with new user key
    $db->query('INSERT INTO plugin_reward_affiliate_id (user_id, affiliate_id) VALUES (:user_id, :affiliate_id)', array('user_id'      => (int) $Auth->id, 'affiliate_id' => $affKey));
}

// get existing paypal email address
$paypalEmail = $db->getValue("SELECT paypal_email FROM plugin_reward_affiliate_id WHERE user_id = " . (int) $Auth->id . " LIMIT 1");

// get instance
$rewardObj       = pluginHelper::getInstance('rewards');
$rewardObj->clearPendingRewards();
$rewardObj->aggregateRewards();
$rewardsSettings = $rewardObj->settings;

// get current user rewards
$thisMonthsRewards = $db->getValue("SELECT SUM(reward_amount) AS total FROM plugin_reward WHERE reward_user_id = " . (int) $Auth->id . " AND status IN ('pending', 'cleared') AND UNIX_TIMESTAMP(reward_date) >= " . strtotime(date('Y-m-01 00:00:00')));
$thisMonthsRewards = number_format($thisMonthsRewards, 2);

// get rewards available for withdrawal
$availableForWithdraw = $db->getValue("SELECT SUM(amount) AS total FROM plugin_reward_aggregated WHERE reward_user_id = " . (int) $Auth->id . " AND status IN ('available')");
$availableForWithdraw = number_format($availableForWithdraw, 2);

// get total aggregated rewards
$totalAggregated = (float) $db->getValue("SELECT SUM(amount) AS total FROM plugin_reward_aggregated WHERE reward_user_id = " . (int) $Auth->id);

// get total pending payment
$totalPendingPayment = (float) $db->getValue("SELECT SUM(amount) AS total FROM plugin_reward_withdraw_request WHERE reward_user_id = " . (int) $Auth->id);
$totalPendingPayment = number_format($totalPendingPayment, 2);

// get current user total rewards
$totalRewards = $db->getValue("SELECT SUM(reward_amount) AS total FROM plugin_reward WHERE reward_user_id = " . (int) $Auth->id . " AND status IN ('pending', 'cleared')");
$totalRewards = number_format($totalRewards, 2);

// get current user total PPD downloads
$totalPPDDownloads = $db->getValue("SELECT COUNT(id) AS total FROM plugin_reward_ppd_detail WHERE reward_user_id = " . (int) $Auth->id . " AND status IN ('pending', 'cleared', 'aggregated')");

// get current user total PPD downloads
$totalPPDDownloadsUncleared = $db->getValue("SELECT COUNT(id) AS total FROM plugin_reward_ppd_detail WHERE reward_user_id = " . (int) $Auth->id . " AND status IN ('pending', 'cleared', 'aggregated')");

// setup page
define("PAGE_NAME", t("rewards", "Rewards"));
define("PAGE_DESCRIPTION", t("rewards_meta_description", "Rewards"));
define("PAGE_KEYWORDS", t("rewards_meta_keywords", "earn, money, rewards, cash, sales, affiliate, file, hosting, site"));

require_once(DOC_ROOT . '/_header.php');
?>

<script>
    $(document).ready(function() {
        $('#rewardsData').dataTable( {
            "sPaginationType": "full_numbers",
            "bAutoWidth": false,
            "bServerSide": true,
            "bProcessing": true,
            "sAjaxSource": '_account_rewards.ajax.php',
            "iDisplayLength": 50,
            "bFilter": false,
            "bSort": false,
            "bLengthChange": false,
            "aoColumns": [
                { sClass: "alignCenter" },
                { sClass: "alignCenter" },
                { sClass: "alignCenter" },
                { sClass: "alignCenter" }
            ]
        } );
        
        $('#rewardsDataPPD').dataTable( {
            "sPaginationType": "full_numbers",
            "bAutoWidth": false,
            "bServerSide": true,
            "bProcessing": true,
            "sAjaxSource": '_account_rewards_ppd.ajax.php',
            "iDisplayLength": 50,
            "bFilter": false,
            "bSort": false,
            "bLengthChange": false,
            "aoColumns": [
                { sClass: "alignCenter" },
                { sClass: "alignCenter" },
                { sClass: "alignCenter" },
                { sClass: "alignCenter" }
            ]
        } );

        $('#aggregatedData').dataTable( {
            "sPaginationType": "full_numbers",
            "bAutoWidth": false,
            "bServerSide": true,
            "bProcessing": true,
            "sAjaxSource": '_account_rewards_aggregated.ajax.php',
            "iDisplayLength": 50,
            "bFilter": false,
            "bSort": false,
            "bLengthChange": false,
            "aoColumns": [
                { },
                { },
                { sClass: "alignCenter" },
                { sClass: "alignCenter" },
                { sClass: "alignCenter" }
            ]
        } );
        
        $("#confirmWithdrawal").dialog({
            autoOpen: false,
            height: 205,
            width: 350,
            modal: true,
            buttons: {
                "Withdraw <?php echo SITE_CONFIG_COST_CURRENCY_SYMBOL . $availableForWithdraw; ?>": function() {
                    paypal_email = $('#paypal_email').val();
                    if(paypal_email.length == 0)
                    {
                        alert('Error: Please enter your PayPal email address for the payment.');
                        $('#paypal_email').focus();
                    }
                    else
                    {
                        $.ajax({
                            url: '_request_withdrawal.ajax.php',
                            data: {paypal_email : paypal_email},
                            dataType: 'json',
                            success: function(data) {
                                alert(data.msg);
                                $("#confirmWithdrawal").dialog("close");
                                window.location='account_rewards.html';
                            },
                            error: function(data) {
                                alert("There was a problem requesting the withdrawal, please try again later.");
                            }
                        });
                    }
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        });
    } );
    
function requestWithdrawal()
{
    $("#confirmWithdrawal").dialog("open");
}
</script>

<div class="contentPageWrapper">
    <div class="pageSectionMainFull ui-corner-all">
        <div class="pageSectionMainInternal">
            <div id="pageHeader">
                <h2><?php echo t("overview", "overview"); ?></h2>
            </div>
            <div>
                <table class="accountStateTable">
                    <tbody>
                        <?php if ((int) $totalRewards > 0): ?>
                            <tr>
                                <td class="first">
                                    <?php echo UCWords(t('this_months_rewards', 'this months rewards')); ?>:
                                </td>
                                <td>
                                    <?php echo SITE_CONFIG_COST_CURRENCY_SYMBOL; ?><?php echo $thisMonthsRewards; ?>
                                </td>
                            </tr>
                        <?php endif; ?>
                            <tr>
                                <td class="first">
                                    <?php echo UCWords(t('cleared_rewards', 'cleared rewards')); ?>:
                                </td>
                                <td>
                                    <?php echo SITE_CONFIG_COST_CURRENCY_SYMBOL; ?><?php echo $availableForWithdraw; ?>
                                    <?php
                                    if ($availableForWithdraw >= $rewardsSettings['payment_threshold'])
                                    {
                                        echo '&nbsp;<a href="#" onClick="requestWithdrawal(); return false;">(request withdrawal)</a>';
                                    }
                                    
                                    if($totalPendingPayment > 0)
                                    {
                                        echo '&nbsp;<span style="color: #999;">('.SITE_CONFIG_COST_CURRENCY_SYMBOL.$totalPendingPayment.' pending payment)</span>';
                                    }
                                    ?>
                                </td>
                            </tr>
                        <?php
                        if((int)$rewardsSettings['pps_enabled'] == 1)
                        {
                        ?>
                        <tr>
                            <td class="first">
                                <?php echo UCWords(t('total_rewards_pps', 'total rewards (pps)')); ?>:
                            </td>
                            <td>
                                <?php echo SITE_CONFIG_COST_CURRENCY_SYMBOL; ?><?php echo $totalRewards; ?>
                            </td>
                        </tr>
                        <?php
                        }
                        
                        if((int)$rewardsSettings['ppd_enabled'] == 1)
                        {
                        ?>
                        <tr>
                            <td class="first">
                                <?php echo UCWords(t('noncleared_downloads_ppd', 'uncleared downloads (ppd)')); ?>:
                            </td>
                            <td>
                                <?php echo $totalPPDDownloadsUncleared; ?>&nbsp;&nbsp;<span style='color: #999;'><?php echo t('mix_groups', '(mixed groups)'); ?></span>
                            </td>
                        </tr>
                        <?php
                        }
                        ?>
                    </tbody>
                </table>
            </div>
            <div class="clear"><!-- --></div>
            <div style="padding-top: 3px;">
                <span style="color: #999;"><?php echo $rewardsSettings['payment_lead_time']; ?> day clearing period on all rewards. Next update <?php echo date('jS F Y', SITE_CONFIG_NEXT_CHECK_FOR_REWARDS_AGGREGATION); ?>. Rewards can be withdrawn when balance is over <?php echo SITE_CONFIG_COST_CURRENCY_SYMBOL; ?><?php echo $rewardsSettings['payment_threshold']; ?>.</span>
            </div>
            <div class="clear"><!-- --></div>

            <?php
            if ($totalAggregated > 0)
            {
                ?>
                <div id="pageHeader" style="padding-top: 18px;">
                    <h2><?php echo t("monthly_totals", "monthly totals"); ?></h2>
                </div>
                <div>
                    <p class="introText">
                        <?php
                        echo '<table id="aggregatedData" width="100%" cellpadding="3" cellspacing="0">';
                        echo '<thead>';
                        echo '<th style="width: 15%; text-align: left;" class="ui-state-default">' . t('month', 'Month') . ':</th>';
                        echo '<th style="width: 40%; text-align: left;" class="ui-state-default">' . t('description', 'Description') . ':</th>';
                        echo '<th style="width: 15%; text-align: center;" class="ui-state-default">' . t('amount', 'Amount') . ':</th>';
                        echo '<th style="width: 15%; text-align: center;" class="ui-state-default">' . t('status', 'Status') . ':</th>';
                        echo '<th style="width: 15%; text-align: center;" class="ui-state-default">' . t('options', 'Options') . ':</th>';
                        echo '</thead>';
                        echo '<tbody>';
                        echo '</tbody>';
                        echo '</table>';
                        ?>
                    </p>
                    <div class="clear"></div>
                </div>
                <div class="clear"><!-- --></div>
                <?php
            }
            ?>

            <?php
            if (($totalRewards > 0) && ((int)$rewardsSettings['pps_enabled'] == 1))
            {
                ?>
                <div id="pageHeader" style="padding-top: 18px;">
                    <h2><?php echo t("recent_rewards", "recent rewards"); ?></h2>
                </div>
                <div>
                    <p class="introText">
                        <?php
                        echo '<table id="rewardsData" width="100%" cellpadding="3" cellspacing="0">';
                        echo '<thead>';
                        echo '<th style="width: 25%; text-align: center;" class="ui-state-default">' . t('reward_date', 'Reward Date') . ':</th>';
                        echo '<th style="width: 25%; text-align: center;" class="ui-state-default">' . t('reward_amount', 'Amount') . ':</th>';
                        echo '<th style="width: 25%; text-align: center;" class="ui-state-default">' . t('percentage', 'Percentage') . ':</th>';
                        echo '<th style="width: 25%; text-align: center;" class="ui-state-default">' . t('status', 'Status') . ':</th>';
                        echo '</thead>';
                        echo '<tbody>';
                        echo '</tbody>';
                        echo '</table>';
                        ?>
                    </p>
                    <div class="clear"></div>
                </div>
                <div class="clear"><!-- --></div>
                <?php
            }
            ?>

            <?php
            if((int)$rewardsSettings['pps_enabled'] == 1)
            {
            ?>
            <div id="pageHeader" style="padding-top: 18px;">
                <h2><?php echo t("how_to_start_earning", "how to start earning"); ?></h2>
            </div>
            <p>
                Earn <?php echo $rewardsSettings['user_percentage']; ?>% of each sale you refer to this site! You can earn money from upgrading users in 2 ways:
            </p>
            <ol class="rewardsTextList">
                <li>Using your unique affiliate id, simply link to the site via your existing website. You'll earn <?php echo $rewardsSettings['user_percentage']; ?>% for any users which register for an account and subsequently upgrade.</li>
                <li>From users which upgrade to download files within your account.</li>
            </ol>
            <p>
                Begin by uploading and sharing your files or by linking from your existing site using your affiliate id like this:
            </p>
            <ul>
                <li><a href="<?php echo WEB_ROOT; ?>/?aff=<?php echo $affKey; ?>"><?php echo WEB_ROOT; ?>/?aff=<?php echo $affKey; ?></a></li>
            </ul>
            </p>
            <div class="clear"><!-- --></div>
            <?php
            }
            ?>

            <?php
            if (($totalPPDDownloads > 0) && ((int)$rewardsSettings['ppd_enabled'] == 1))
            {
                ?>
                <div id="pageHeader" style="padding-top: 18px;">
                    <h2><?php echo t("ppd_recent_downloads", "ppd recent downloads"); ?></h2>
                </div>
                <div>
                    <p class="introText">
                        <?php
                        echo '<table id="rewardsDataPPD" width="100%" cellpadding="3" cellspacing="0">';
                        echo '<thead>';
                        echo '<th style="width: 20%; text-align: center;" class="ui-state-default">' . t('download_date', 'Download Date') . ':</th>';
                        echo '<th style="text-align: center;" class="ui-state-default">' . t('file', 'File') . ':</th>';
                        echo '<th style="width: 20%; text-align: center;" class="ui-state-default">' . t('group', 'Group') . ':</th>';
                        echo '<th style="width: 20%; text-align: center;" class="ui-state-default">' . t('status', 'Status') . ':</th>';
                        echo '</thead>';
                        echo '<tbody>';
                        echo '</tbody>';
                        echo '</table>';
                        ?>
                    </p>
                    <div class="clear"></div>
                </div>
                <div class="clear"><!-- --></div>
                <?php
            }
            ?>

            <?php
            if((int)$rewardsSettings['ppd_enabled'] == 1)
            {
                $lowestValue = $db->getValue("SELECT payout_rate FROM plugin_reward_ppd_group ORDER BY payout_rate ASC LIMIT 1");
            ?>
            <div id="pageHeader" style="padding-top: 18px;">
                <h2><?php echo t("pay_per_download_rates", "Pay Per Download (PPD) Rates"); ?></h2>
            </div>
            <p>
                <?php echo t('upload_your_files_and_youll_be_paid_for_every', 'Upload your files and you\'ll be paid for every file downloaded on your account.'); ?> <?php if((int)$rewardsSettings['ppd_min_file_size'] > 0) echo t('files_above_x_will_count', 'Files above [[[FILE_SIZE]]]MB will count.', array('FILE_SIZE'=>(int)$rewardsSettings['ppd_min_file_size'])); ?> <?php echo t('see_the_payment_rates_below', 'See the payment rates below:'); ?>
            </p>
            <table class="ppdRateTable">
                <thead>
                    <td style="width: 160px; text-align: center;"><?php echo t('group_name', 'Group Name'); ?>:</td>
                    <td style="width: 160px; text-align: center;"><?php echo t('paid_per_1000_users', 'Paid Per 1,000 Downloads'); ?>:</td>
                    <td><?php echo t('downloading_country', 'Downloading Country'); ?>:</td>
                </thead>
                <tbody>
                <?php
                // get ppd groups
                $groups = $db->getRows('SELECT id, group_label, payout_rate FROM plugin_reward_ppd_group ORDER BY id');
                foreach($groups AS $group)
                {
                    $countryData = $db->getRows('SELECT plugin_reward_ppd_group_country.country_code, plugin_reward_country_list.name FROM plugin_reward_ppd_group_country LEFT JOIN plugin_reward_country_list ON plugin_reward_ppd_group_country.country_code = plugin_reward_country_list.iso_alpha2 WHERE group_id='.$group['id']);
                    $countries = array();
                    if(COUNT($countryData))
                    {
                        foreach($countryData AS $countryRow)
                        {
                            $countries[] = $countryRow['name'];
                        }
                    }
                    
                    // add 'other' label
                    if($group['payout_rate'] == $lowestValue)
                    {
                        $countries[] = UCWords(t('other', 'Other'));
                    }
                    
                    // for no countries
                    if(COUNT($countries) == 0)
                    {
                        $countries[] = '-';
                    }
                    
                    $countriesStr = implode(", ", $countries);
                    
                    ?>
                    <tr>
                        <td style="text-align: center;"><?php echo safeOutputToScreen($group['group_label']); ?></td>
                        <td style="text-align: center;"><?php echo SITE_CONFIG_COST_CURRENCY_SYMBOL.safeOutputToScreen($group['payout_rate']); ?></td>
                        <td><?php echo safeOutputToScreen($countriesStr); ?></td>
                    </tr>
                    <?php
                }
                ?>
                </tbody>
            </table>
            <div class="clear"><!-- --></div>
            <?php
            }
            ?>
        </div>
    </div>
</div>
<div class="clear"></div>

<div id="confirmWithdrawal" title="Confirm Withdrawal" class="popupForm">
    <p>Please confirm your withdrawal of <?php echo SITE_CONFIG_COST_CURRENCY_SYMBOL . $availableForWithdraw; ?>:</p>
    <form method="POST" action="">
        <label for="paypal_email">
            Your PayPal Email Address:<br/>
            <input name="paypal_email" id="paypal_email" type="text" value="<?php echo safeOutputToScreen($paypalEmail); ?>"/>
        </label>
        <div class="clear"><!-- --></div>
    </form>
</div>

<?php
require_once(DOC_ROOT . '/_footer.php');
?>