<?php
/**********************************************************************
***********************************************************************/


function create_iou_bank_payment_cart($type, $cart_name)
{
	global $Refs;

	if (isset($_SESSION[$cart_name]))
	{
            unset ($_SESSION[$cart_name]);
	}

	$cart = new items_cart($type);
        $cart->order_id = 0;

	
        $cart->reference = $Refs->get_next($cart->trans_type);
        $cart->tran_date = new_doc_date();
        if (!is_date_in_fiscalyear($cart->tran_date)){
                $cart->tran_date = end_fiscalyear();
        }
	

	$_POST['memo_'] = $cart->memo_;
	$_POST['ref'] = $cart->reference;
	$_POST['date_'] = $cart->tran_date;

	$_SESSION[$cart_name] = &$cart;
}


function add_iou_bank_payment_new_item($cart_name, $amount, $account_code, $line_memo)
{
    
	$_SESSION[$cart_name]->add_gl_item($account_code, 0,
		0, $amount, $line_memo);
        
        return array("success"=>true, "set_focus"=>'', "message"=>'');

}

function check_iou_bank_payment_item_data($amount, $ex_rate)
{
        if($_POST['payment_method'] == 1){//Bank
            if(!(input_num('bank_account') > 0)){ 
                     $msg = ( _("Please select a bank account."));
                    $set_focus = ('bank_account');
                    return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
            }
        }
    
	if (!check_num2($amount, 0.001))
	{
		$msg = ( _("The amount entered is not a valid number or is less than zero."));
		$set_focus = ('amount');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
	}
	if ($ex_rate <= 0)
	{
		$msg = ( _("The exchange rate cannot be zero or a negative number."));
		$set_focus = ('_ex_rate');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
	}

	return array("success"=>true, "set_focus"=>'', "message"=>'');
}

function check_iou_bank_payment_trans_data($cart_name)
{
	global $Refs;

	if ($_SESSION[$cart_name]->count_gl_items() < 1) {
		$msg = (_("You must enter at least one payment line."));
		$set_focus = ('code_id');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
	}

	if ($_SESSION[$cart_name]->gl_items_total() == 0.0) {
		$msg = (_("The total bank amount cannot be 0."));
		$set_focus = ('code_id');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
	}


	if (!$Refs->is_valid($_POST['reference']))
	{
		$msg = ( _("You must enter a reference."));
		$set_focus = ('reference');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
	}
	$ref_val_msg = reference_exists($_POST['reference'], $_SESSION[$cart_name]->trans_type);
        if ($ref_val_msg != "")
	{
		$set_focus = ('ref');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$ref_val_msg);
	}
	if (!is_date($_POST['payment_date']))
	{
		$msg = (_("The entered date for the payment is invalid."));
		$set_focus = ('payment_date');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
	}
	
        if (!is_date_in_fiscalyear($_POST['payment_date']))
	{
		$msg = (_("The entered date is not in fiscal year."));
		$set_focus = ('payment_date');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
	} 

        $ap_msg = is_accounting_period_open($_POST['payment_date']);
	if ($ap_msg['success'] !== true)
	{
		$msg = ($ap_msg['message']);
		$set_focus = ('payment_date');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
	}
        
        
	if (!db_has_currency_rates(get_bank_account_currency($_POST['bank_account']), $_POST['payment_date'], true)){
                $msg = (_("Exchange rates not found."));
		$set_focus = ('payment_date');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
        }

	if (isset($_POST['settled_amount']) && (input_num('settled_amount') <= 0)) {
		$msg = (_("Settled amount have to be positive number."));
		$set_focus = ('settled_amount');
		return array("success"=>false, "set_focus"=>$set_focus, "message"=>$msg);
	}
        
	return array("success"=>true, "set_focus"=>"", "message"=>"");
}

