<?php
require_once("include/bittorrent.php");

session_start();

function bark($msg) {
genbark($msg, "Job failed!");
}
dbconn();
loggedinorreturn();
get_date_time();

function getBonus($bonus_id){
    $bonus_id = intval($bonus_id);
    $sql = "SELECT * FROM bonus WHERE id=$bonus_id";
    $qry = mysql_query($sql);
    if ($a = mysql_fetch_assoc($qry)) {
        return $a;
    }
    else return false;
}

function updateBonus($user_id, $bonus, $uploaded){
    $user_id = intval($user_id);
    $bonus = doubleval($bonus);
    $upload = doubleval($upload);

    if ($user_id) {
        $sql = "UPDATE users
                SET seedbonus=seedbonus-$bonus,
                    uploaded=uploaded+$uploaded
                WHERE id=$user_id LIMIT 1";
        $qry = mysql_query($sql);
    }
}

function getSeedBonus($user_id) {
    $ret = 0;
    $user_id = intval($user_id);
    if ($user_id) {
        $sql = "SELECT seedbonus FROM users WHERE id=$user_id";
        $qry = mysql_query($sql);
        $a = mysql_fetch_assoc($qry);
        $ret = $a["seedbonus"];
    }

    return $ret;
}

$msg = -1;

if ($CURUSER["id"] < 1) {
    $msg = 1;
}
elseif (is_array($_POST["takebonus"])) {
    $bonus_id = array_keys($_POST["takebonus"]);
    if ($bonus = getBonus($bonus_id[0])) {
        $seedbonus = getSeedBonus($CURUSER['id']);
        $bpunkte = str_replace(".", "", $bonus["points"]);
        if ($seedbonus >= $bpunkte) {
            updateBonus($CURUSER["id"], $bpunkte, $bonus["menge"]);
            $modcomment ="User hat " .$bpunkte. " Punkte für " .$bonus["bonusname"]. " eingetauscht.\n ";
            write_modcomment($userid, $CURUSER["id"], "$modcomment");
            $msg = 4 . "|" . $bonus["bonusname"];
        }
        else $msg = 3;
    }
    else $msg = 2;
}
else $msg = 2;

header("Location: mybonus.php?msg=$msg");
?>