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


function can_complete_iou_with_no_expenses($iou_id)
{
    global $document_approval_statuses, $systypes_array;
    
        $py_q = get_unreleased_i_owe_you_payments($iou_id);
        if(db_num_rows($py_q) > 0){
            $message = "There are unreleased payments belongs to ".$systypes_array[ST_I_OWE_YOU]." #".$iou_id." and it can not be completed.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $iou = get_i_owe_you_record($iou_id);  
        $total_iou_payments = get_i_owe_you_payments_total($iou_id, -1, 1); 
        $iou_bank_total = -get_i_owe_you_bank_payments_total($iou_id); 
        $iou_advances_total = get_i_owe_you_advances_paid_total($iou_id);
//        $total = $total_advances_paid + $total_payments + $bank_payments + $advance_amount;
        
//        $released_payments_total = get_released_i_owe_you_payments_total($iou_id);
//        $payments_advance_total = $released_payments_total + $iou['advance_amount'];
//        if($payments_advance_total > 0){
//            $message = "There is a balance of Rs. $payments_advance_total of payments plus advances of this I Owe You and it can not be completed.";
//            $set_focus = '';
//            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
//        }
        
        if($iou['batch_complete'] == true){
            $message = "Expenses batch (".$iou['batch_no'].") of ".$systypes_array[ST_I_OWE_YOU]." #".$iou_id." has been already completed.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    
        if($iou['advances_batch_no'] > 0){
            $message = "An advance payment has been done for ".$systypes_array[ST_I_OWE_YOU]." #".$iou_id.". It can not be completed alone.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $total_payments = $total_iou_payments + $iou_advances_total + $iou_bank_total;
        if(abs($total_payments) > 0){
            $message = "A net payment of Rs. ".$total_payments." has been done for ".$systypes_array[ST_I_OWE_YOU]." #".$iou_id.". Paid net amount should be zero to complete this IOU.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        if($iou['batch_no'] == 0){
            $message = "Expense batch number is required and it has to be either ".$document_approval_statuses[AS_APPROVED]." or ".$document_approval_statuses[AS_REJECTED]." to complete this I Owe You. 
                        Please go to the expense entry srceen. That creates a batch number. No need to enter expenses.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        
        if($iou['batch_no'] > 0){
            
            $batch = get_i_owe_you_batch_header($iou['batch_no']);
            if(!($batch['approval_status'] == AS_APPROVED || $batch['approval_status'] == AS_REJECTED))
            {
                $message = "Status of this I Owe You bacth should be ".$document_approval_statuses[AS_APPROVED]." or ".$document_approval_statuses[AS_REJECTED]." to complete ".$systypes_array[ST_I_OWE_YOU]." #".$iou_id.".";
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
        
            $result_batch_i_owe_yous = get_batch_i_owe_yous($iou['batch_no']);
            if(db_num_rows($result_batch_i_owe_yous) > 1) // There are more IOUS included in this batch
            {
                $message = "There are other I Owe Yous included in the expense batch. This I Owe You can not be completed alone.";
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
            
            $result_batch_expences = get_batch_i_owe_you_valid_expences($iou['batch_no']);
            if(db_num_rows($result_batch_expences) > 0) // Real (not Rejected) expenses entered 
            {
                $message = "There are expences entered and this I Owe You can not be completed alone.";
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
            
        }
        
        return array("success" => true, "message" => "");
        
    
    
    
    

}

function can_complete_iou_batch_with_expenses($batch_no, $keep_balance = false)
{
    global $approval_statuses;
        
        if(!($batch_no > 0)) // Not gone to the expenses entry screen
        {
            $message = "No expenses entered yet. Can not complete batch.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $result = get_batch_i_owe_you_expences($batch_no);
        if(db_num_rows($result) == 0) // No real expenses entered 
        {
            $message = "No approved expenses found. Can not complete batch.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $batch = get_i_owe_you_batch_header($batch_no);
        if(!($batch['approval_status'] == AS_APPROVED || $batch['approval_status'] == AS_REJECTED))
        {
            $message = "Status of this I Owe You bacth does not allow completing.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        if($batch['complete'])
        {
            $message = "This expense batch has been completed already.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $ex_q = get_unapproved_i_owe_you_batch_expences($batch_no);
        if(db_num_rows($ex_q) > 0){
            $message = "There are unapproved expenses. Can not complete this I Owe You batch.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $py_q = get_unreleased_i_owe_you_batch_payments($batch_no);
        if(db_num_rows($py_q) > 0){
            $message = "There are unreleased payments belongs to this I Owe You batch and it can not be completed.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }

        $approved_expenses_total = get_approved_i_owe_you_batch_expenses_total($batch_no);
        $released_payments_total = get_released_i_owe_you_batch_payments_total($batch_no);
        $advances_total = get_i_owe_you_batch_advances_total($batch_no);
        $bank_payments_total = -get_i_owe_you_batch_bank_payments_total($batch_no);
        
        if($batch['approval_status'] == AS_REJECTED){
            $approved_expenses_total = 0;
            $payments_advances_total = $released_payments_total + $advances_total + $bank_payments_total;
            if($payments_advances_total != 0){
                $message = "All payments total of this batch is ". number_format($payments_advances_total,2)
                            ." (= IOU Payments Rs. ".number_format($released_payments_total,2)
                            ." + Advances Rs.".number_format($advances_total,2)
                            ." + Bank Payments Rs.".number_format($bank_payments_total,2).")."
                            ." It has to be zero to complete this ".$approval_statuses[AS_REJECTED]." batch."; 
                
                return array("success" => false, "focus_to" => "", "message" => $message);
            }
            
            return array("success" => true, "message" => "");
        }
        
        
        
        
        if($approved_expenses_total == 0){
            $message = "No approved expenses for this batch and it can not be completed.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        if($keep_balance){
            $biou_result = get_batch_i_owe_yous($batch_no);
            $iou = db_fetch($biou_result);
            $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']){
                    // can keep the balance with projct float and complete expense batch
                }
                else{
                    $emp_name = get_group_company_employee_formatted_long_name($project_float['company_code'], $project_float['employee_code']);
                    $message = "Current emplyee is different to the project float owner ".$emp_name.". Can not complete this expense batch by keeping the balance with project float.";
                    $set_focus = '';
                    return array("success" => false, "focus_to" => $set_focus, "message" => $message);
                }
            }
            else{
                $message = "No active project float found. Can not complete this expense batch by keeping the balance with project float.";
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
        }
        else{
            $payments_advances_total = $released_payments_total + $advances_total + $bank_payments_total;
            if($payments_advances_total == 0){
                $message = "All payments total of this batch is zero and it can not be completed.";
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }

            
            if($payments_advances_total != $approved_expenses_total){
                $message = "Approved expenses total Rs.".number_format($approved_expenses_total,2)." and total payments ".number_format($payments_advances_total,2)
                            ." (= Payment Rs. ".number_format($payments_advances_total,2)
                            ." + Advances Rs.".number_format($payments_advances_total,2)
                            ." + Bank Payments Rs.".number_format($payments_advances_total,2).") do not match. This batch can not be completed.";
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
        }
        
        return array("success" => true, "message" => "");
        
    
    
    
    

}


function check_i_owe_you_payment_data($iou_id, $selected_id)
{   
    global $systypes_array;
    
    $iou = get_i_owe_you_record($iou_id);

    $project_id = $iou['project_id'];
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($project_id, $user_id);
    if($cap['success'] !== true) 
    {
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $cap['message']);  
    }
        
        
    $cpfa = check_petty_cash_float_access($iou['float_id'], $user_id);
    if ($cpfa['success'] !== true)
    {
        $set_focus = 'float_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $cpfa['message']);  
    }
            
    if ($iou['approval_status'] != AS_APPROVED){
        $message = "This I Owe Yo is not approved. Can not make payments for it.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    } 
    
    
    if ($iou['batch_complete'] == 1){
        $message = "This I Owe You batch has been completed and can not make any transactions related to it.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }   
    
    if (!check_num('amount',0.01)){
        $message = "Amount entered should be greater than zero.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }    
  
   
    if (!is_date($_POST['payment_date']))
   	{
        $message = "Date entered is not a valid date.";
        $set_focus = 'payment_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}
        
    if (!is_date_in_fiscalyear($_POST['payment_date'])) {
        $message = (_("The entered date is not in fiscal year."));
        $set_focus = ('payment_date');
        return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);
    }
        
    $msg = is_accounting_period_open($_POST['payment_date']);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']);
        $set_focus = ('payment_date');
        return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);
    }
    
           
    $advace = get_i_owe_you_advances_paid_total($iou_id);
//    $advace = $iou['advance_amount'];
    
    $iou_bank_total = get_i_owe_you_bank_payments_total($iou_id);
    $bank_payments = -($iou_bank_total);
//    $bank_payments = $iou['bank_payments'];
    
    $pay_tot = get_i_owe_you_payments_total($iou_id, $selected_id);
    if($_POST['is_return'] == 1){
        $this_payment_amount = input_num('amount') * -1;
        
        $payments_total = $pay_tot + $advace + $bank_payments + $this_payment_amount;

        if(0 > $payments_total){ 
            $message = "This payment (Rs.".number_format($this_payment_amount,2)
                                .") + Paid and unpaid ".$systypes_array[ST_I_OWE_YOU_PAYMENT]."s total (Rs.".number_format($pay_tot,2)
                                .") + ".$systypes_array[ST_I_OWE_YOU_ADVANCES]."s total (Rs.".number_format($advace,2)
                                .") + ".$systypes_array[ST_IOU_BANKPAYMENT]."s total (Rs.".number_format($bank_payments,2)
                                .") <br>total (Rs.".number_format($payments_total,2)
                                .") can not be negative.";
            $set_focus = 'amount';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    }
    else{
        $this_payment_amount = input_num('amount');
    
        $payments_total = $pay_tot + $advace + $bank_payments + $this_payment_amount;

        if($iou['amount'] < $payments_total){ 
            $message = "This payment (Rs.".number_format($this_payment_amount,2)
                                .") + Paid and unpaid ".$systypes_array[ST_I_OWE_YOU_PAYMENT]."s total (Rs.".number_format($pay_tot,2)
                                .") + ".$systypes_array[ST_I_OWE_YOU_ADVANCES]."s total (Rs.".number_format($advace,2)
                                .") + ".$systypes_array[ST_IOU_BANKPAYMENT]."s total (Rs.".number_format($bank_payments,2)
                                .") <br>total (Rs.".number_format($payments_total,2)
                                .") can not be more than the ".$systypes_array[ST_I_OWE_YOU]." amount (Rs.".number_format($iou['amount'],2).").";
            $set_focus = 'amount';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    }

    if($payments_total < 0){
        $message = "Total of payments and advances can not be negative.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    $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']){
            $payment_amount = input_num('amount');
            $pf_balance = get_project_float_balance($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 ".$pf_limit;
                return array("success" => false, "message" => $message);
            }
        }
    }            
            
    return array("success" => true, "message" => "");
    
}



function add_iou_payment($iou_id, $selected_id)
{   
    if($_POST['payment_method'] == 1)
    {
       return array("success" => true, "message" => "");
    }
    
    $cd = check_i_owe_you_payment_data($iou_id, $selected_id);
    if($cd["success"] !== true) 
    {
       return array("success" => false, "message" => $cd["message"]);
    }
    
    $is_return = $_POST['is_return'];
    $amount = input_num('amount');
    if($_POST['is_return'])
    {        
      $amount *= -1;
    }    
       
    $iou = get_i_owe_you_record($iou_id);
    $rec_id = add_i_owe_you_payment($iou_id, $_POST['payment_date'], $amount, 
                                    $_POST['payment_comment'], $is_return, $iou['float_id'], ST_I_OWE_YOU);
    if($rec_id > 0){
        return array("success" => true, "trans_no" => $rec_id, "message" => "Petty Cash payment has been added.");
    }
    else{
        return array("success" => false, "message" => "Petty Cash payment could not be added.");
    }
}

function update_iou_payment($iou_id, $selected_id)
{
    $cd = check_i_owe_you_payment_data($iou_id, $selected_id);
    if($cd["success"] !== true) 
    {
        return array("success" => false, "message" => $cd["message"]);
    }
    
    $amount = input_num('amount');
    if($_POST['is_return'])
    {        
      $amount *= -1;
    }    
    
    $recs = update_i_owe_you_payment($selected_id, $_POST['payment_date'], $amount, $_POST['payment_comment']);
    if($recs == 1){
        return array("success" => true, "trans_no" => $selected_id, "message" => "Petty Cash payment has been updated.");
    }
    else{
        return array("success" => false, "message" => "Petty Cash payment could not be updated.");
    }
}



function complete_iou($iou_id)
{
          
//        $i_owe_you_details_q = get_i_owe_you_details($iou_id);
//        while ($myrow = db_fetch($i_owe_you_details_q))
//        {
//            add_to_task_cost($task_costs_summary, $myrow['task_id'], $myrow['amount'], $myrow['amount'], $myrow['amount']);
//        }
//        
//        get_task_cost_details($task_costs_summary);
//        
//        $current_user_id = $_SESSION['wa_current_user']->user;
//        
//        // Expences approval removes individual task allocations. 
//        // This is incase if something still reaining due to the continuous modifications.
//        // Once process gets stable this can be removed
//        $rta_msg = remove_task_allocations(ST_I_OWE_YOU, $iou_id, $task_costs_summary, $current_user_id);
//        if($rta_msg['success'] !== true)
//        {
//            cancel_transaction();
//            return array("success" => $rta_msg['success'], "tran_no" => $iou_id, "message" => $rta_msg['message']);
//        }  
        
        $n = complete_i_owe_you($iou_id);
        if($n != 1)
        {
            cancel_transaction();
            return array("success" => false, "tran_no" => $iou_id, "message" => "Another user has updated I Owe You $iou_id");
        }
        
        return array("success" => true, "message" => "");
}    
    


function complete_iou_batch_with_expenses($batch_no, $keep_balance = false)
{
    begin_transaction();
    
    $iou_batch_q = get_batch_i_owe_yous($batch_no);
    while ($iou = db_fetch($iou_batch_q))
    {
        $msg = complete_iou($iou['id']);
        if($msg['success'] !== true){
            cancel_transaction();
            return array("success" => false,  "tran_no" => $msg['tran_no'], "message" => $msg['message']);
        }
    }
    
    $n = complete_i_owe_you_batch($batch_no, $keep_balance);
    if($n != 1){
        cancel_transaction();
        return array("success" => false, "tran_no"=> $batch_no, "message" => "Could not complete IOU Batch ".$batch_no.".");
    }
    commit_transaction();
    return array("success" => true, "tran_no"=> $batch_no, "message" => "");
}


function make_iou_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.");
//    }
    
    
    $payment = get_i_owe_you_payment($payment_id);
    if (!is_date_in_fiscalyear($payment['payment_date'], true)) {
        $message = (_("The entered invoice date is not in fiscal year.")); 
        return array("success"=>false, "message"=>$message);
    }
        
    $msg = is_accounting_period_open($payment['payment_date'], true);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']); 
        return array("success"=>false, "message"=>$message);
    }

    $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;
    }
    
    $iou_payment_date_ = $_POST['payment_date'];

    add_to_petty_cash_float(ST_I_OWE_YOU_PAYMENT, $payment_id, $iou['float_id'], $float_payment_amount, $iou_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, date2sql($iou_payment_date_));
        }
    }
        
    return array("success" => true, "trans_no" => $payment_id, "message" => "I Owe You payment $payment_id has been released.");
    
}


function complete_iou_with_no_expenses($batch_no)
{
    begin_transaction();
    
    $iou_batch_q = get_batch_i_owe_yous($batch_no);
    while ($iou = db_fetch($iou_batch_q))
    {
        $msg = complete_iou($iou['id']);
        if($msg['success'] !== true){
            cancel_transaction();
            return array("success" => false,  "tran_no" => $msg['tran_no'], "message" => $msg['message']);
        }
    }
    
    $n = complete_i_owe_you_batch($batch_no);
    if($n != 1){
        cancel_transaction();
        return array("success" => false, "tran_no"=> $batch_no, "message" => "Could not complete IOU Batch ".$batch_no.".");
    }
    commit_transaction();
    return array("success" => true, "tran_no"=> $batch_no, "message" => "");
}

function delete_iou_payment_entry($iou_id, $selected_id)
{
    $cd = can_delete_i_owe_you_payment($iou_id, $selected_id);
    if($cd["success"] !== true) 
    {
       return array("success" => false, "message" => $cd["message"]);
    }

    $recs = delete_petty_cash_payment_entry($selected_id);
    if($recs != 1){
        return array("success" => false, "message" => "Petty cash payment could not be deleted.");
    }

    return array("success" => true, "message" => "Petty cash payment has been deleted.");
}


function can_delete_i_owe_you_payment($iou_id, $selected_id)
{   
    global $systypes_array;
    
    $iou = get_i_owe_you_record($iou_id);

    $project_id = $iou['project_id'];
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($project_id, $user_id);
    if($cap['success'] !== true) 
    {
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $cap['message']);  
    }
        
        
    $cpfa = check_petty_cash_float_access($iou['float_id'], $user_id);
    if ($cpfa['success'] !== true)
    {
        $set_focus = 'float_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $cpfa['message']);  
    }
            
    if ($iou['approval_status'] != AS_APPROVED){
        $message = "This I Owe Yo is not approved. Can not make payments for it.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    } 
    
    
    if ($iou['batch_complete'] == 1){
        $message = "This I Owe You batch has been completed and can not make any transactions related to it.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }   
    
    if (!is_date($_POST['payment_date']))
   	{
        $message = "Date entered is not a valid date.";
        $set_focus = 'payment_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}

    $advace = get_i_owe_you_advances_paid_total($iou_id); 
    
    $iou_bank_total = get_i_owe_you_bank_payments_total($iou_id);
    $bank_payments = -($iou_bank_total); 
     
    $pay_tot = get_i_owe_you_payments_total($iou_id, $selected_id);
//    $payment = get_i_owe_you_payment($selected_id);
//    $this_payment_amount = $payment['amount'];    

//    $payments_total = $pay_tot + $advace;

//    if($iou['amount'] < $payments_total){
//        $message = "Payments (".number_format($pay_tot,2)
//                            .") plus advances (".number_format($advace,2)
//                            .") total (".number_format($payments_total,2)
//                            .") can not be more than the approved amount (".number_format($iou['amount'],2).").";
//        $set_focus = 'amount';
//        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
//    }

    $iou_amount = $iou['amount'];;
        
    $payments_total = $pay_tot + $advace + $bank_payments;

//    if($iou_amount < $payments_total){ 
//        $message = "When this payment is deleted "
//                            ." <br>Paid and unpaid ".$systypes_array[ST_I_OWE_YOU_PAYMENT]."s total (Rs.".number_format($pay_tot,2)
//                            .") + ".$systypes_array[ST_I_OWE_YOU_ADVANCES]."s total (Rs.".number_format($advace,2)
//                            .") + ".$systypes_array[ST_IOU_BANKPAYMENT]."s total (Rs.".number_format($bank_payments,2)
//                            .") <br>total (Rs.".number_format($payments_total,2)
//                            .") will be higher than the  ".$systypes_array[ST_I_OWE_YOU]." amount of (Rs.".number_format($iou_amount,2).")";
//
//        return array("success" => false, "focus_to" => "", "message" => $message);
//    }

    if(0 > $payments_total){ 
        $message = "When this payment is deleted "
                            ." <br>Paid and unpaid ".$systypes_array[ST_I_OWE_YOU_PAYMENT]."s total (Rs.".number_format($pay_tot,2)
                            .") + ".$systypes_array[ST_I_OWE_YOU_ADVANCES]."s total (Rs.".number_format($advace,2)
                            .") + ".$systypes_array[ST_IOU_BANKPAYMENT]."s total (Rs.".number_format($bank_payments,2)
                            .") <br>total (Rs.".number_format($payments_total,2)
                            .") will go negative."; 

        return array("success" => false, "focus_to" => "", "message" => $message);
    }
    
    
    $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']){
            $payment_amount = input_num('amount');
            $pf_balance = get_project_float_balance($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 ".$pf_limit;
                return array("success" => false, "message" => $message);
            }
        }
    }            
            
    return array("success" => true, "message" => "");
    
}


function display_i_owe_you_payment_edit_controls(&$selected_id, &$Mode, $iou_id)
{
    
    $iouh = get_i_owe_you_record($iou_id);
    display_project_float_message($iouh['project_id'], $iouh['company_code'], $iouh['employee_code']);


    br(1);

//-----------------------------------------------------------------------------------------------

    $_POST['id'] = 0;
    //$_POST['expence_description'] = "";
    $_POST['payment_date'] = ""; 
//    $_POST['is_return'] ="";
    $_POST['amount'] = "";
    $_POST['payment_comment'] ="";

    global $Refs, $Ajax;
    
    $Ajax->activate("reference");
        
    if($selected_id > 0 ){
        if ($Mode =='Edit'){
            $id = $selected_id;

            $myrow = get_i_owe_you_payment($id);       

            $_POST['id'] = $myrow["id"];       
            $_POST['payment_date'] = sql2date($myrow["payment_date"]);
            $_POST['is_return'] = $myrow["is_return"];
            $_POST['amount'] = $myrow["amount"];
            if(($myrow['is_return']) == 1){
                $amount = $_POST['amount'];   
                $amount *= -1;        
                $_POST['amount'] = $amount;  
            }
            $_POST['payment_comment'] = $myrow["comment"]; 
            hidden('id', $_POST['id']);
        }


        hidden('selected_id', $selected_id);
        hidden('iou_id', $iou_id);

        start_table(TABLESTYLE2);

        label_row("I Owe You:", $iou_id);

        $_POST['payment_method'] = 0;
        hidden('payment_method', $_POST['payment_method']);
        
        if($_POST['is_return'] ==  true){
            $is_return_name = "Return";
        }
        else{
            $is_return_name = "Pay";
        }
        label_row("Pay/Return", $is_return_name);
        hidden('is_return', $_POST['is_return']);

        date_row("Date:", "payment_date"); 

        amount_row('Amount:', 'amount', $_POST['amount'], null, null, 2);
        textarea_row("Comment:", "payment_comment",null,30,3);
        end_table(1);
        br();


        submit_add_or_update_center($selected_id == -1, '', 'both');
        br();
        submit_center_first('Update_Make_Payment', _("Make Payment"), '', 'default');
        submit('Update_Make_Payment_Close_IOU_For_Payments', _("Make Payment & Close IOU for Payments"), true, '', 'default');
        submit_center_last('Close_IOU_For_Payments', _("Close IOU For Payments"), '', 'default');
        br();
        submit_center_first('Update_Make_Payment_Complete_Batch', _("Make Payment & Complete Batch"), '', 'default');
        submit_center_last('Complete_Batch', _("Complete Batch"), '', 'default');
        br();
        submit_center_first('Complete_IOU_With_No_Expenses', _("Complete IOU With No Expenses"), '', 'default');
        submit_center_last('Keep_Balance_Complete_Batch', _("Keep Balance with Project Folat and Complete Batch"), '', 'default');
    }    
    else{//New
        hidden('selected_id', $selected_id);
        hidden('iou_id', $iou_id);

        start_table(TABLESTYLE2);
        //value_list_row("Expense Type:", "expense_type_id", "PETTY_CASH_EXPENSE_TYPES", null, '');
        label_row("I Owe You:", $iou_id);
    //    batch_i_owe_you_list_row("I Owe You:","i_owe_you_id", $batch_no, $iou_id, $selected_id, "Select an I Owe you");
        yesno_list_row("Payment Source", 'payment_method', null, 'Bank', 'Float', true);

        if(!isset_numeric_post('is_return', -1)){
            $_POST['is_return'] = 0;
        }
        yesno_list_row("Pay/Return", 'is_return', null, 'Return', 'Pay', true);
            
            
        if($_POST['payment_method'] == 1){//Bank
            bank_accounts_list_row("From:", 'bank_account', null, false,'');
            
//            hidden('is_return', 0);
            
            if($_POST['is_return'] == 1){//Return
                $Reference = $Refs->get_next(ST_IOU_BANKPAYMENT_RETURN);
            }
            else{
                $Reference = $Refs->get_next(ST_IOU_BANKPAYMENT);
            }
            $_POST['reference'] = $Reference;
            ref_row(_("Reference:"), 'reference');
        }
        else{ // Cash
            hidden('bank_account', 0);
            hidden('reference', '');
        }
        
        date_row("Date:", "payment_date");

        amount_row('Amount:', 'amount', $_POST['amount'], null, null, 2);
        textarea_row("Comment:", "payment_comment",null,30,3);
        end_table(1);

        br();

        if($_POST['payment_method'] == 0){
            submit_add_or_update_center($selected_id == -1, '', 'both');
        }

        br();
        submit_center_first('Add_Make_Payment', _("Make Payment"), '', 'default');
        submit('Add_Make_Payment_Close_IOU_For_Payments', _("Make Payment & Close IOU for Payments"), true, '', 'default');
        submit_center_last('Close_IOU_For_Payments', _("Close IOU for Payments"), '', 'default');

        br();
        submit_center_first('Add_Make_Payment_Complete_Batch', _("Make Payment & Complete Batch"), '', 'default');
        submit_center_last('Complete_Batch', _("Complete Batch"), '', 'default');

        br();
        submit_center_first('Complete_IOU_With_No_Expenses', _("Complete IOU With No Expenses"), '', 'default');
        submit_center_last('Keep_Balance_Complete_Batch', _("Keep Balance with Project Folat and Complete Batch"), '', 'default');

    }

}