<?php

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

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

// setup initial params
$paypal_email = strtolower(trim($_REQUEST['paypal_email']));
$result       = array();
$result['error'] = false;
$result['msg']   = '';
$db              = Database::getDatabase(true);

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

// 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);

// double check the amount is above the threshold
if ($availableForWithdraw < $rewardsSettings['payment_threshold'])
{
    $result['error'] = true;
    $result['msg']   = 'The amount available within your account ' . $availableForWithdraw . ' is less than the payment threshold (' . $rewardsSettings['payment_threshold'] . ').';
}
elseif (_CONFIG_DEMO_MODE == true)
{
    $result['error'] = true;
    $result['msg']   = adminFunctions::t("no_changes_in_demo_mode");
}
else
{
    // add payment request
    $dbInsert = new DBObject("plugin_reward_withdraw_request",
                    array("reward_user_id", "amount",
                        "requested_date", "status")
    );
    $dbInsert->reward_user_id = (int) $Auth->id;
    $dbInsert->amount = $availableForWithdraw;
    $dbInsert->requested_date = date("Y-m-d H:i:s", time());
    $dbInsert->status = 'pending';
    $dbInsert->insert();

    // update aggregated rewards
    $db->query("UPDATE plugin_reward_aggregated SET status='payment_in_progress', withdrawal_request_id=".(int)$dbInsert->id." WHERE reward_user_id = " . (int) $Auth->id . " AND status IN ('available')");
    
    // store paypal email address
    $db->query("UPDATE plugin_reward_affiliate_id SET paypal_email=".$db->quote($paypal_email)." WHERE user_id = " . (int) $Auth->id . " LIMIT 1");

    // send notification to admin
    $subject = t('rewards_request_withdrawal_email_to_admin_subject', 'Rewards withdrawal request for [[[AMOUNT]]]', array('AMOUNT'      => $availableForWithdraw));
    $replacements = array(
        'SITE_NAME'      => SITE_CONFIG_SITE_NAME,
        'ADMIN_WEB_ROOT' => ADMIN_WEB_ROOT
    );
    $defaultContent  = "Dear Admin,<br/><br/>";
    $defaultContent .= "A rewards withdrawal request has been received. Please login to [[[SITE_NAME]]] and process the request:<br/><br/>";
    $defaultContent .= "<a href='[[[ADMIN_WEB_ROOT]]]'>[[[ADMIN_WEB_ROOT]]]</a><br/><br/>";
    $defaultContent .= "Regards,<br/>";
    $defaultContent .= "[[[SITE_NAME]]] Admin";
    $htmlMsg         = t('rewards_request_withdrawal_email_to_admin_content', $defaultContent, $replacements);
    send_html_mail(SITE_CONFIG_SITE_ADMIN_EMAIL, $subject, $htmlMsg, SITE_CONFIG_DEFAULT_EMAIL_ADDRESS_FROM, strip_tags(str_replace("<br/>", "\n", $htmlMsg)));
    
    $result['error'] = false;
    $result['msg'] = 'Your withdrawal request has been made. You\'ll receive further information once the request has been approved.';
}

echo json_encode($result);