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



function can_complete_petty_cash_expense_batch($batch_no, $keep_balance)
{

        $result = get_batch_i_owe_you_expences($batch_no);
        if(db_num_rows($result) == 0) // No real expenses entered 
        {
            $message = "No expences entered yet. 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 expense batch does not allow completing it.";
            $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 expense batch.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $py_q = get_unreleased_petty_cash_expense_batch_payments($batch_no);
        if(db_num_rows($py_q) > 0){
            $message = "There are unreleased payments belongs to expense 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_petty_cash_expenses_batch_payments_total($batch_no);
        
        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){
            $pce = get_petty_cash_expenses_header_by_batch_no($batch_no);
            $project_float = get_project_float_by_project_id($pce['project_id']);
            if($project_float && $project_float['inactive'] == 0){
                if($pce['company_code'] == $project_float['company_code'] && $pce['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{
            if($released_payments_total == 0){
                $message = "No released payments for this batch and it can not be completed.";
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
        
        
            if($released_payments_total != $approved_expenses_total){
                $message = "Approved expenses total $approved_expenses_total and released payments total $released_payments_total 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_petty_cash_payment_data($pce_id, $selected_id, $pce)
{   
    $project_id = $pce['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($pce['float_id'], $user_id);
    if ($cpfa['success'] !== true)
    {
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $cpfa['message']);  
    }
            
    if ($pce['approval_status'] != AS_APPROVED){
        $message = "This expenses batch is not approved. Can not make payments for it.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    } 
    
    
    if ($pce['batch_complete'] == 1){
        $message = "This  expenses 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, "focus_to" => $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, "focus_to" => $set_focus, "message" => $message);
    }
    
    $pay_tot = get_petty_cash_Payments_total(ST_PETTY_CASH, $pce_id, $selected_id);
    if($_POST['is_return'] == 1){
        $this_payment_amount = input_num('amount') * -1;
    }
    else{
        $this_payment_amount = input_num('amount');
    }
    $payments_total = $pay_tot + $this_payment_amount;

    if($pce['amount'] < $payments_total){
//        $message = "Can not create payments more than the expenses total.";
        $message = "Total of payments (".number_format($payments_total,2).") can not be more than the expenses total (".number_format($pce['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);
    }

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



function add_petty_cash_payment($pce_id, $selected_id)
{   
    $pce = get_petty_cash_expenses_header($pce_id);
    
    $cd = check_petty_cash_payment_data($pce_id, $selected_id, $pce);
    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;
    }    
       
    $rec_id = add_i_owe_you_payment($pce_id, $_POST['payment_date'], $amount, $_POST['payment_comment'], 
                                    $is_return, $pce['float_id'], ST_PETTY_CASH);
    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_petty_cash_payment($pce_id, $selected_id)
{
    $pce = get_petty_cash_expenses_header($pce_id);
    
    $cd = check_petty_cash_payment_data($pce_id, $selected_id, $pce);
    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)
//{
//
//    $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)
//{
//    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']);
//        }
//    }
//    
//
//}


function make_petty_cash_payment($pce_id, $payment_id)
{
    begin_transaction();
    
    //$myrow = get_salary_advance_details($id);
    $pce = get_petty_cash_expenses_header($pce_id);    
    //$account_codes = get_salary_advance_account_detail($myrow['type_id']);
    $account_codes = array();    

    $num_rows = release_i_owe_you_payment($pce_id, $account_codes, $payment_id);
    if($num_rows != 1){
        cancel_transaction();
        return array("success" => false, "message" => "Another user has updated Petty Cash payment $payment_id.");
    }
    
    if($_POST['is_return'] == 1){
        $payment_amount = input_num('amount');
    }
    else{
        $payment_amount = -input_num('amount');
    }
        
    add_to_petty_cash_float(ST_PETTY_CASH_PAYMENT, $payment_id, $pce['float_id'], $payment_amount, $_POST['payment_date']);
    
    $project_float = get_project_float_by_project_id($pce['project_id']);
    if($project_float && $project_float['inactive'] == 0){
        if($pce['company_code'] == $project_float['company_code'] && $pce['employee_code'] == $project_float['employee_code']){
            add_to_project_float(ST_PETTY_CASH_PAYMENT, $payment_id, $pce['project_id'], $project_float['company_code'], 
                                    $project_float['employee_code'], -$payment_amount, date2sql($_POST['payment_date']));
        }
    }
        

    commit_transaction();

    $cb_msg = complete_petty_cash_expenses_batch($pce_id, false);
    if($cb_msg["success"] !== true){
        return array("success" => true, "message" => "Petty cash payment $payment_id has been released.");
    }
    else{
        return array("success" => true, "message" => "Petty cash payment $payment_id has been released and expense batch ".$pce_id." has been completed.");
    }

}
    
function complete_petty_cash_expenses_batch($pce_id, $keep_balance = false)
{
    //$myrow = get_salary_advance_details($id);
    $pce = get_petty_cash_expenses_header($pce_id);    
    
    $batch_no = $pce['batch_no'];
    
    $ccpceb_msg = can_complete_petty_cash_expense_batch($batch_no, $keep_balance);
    if($ccpceb_msg['success'] !== true){
        
        return array("success" => false, "message" => $ccpceb_msg['message']);
    }
    
    begin_transaction();
    
    $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.".");
    }
    
    $n = complete_petty_cash_expenses_header($pce_id);
    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, "message" => "Petty cash expense $pce_id has been completed.");

}


function delete_petty_cash_payment($pce_id, $selected_id)
{
    
    $pce = get_petty_cash_expenses_header($pce_id);
    $cdpcp_msg = can_delete_petty_cash_payment($pce_id, $selected_id, $pce);
    if($cdpcp_msg['success'] !== true){        
        return array("success" => false, "message" => $cdpcp_msg['message']);
    }
    
    $n = delete_petty_cash_payment_entry($selected_id);
    if($n != 1){
        return array("success" => false, "message" => "Could not delete the petty cash payment entry");
    }
    
    return array("success" => true, "message" => "Selected petty cash payment entry has been deleted.");
    
}


function can_delete_petty_cash_payment($pce_id, $selected_id, $pce)
{   
    $project_id = $pce['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($pce['float_id'], $user_id);
    if ($cpfa['success'] !== true)
    {
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $cpfa['message']);  
    }
            
    if ($pce['approval_status'] != AS_APPROVED){
        $message = "This expenses batch is not approved. Can not make payments for it.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    } 
    
    
    if ($pce['batch_complete'] == 1){
        $message = "This  expenses 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);
   	}
    
    $pay_tot = get_petty_cash_Payments_total(ST_PETTY_CASH, $pce_id, $selected_id);
    $payments_total = $pay_tot;

    if($pce['amount'] < $payments_total){
        $message = "Total of payments (".number_format($payments_total,2).") can not be more than the expenses total (".number_format($pce['amount'],2).").";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }

    if($payments_total < 0){
        $message = "Total of payments can not be negative.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }

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