<?php

header("Access-Control-Allow-Origin: *");
include "databasefunctions.php";
include_once "bintypes.php";
include "user.php";
include "pointObject.php";
if (isset($_POST["userId"]) && isset($_POST["points"]) && isset($_POST["token"])) {
    if ($_POST["token"] !== $masterToken) {
        $errorMsg = ["Error" => "No or invalid access token given"];
        echo json_encode($errorMsg);
        return;
    } else {
        $id = $_POST["userId"];
        $points = $_POST["points"];
        $user = makeUserFromRaw(GetUser($id));
        $newPoints = new PointObject();
        $newPoints->Add($user->Points);
        $newPoints->AddFromArray($points);
        $user->Points = $newPoints;
        $user->Points->RemoveNegative();
        echo EditUserPoints($user->UserId, json_encode($user->Points));
    }
} else {
    $errorMsg = ["Error" => "Missing required parameters"];
    echo json_encode($errorMsg);
}
function EditBinWeight($id, $weight)
{
    include_once "exchangeRates.php";
    include_once "pointObject.php";
    include_once "bin.php";
    $binOld = makeBinFromRaw(GetBin($id), "en");
    $oldWeight = $binOld->CurrentWeight;
    $weightDiff = max(0, $weight - $oldWeight);
    $link = Connect();
    $time = time();
    $sql = "INSERT INTO `history` (binId, weight, unixStamp) VALUES ('{$id}', '{$weight}', '{$time}')";
    mysqli_query($link, $sql);
    $bin = GetBin($id);
    $typeId = (int) $bin[3];
    $typeName = binTypes($bin[3], "en");
    // award points
    $toAward = new PointObject();
    $points = array();
    switch ($typeName) {
        case "Waste":
            $toAward->Waste = $weightDiff * getExchangeRates()->waste;
            break;
        case "Plastic":
            $toAward->Plastic = $weightDiff * getExchangeRates()->plastic;
            break;
        case "Glass":
            $toAward->Glass = $weightDiff * getExchangeRates()->glass;
            break;
        case "Organic":
            $toAward->Organic = $weightDiff * getExchangeRates()->organic;
            break;
        case "Tin":
            $toAward->Tin = $weightDiff * getExchangeRates()->tin;
            break;
        case "Paper":
            $toAward->Paper = $weightDiff * getExchangeRates()->paper;
            break;
        case "Chemical":
            $toAward->Chemical = $weightDiff * getExchangeRates()->chemical;
            break;
    }
    $userId = (int) $bin[1];
    $user = makeUserFromRaw(GetUser($userId), "full");
    $newPoints = new PointObject();
    $newPoints->Add($user->Points);
    $newPoints->Add($toAward);
    $user->Points = $newPoints;
    $user->Points->RemoveNegative();
    EditUserPoints($user->UserId, json_encode($user->Points));
    //
    return $toAward;
}