<?php

$path_to_root = "../..";
include_once($path_to_root . "/includes/ui/items_cart.inc");
include_once($path_to_root . "/gl/includes/gl_db.inc");

function add_bank_payment($rest) {
    global $Refs, $systypes_array;
    $req = $rest->request();
    $info = $req->post();

    $deposit = new items_cart(ST_BANKPAYMENT);
    
    $can_process = check_item_data($info);
    if ($can_process['passed'] == false) {
        unset($deposit);
        api_error(200, $can_process['message']);
        return;
    }
    
    foreach ($info['gl_items'] as $item) {
        $deposit->add_gl_item($item['code_id'], $info['dimension']['id'], 0, $item['amount'], $item['memo']);
    }
    
    $can_process = check_trans($deposit,$info);
    if ($can_process['passed'] == false) {
        unset($deposit);
        api_error(200, $can_process['message']);
        return;
    }
    
    $deposit->tran_date = $info['date_'];
    $deposit->reference = $Refs->get_next($deposit->trans_type, null, $deposit->tran_date);
    $reference = $deposit->reference;
    
    $trans = write_bank_transaction(
            $deposit->trans_type, $deposit->order_id, $info['bank_account'], $deposit, $deposit->tran_date, 0, 0, 0, $deposit->reference, $info['memo'], true, null);
    if(!$trans[1]){
        unset($deposit);
        api_error(200, "could not save to database");
        return;
    }
    
    $response['msg'] = $systypes_array[$deposit->trans_type] . " has been saved";
    $response['reference'] = $reference;
    $response['type_no'] = $trans[1];
    api_success_response(json_encode($response));
}

function check_trans($deposit, $info) {
    global $Refs, $systypes_array;

    if ($deposit->count_gl_items() < 1) {
        return array("passed" => false, "message" => _("You must enter at least one payment line."));
    }

    if ($deposit->gl_items_total() == 0.0) {
        return array("passed" => false, "message" => _("The total bank amount cannot be 0."));
    }

    $limit = get_bank_account_limit($info['bank_account'], $info['date_']);

    $amnt_chg = -$deposit->gl_items_total() - $deposit->original_amount;

    if ($limit !== null && floatcmp($limit, -$amnt_chg) < 0) {
        return array("passed" => false, "message" => sprintf(_("The total bank amount exceeds allowed limit (%s)."), price_format($limit - $deposit->original_amount)));
    }
    if ($trans = check_bank_account_history($amnt_chg, $info['bank_account'], $info['date_'])) {
        if (isset($trans['trans_no'])) {
            return array("passed" => false, "message" => sprintf(_("The bank transaction would result in exceed of authorized overdraft limit for transaction: %s #%s on %s."),
                            $systypes_array[$trans['type']], $trans['trans_no'], sql2date($trans['trans_date'])));
        }
    }
    if (!check_reference($deposit->reference, $deposit->trans_type, $deposit->order_id)) {
        return array("passed" => false, "message" => _("The reference is invalid."));
    }
    if (!is_date($info['date_'])) {
        return array("passed" => false, "message" => _("The entered date for the payment is invalid."));
    } elseif (!is_date_in_fiscalyear($info['date_'])) {
        return array("passed" => false, "message" => _("The entered date is out of fiscal year or is closed for further data entry."));
    }
    
    $currency = get_bank_account_currency($info['bank_account']);
    if (!db_has_currency_rates($currency, $info['date_'], true))
        return array("passed" => false, "message" => sprintf(_("Cannot retrieve exchange rate for currency %s as of %s. Please add exchange rate manually on Exchange Rates page."),
					 $currency, $info['date_']));
    return array("passed" => true);
}

function check_item_data($info) {
    
    foreach ($info['gl_items'] as $item){
        if (!$item['amount']) {
            return array("passed" => false, "message" => _("The amount entered is not a valid number or is less than zero."));
        }
        if (isset($info['_ex_rate']) && $info['_ex_rate'] <= 0) {
            return array("passed" => false, "message" => _("The exchange rate cannot be zero or a negative number."));
        }
    }

    return array("passed" => true);
}