function process_iou_bank_payment($cart_name, $bank_account,$date_,
                                $PayType, $person_id, $PersonDetailID,
                                $ref, $memo_, $settled_amount, $ex_rate, $gl_trans_type_id)
{
        global $Refs;

        $_SESSION[$cart_name] = &$_SESSION[$cart_name];
        $new = $_SESSION[$cart_name]->order_id == 0;

        $trans = write_bank_transaction(
                $_SESSION[$cart_name]->trans_type, $_SESSION[$cart_name]->order_id, $bank_account,
                $_SESSION[$cart_name], $date_,
                $PayType, $person_id, $PersonDetailID,
                $ref, $memo_, true, $settled_amount, $gl_trans_type_id);

        add_new_exchange_rate(get_bank_account_currency($bank_account), $date_, $ex_rate);
        $trans_type = $trans[0];
        $trans_no = $trans[1];
        
//        $Refs->save(ST_IOU_BANKPAYMENT, $trans_no, $ref);

        $_SESSION[$cart_name]->clear_items();
        unset($_SESSION[$cart_name]);

        return $trans_no;

}


function add_iou_bank_payment($iou_id, $selected_id)
{   
    global $systypes_array;
    
    if($_POST['is_return'] == 1){
        $trans_type = ST_IOU_BANKPAYMENT_RETURN;
        $cart_name = "IOU_BANK_PAY_RETURN";
        $payment_amount = -input_num('amount');
    }
    else{
        $trans_type = ST_IOU_BANKPAYMENT;
        $cart_name = "IOU_BANK_PAY";
        $payment_amount = input_num('amount');
    }
    
    
    $iou = get_i_owe_you_record($iou_id);
    $row_state = $iou["row_state"];
    $float_id = $iou["float_id"];
    $float_row = get_petty_cash_float_line($float_id);
    
    $cd = check_i_owe_you_payment_data($iou_id, $selected_id);
    if($cd["success"] !== true) 
    {
       return $cd;
    }
    
    
    $ex_rate = 1;
    
    $cd = check_iou_bank_payment_item_data(input_num('amount'), $ex_rate);
    if($cd["success"] !== true) 
    {
       return $cd;
    }
    
    create_iou_bank_payment_cart($trans_type, $cart_name);
    
    $default_emp_pc_advances_act = get_sys_prefs_parameter_value('emp_pc_advances_act');
    
    $project = get_project_record($iou['project_id']);

    if (!(strlen($default_emp_pc_advances_act) > 2))
    {
        $msg = ( _("Employee petty cash advances not defined in the system."));
        return array("success"=>false, "set_focus"=>'', "message"=>$msg);
    }
    
    if(strlen($project['employee_advances_account']) > 2){
        $emp_pc_advances_act = $project['employee_advances_account'];
    }else{
        if(strlen($float_row['credit_account']) > 2){
            $emp_pc_advances_act = $float_row['credit_account'];
        }
        else{
            $emp_pc_advances_act = $default_emp_pc_advances_act;
        }
    }
        
    $line_memo = "";
    
    $cd = add_iou_bank_payment_new_item($cart_name, $payment_amount, $emp_pc_advances_act, $line_memo);
    if($cd["success"] !== true) 
    {
       return $cd;
    }

    $cd = check_iou_bank_payment_trans_data($cart_name);
    if($cd["success"] !== true) 
    {
       return $cd;
    }
    
    $bank_account = $_POST['bank_account'];
    $bank_payment_date_ = $_POST['payment_date'];
    $PayType = PT_IOU;
    $person_id = $iou_id;
    $PersonDetailID = 0;
    $ref = $_POST['reference'];
    $memo_ = $_POST['payment_comment'];
    $settled_amount = $payment_amount;
    
    $gl_trans_type_id = 42;
            
//    return array("success" => true, "set_focus"=>'', "message" => "Could not create IOU bank payment.");
     
    $trans_no = process_iou_bank_payment($cart_name, $bank_account,$bank_payment_date_,
                                $PayType, $person_id, $PersonDetailID,
                                $ref, $memo_, $settled_amount, $ex_rate, $gl_trans_type_id);
    
                        
    if(!($trans_no > 0)){
        return array("success" => true, "set_focus"=>'', "message" => "Could not create IOU bank payment.");
    }
    
    $iou_bank_total = get_i_owe_you_bank_payments_total($iou_id);
    $iou_bank_total = -($iou_bank_total);
    
    update_i_owe_you_bank_payments_total($iou_id, $iou_bank_total, $row_state);
    
    $n = db_num_affected_rows();
    if(!($n > 0)){
        return array("success" => true, "set_focus"=>'', "message" => "Could not update IOU bank payments total.");
    }
    
    $project_float = get_project_float_by_project_id($iou['project_id']);
    if($project_float && $project_float['inactive'] == 0){
        if($iou['company_code'] == $project_float['company_code'] && $iou['employee_code'] == $project_float['employee_code']){
            $pf_balance = get_project_float_balance($iou['project_id']);
            $pf_new_balance = $pf_balance + $payment_amount;
            $pf_limit = $project_float['amount'];
            if($pf_new_balance > $pf_limit){
                $message = "This payment will make the Project Float balance ".number_format($pf_new_balance,2).", higher than its limit of ".number_format($pf_limit,2);
                return array("success" => false, "message" => $message);
            }
            add_to_project_float($trans_type, $trans_no, $iou['project_id'], $project_float['company_code'], 
                                    $project_float['employee_code'], $payment_amount, date2sql($bank_payment_date_));
        }
    }
        
    return array("success" => true, "trans_no" => $trans_no, "message" => $systypes_array[$trans_type]." #.$trans_no has been created.");

    
}


