<?php

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

$sender = $database->get("accounts", ["[>]authkeys" => "accountid"], ["accounts.accountid", "balance", "type"], ["authkeys.key" => $VARS["key"]]);

if (!$database->has("accounts", ["publicid" => $VARS["to"]])) {
    sendJsonResp($Strings->get("Could not find the receiving account.", false), "ERROR");
}

$receiver = $database->get("accounts", ["accountid", "balance", "type"], ["publicid" => $VARS["to"]]);

$amount = $VARS["amount"] * 1.0;

if ($amount > $sender["balance"]) {
    sendJsonResp($Strings->get("Insufficient funds.", false), "ERROR");
}

if (($sender["type"] == 1 && $receiver["type"] == 2) || ($sender["type"] == 2 && $receiver["type"] == 3)) {
    $success = false;
    $database->action(function ($database) {
        global $VARS, $sender, $receiver, $amount, $success;

        $database->update("accounts", ["balance[+]" => $amount], ["accountid" => $receiver["accountid"]]);
        $database->update("accounts", ["balance[-]" => $amount], ["accountid" => $sender["accountid"]]);

        $database->insert("transactions", [
            "amount" => $amount,
            "fromid" => $sender["accountid"],
            "toid" => $receiver["accountid"],
            "datetime" => date("Y-m-d H:i:s")
        ]);
        $success = true;
    });

    if ($success) {
        sendJsonResp();
    } else {
        sendJsonResp($Strings->get("An unknown problem occurred.", false), "ERROR");
    }
} else {
    sendJsonResp($Strings->get("Money must be sent from givers to receivers.", false), "ERROR");
}