#include "..\script_component.hpp"

/*
 * Author: IDSolutions
 * Handles the purchase of an item
 *
 * Arguments:
 * 0: Price <NUMBER> - The price of the item
 *
 * Return Value:
 * None
 *
 * Example:
 * [1000] call forge_store_fnc_handlePurchase
 *
 * Public: No
 */

params ["_price"];

private _paymentData = GVAR(activePayment);
private _payment = call compile _paymentData;
private _store = nil;

scopeName "main";

if (count _payment > 3) then {
    private _authorizedUIDs = _payment select 3;

    if !(getPlayerUID player in _authorizedUIDs) then {
        ["You are not authorized to use this payment method!", "warning", 3, "right"] call EFUNC(misc,notify);
        false breakOut "main";
    };
};

if (_payment select 0 == "Organization") then {
    _store = call EFUNC(org,verifyOrgStore);
    private _org = _store call ["getOrg", []];
    private _ownerUID = _org get "owner";

    if (getPlayerUID player != _ownerUID) then {
        ["You do not own this organization!", "warning", 3, "right"] call EFUNC(misc,notify);
        false breakOut "main";
    };
};

private _varType = toLower (_payment select 2);
private _varName = _payment param [1, "", [""]];
private _balance = switch (_varType) do {
    case "organization": { _store call ["getFunds", []] };
    case "player": { GETVAR(player,_varName,0) };
    case "mission": { GETVAR(missionNamespace,_varName,0) };
    default { diag_log "[FORGE Store] Error: Unknown payment type"; 0 };
};

if (_balance < _price) exitWith {
    ["You do not have enough funds!", "warning", 3, "right"] call EFUNC(misc,notify);
    false
};

switch (_varType) do {
    case "organization": { _store call ["updateFunds", -_price] };
    case "player": {
        private _newBalance = _balance - _price;
        SETPVAR(player,_varName,_newBalance);
    };
    case "mission": {
        private _newBalance = _balance - _price;
        SETPVAR(missionNamespace,_varName,_newBalance);
    };
};

true