function make_iou_bank_payment($iou_id, $payment_id)
{
    //$myrow = get_salary_advance_details($id);
    $iou = get_i_owe_you_record($iou_id);    
    //$account_codes = get_salary_advance_account_detail($myrow['type_id']);
    $account_codes = array();    
//    if(!$account_codes){
//        return array("success" => false, "Could not retrieve payment account details for this slary advance type. Not possible to make the payment.");
//    }
//    
//    if(($account_codes['debit_code'] == "" || $account_codes['credit_code'] == ""))
//    {
//        return array("success" => false, "Account definition for this salary advance type is not complete. Not possible to make the payment.");
//
//    }
//    
//    if($myrow['status_code'] == "D"){
//        return array("success" => false, "Payment has been already processed for this salary advance.");
//    }
//    
//    if($myrow['status_code'] != "A"){
//        return array("success" => false, "This salary advance has not been approved.");
//    }

    $num_rows = release_i_owe_you_payment($iou, $account_codes, $payment_id);
    if($num_rows != 1){
        return array("success" => false, "message" => "Another user has updated I Owe You payment $payment_id.");
    }
    
    $payment_total = get_i_owe_you_payments_total($iou_id, -1, 1);
    $n2 = update_i_owe_you_payments_total($iou_id, $payment_total, $iou['row_state']);
    if($n2 != 1){
        return array("success" => false, "message" => "Another user has updated I Owe You $iou_id.");
    }
    
    $payment_amount = input_num('amount');

    if($_POST['is_return'] == 1){
        $float_payment_amount = $payment_amount;
    }
    else{
        $float_payment_amount = -$payment_amount;
    }

    add_to_petty_cash_float(ST_I_OWE_YOU_PAYMENT, $payment_id, $iou['float_id'], $float_payment_amount, $_POST['payment_date']);

    $project_float = get_project_float_by_project_id($iou['project_id']);
    if($project_float && $project_float['inactive'] == 0){
        if($iou['company_code'] == $project_float['company_code'] && $iou['employee_code'] == $project_float['employee_code']){
            $pf_balance = get_project_float_balance($iou['project_id']);
            $pf_new_balance = $pf_balance + $payment_amount;
            $pf_limit = $project_float['amount'];
            if($pf_new_balance > $pf_limit){
                $message = "This payment will make the Project Float balance ".number_format($pf_new_balance,2).", higher than its limit of ".number_format($pf_limit,2);
                return array("success" => false, "message" => $message);
            }
            add_to_project_float(ST_I_OWE_YOU_PAYMENT, $payment_id, $iou['project_id'], $project_float['company_code'], 
                                    $project_float['employee_code'], $payment_amount, $iou['tran_date']);
        }
    }
        
    return array("success" => true, "message" => "I Owe You payment $payment_id has been released.");
    
}
