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

function remove_iou_batch_iou_task_allocations($batch_no, $current_user_id)
{
    $batch_i_owe_yous_q = get_batch_i_owe_yous($batch_no);
    while ($iou = db_fetch($batch_i_owe_yous_q)){
        $task_costs_summary = array();
        
        $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);
        
        $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']);
        }
        
    }
    return array("success" => true, "message" => "");
}


function can_release_batch_expenses_for_approval($batch_no){
    
    $batch = get_i_owe_you_batch_header($batch_no);
    
    if (!is_date_in_fiscalyear($batch['tran_date'], true)) {
        $message = (_("IOU Batch Date is not in fiscal year."));          
        return array("success" => false, "tran_no" => $batch_no, "message" => $message);        
    }
        
    $msg = is_accounting_period_open($batch['tran_date'], true);
    if ($msg['success'] !== true){
        $message = ($msg['message']);  
        return array("success" => false, "tran_no" => $batch_no, "message" => $message);        
    }
    
    
    return array("success" => true, "message" => "");        
}
    
function release_batch_expenses_for_approval($batch_no, $company_code, $employee_code){
    
    $cr_msg = can_release_batch_expenses_for_approval($batch_no);
    if($cr_msg['success'] !== true)
    {
        return $cr_msg;
    }
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $expences = get_batch_i_owe_you_expences($batch_no);
    $iou_batch_task_costs_summary = array();
    $batch_expences_count = 0;
    
    while ($myrow = db_fetch($expences)){        
        add_to_task_cost($iou_batch_task_costs_summary, $myrow['task_id'], $myrow['approved_amount'], $myrow['approved_amount'], $myrow['approved_amount']);
        
        $batch_expences_count++;
    }
        
    // update charging cost with actual additional amounts required (deduct the already allocated amounts)
    foreach ($iou_batch_task_costs_summary as &$task_cost_summary_line) {     
        $task_total_allocation = get_batch_i_owe_yous_total_task_allocation($batch_no, $task_cost_summary_line['task_id']);
        if($task_cost_summary_line['charging_cost'] > $task_total_allocation){
            // Only the additional amount for this task is required. Balance is already allocated
            $task_required_amount = $task_cost_summary_line['charging_cost'] - $task_total_allocation;
        }
        else{
            // More than the required amount already allocated
            $task_required_amount = 0;
        }
        
        $task_cost_summary_line['charging_cost'] = $task_required_amount;
    }
        
    get_task_cost_details($iou_batch_task_costs_summary);
    
//    $task_costs_summary = calculate_task_remaining_totals($mr_details_array);
    
    begin_transaction();
    
    $batch = get_i_owe_you_batch_header($batch_no);
    
    $pceh = get_petty_cash_expenses_header_by_batch_no($batch_no);
    if(is_array($pceh)){
        $batch_source_type = 1 ; // Petty Cash 
    }else{
        $batch_source_type = 0; // IOU expense 
    }

//    add_to_task_cost($task_costs_summary, $iou['task_id'], $iou['amount'], $iou['amount'], $iou['amount']);
    
    if($batch_source_type == 1){//Petty cash - check budgets
        $info = approve_document(ST_I_OWE_YOU_BATCH, $batch_no, $batch['project_id'], $iou_batch_task_costs_summary, 
                                        $batch['next_approval_group_id'], $current_user_id, $batch['row_state'], $batch['created_by']);
    }else{// IOU - Do not check budgets. IOUs already approved and these expense transactions are already done
        $info = approve_document(ST_I_OWE_YOU_BATCH, $batch_no, $batch['project_id'], $batch['amount'], 
                                        $batch['next_approval_group_id'], $current_user_id, $batch['row_state'], $batch['created_by']);
    }
    
    if($info['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $info['success'],"tran_no" => $batch_no, "message" => $info['message']);
    }

    if($info['approval_status'] == AS_APPROVED)
    {            
        $rbta_msg = remove_iou_batch_iou_task_allocations($batch_no, $current_user_id);
        if($rbta_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $rbta_msg['success'], "tran_no" => $batch_no, "message" => $rbta_msg['message']);
        }
        
        // Set the charging cost to real charging value (now the allocations are removed)
        foreach ($iou_batch_task_costs_summary as &$task_line){
            $task_line['charging_cost'] = $task_line['remaining_cost'];
        }
    
        // Refresh task total bdget details of the batch including row_state
        get_task_cost_details($iou_batch_task_costs_summary);
        
        $cct_msg = charge_cost_to_tasks(ST_I_OWE_YOU_BATCH, $batch_no, 
                        $iou_batch_task_costs_summary, $current_user_id);

        if($cct_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $cct_msg['success'], "tran_no" => $batch_no, "message" => $cct_msg['message']);
        }
        
        $n = update_batch_expences_approved($batch_no);
        if($batch_expences_count != $n){
            cancel_transaction();
            return array("success" => $cct_msg['success'], "tran_no" => $batch_no, "message" => "Another user has updated some of the  records");
        }
        
        $project_float = get_project_float_by_project_id($batch['project_id']);
        if($project_float && $project_float['inactive'] == 0){
            if($company_code == $project_float['company_code'] && $employee_code == $project_float['employee_code']){
                add_to_project_float(ST_I_OWE_YOU_BATCH, $batch_no, $batch['project_id'], $project_float['company_code'], 
                                        $project_float['employee_code'], -$batch['amount'], $batch['created_on']);
            }
        }
        
        if($batch['checked'] == 0){//For single step approval. No chance for the user to update documents checked manually
            set_expense_batch_checked($batch_no);
        }
    }
    else{// document not got approved. Still in the approval path.
        if($batch['approval_status'] == AS_AWAITING_APPROVAL){//previous status is awaiting approval. 2nd step release and onwards should set the documents checked
            set_expense_batch_checked($batch_no);
        }        
    }
    
    
//    $cioub = close_i_owe_you_batch($batch_no, $row_state);
//    if($cioub['success'] !== true)
//    {
//        cancel_transaction();
//        return $cioub;
//    }
//    
    commit_transaction();
    
    return array("success" => true, "tran_no" => $batch_no, "message" => $info['message']);
}

function set_expense_batch_checked($batch_no)
{
    $lv = get_listvalue_by_code("IOU_DOCUMENT_STATUSES", "DOC_CHKD");
    
    $batch_q = get_batch_i_owe_you_expences($batch_no);
    while ($ex = db_fetch($batch_q))
    {
        if($ex["document_status_id"] != $lv["id"]){
            update_batch_expense_detail_documents_checked_status($ex["id"], $lv["id"]);
        }
    }
    
    update_i_owe_you_batch_checked($batch_no);
}

function can_approve_expense($batch_no, &$row_state = 0, $release_for_approval=false)
{	
    $batch = get_i_owe_you_batch_header_record($batch_no);

    $project_id = $batch['project_id'];    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($project_id, $user_id);
    if($cap['success'] !== true) 
    {
        $message = ($cap["message"]);
        $focus_to = ('project_id');
        return array("success" => false, "focus_to" => $focus_to, "message" => $message);
    }
    
    if(!(in_array($batch['approval_status'], array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_BACK_TO_ORIGINATOR))))
    {
        $message = ( _("This expense batch status does not allow any changes to its details."));
        $focus_to = ('batch_task');
        return array("success" => false, "focus_to" => $focus_to, "message" => $message);
    }
    
    $ced = can_edit_document(ST_I_OWE_YOU_BATCH, $project_id, $batch['next_approval_group_id'], $user_id, $batch['created_by'], $batch['batch_no']);  
    if($ced['success'] !== true) 
    {
        $message = ($ced["message"]);
        $focus_to = ('project_id');
        return array("success" => false, "focus_to" => $focus_to, "message" => $message);
    }
    
    $batch_q = get_batch_i_owe_you_expences($batch_no);
    while ($ex = db_fetch($batch_q))
    {
        if ($batch['approval_status'] == AS_AWAITING_APPROVAL || $batch['approval_status'] == AS_WITH_THE_APPROVER) {
            if (isset($_POST['document_status_id_'.$ex["id"]])) {
                $document_status_id = $_POST['document_status_id_'.$ex["id"]];
            }
            
            if ($release_for_approval === true) {
                $lv = get_listvalue_by_code("IOU_DOCUMENT_STATUSES", "DOC_CHKD");
                if (! ($document_status_id > 0)) {                    
                    $msg = "Expenses line id ".$ex["id"].' : When releasing document status of all the lines have to be "'.$lv['value_name'].'".';
                    return array("success" => false, "message" => $msg);
                }
                if ($document_status_id != $lv['id']) {
                    $msg = "Expenses line id ".$ex["id"].' : When releasing document status of all the lines have to be "'.$lv['value_name'].'".';
                    return array("success" => false, "message" => $msg);
                }
            }
        }
        
        if(input_num('approved_amount'.$ex["id"]) > $ex['amount']){
            $msg = "Line id ".$ex["id"]." : Approving amount can not be higher than Rs. ". number_format($ex['amount'],2).".";
            return array("success" => false, "message" => $msg);
        }
        
        switch ($ex['expense_category_id']) {
            case EC_STOCK_ITEM_RECEIPT:
                $approved_amount = $ex['approved_amount'];
                $items_total = (float)get_petty_cash_stock_items_total_cost(ST_PETTY_CASH_ITEM_RECEIPT, ST_I_OWE_YOU_BATCH, $batch_no, $ex["id"]);
                if ($approved_amount < $items_total) {     
                    $msg = "Line id ".$ex["id"]." : Approving value can not be less than the total value of entered stock items Rs.". number_format($items_total,2).".";                    
                    return array("success" => false, "message" => $msg);
                } elseif($approved_amount > $items_total) {     
                    $msg = "Line id ".$ex["id"]." : Approving value can not be more than the total value of entered stock items Rs.". number_format($items_total,2).".";                    
                    return array("success" => false, "message" => $msg);
                }

            default:
                break;
        }

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

function can_delete_expense_batch($batch_no) {
    global $systypes_array;
    
    $batch = get_i_owe_you_batch_header_record($batch_no);
        if (! is_array($batch)) {
            return array("success" => false, "message" => $systypes_array[ST_I_OWE_YOU_BATCH]." #$batch_no has been deleted already.");
        }

    $project_id = $batch['project_id'];    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($project_id, $user_id);
        if ($cap['success'] !== true) {
            $message = ($cap["message"]);
            $focus_to = ('project_id');
            return array("success" => false, "focus_to" => $focus_to, "message" => $message);
        }
    
    if (! (in_array($batch['approval_status'], array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_BACK_TO_ORIGINATOR)))) {
        $message = ( _("This ".$systypes_array[ST_I_OWE_YOU_BATCH]." status does not allow any changes to its details."));
        $focus_to = ('batch_task');
        return array("success" => false, "focus_to" => $focus_to, "message" => $message);
    }
    
    $ced = can_edit_document(ST_I_OWE_YOU_BATCH, $project_id, $batch['next_approval_group_id'], $user_id, $batch['created_by'], $batch['batch_no']);  
        if($ced['success'] !== true) {
            $message = ($ced["message"]);
            $focus_to = ('project_id');
            return array("success" => false, "focus_to" => $focus_to, "message" => $message);
        }
    
    $batch_result = get_batch_i_owe_you_expences($batch_no);
        if (db_num_rows($batch_result) > 0) {
            return array("success" => false, 
                         "message" => "This ".$systypes_array[ST_I_OWE_YOU_BATCH]." has expense details. Please delete all expense details first.");
        }
    
    return array("success" => true, "message" => "", "row_state" => $batch['row_state']);
}


function handle_delete_i_owe_you_batch($batch_no){
    global $systypes_array;
    
    $msg = can_delete_expense_batch($batch_no);
        if ($msg['success'] !== true) {
            return $msg;
        }
        
    $batch_row_state = $msg['row_state'];
    
    begin_transaction();
        $result = get_batch_i_owe_yous($batch_no);
            while ($row = db_fetch($result)) {
                
                $iou_no = $row['id'];
                $n_af = update_remove_i_owe_you_from_batch_no($iou_no, $row['row_state'], $batch_no);
                    if ($n_af !== 1) {
                        cancel_transaction();
                        return array('success' => false, 'message' => _("Another user has updated ".$systypes_array[ST_I_OWE_YOU]." #$iou_no."));
                    }
            }
            
            $naf_row = delete_i_owe_you_batch_header($batch_no, $batch_row_state);
                if ($naf_row !== 1) {
                    cancel_transaction();
                    return array('success' => false, 'message' => _("Another user has updated ".$systypes_array[ST_I_OWE_YOU_BATCH]." #$batch_no."));
                }
            
    commit_transaction();
    
        return array('success' => true, 'message' => _($systypes_array[ST_I_OWE_YOU_BATCH]." #$batch_no has been deleted."));
}

function complete_i_owe_you_batch_with_no_expenses($batch_no){
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $expences = get_batch_i_owe_you_expences($batch_no);
    $iou_batch_task_costs_summary = array();
    $batch_expences_count = 0;
    
    while ($myrow = db_fetch($expences))
    {
//        $a['row_id'] = $myrow['id'];
//        $a['task_id'] = $myrow['task_id'];
//        $a['amount'] = $myrow['amount'];
//        $task_costs_summary[] = $a;
     
        add_to_task_cost($iou_batch_task_costs_summary, $myrow['task_id'], $myrow['approved_amount'], $myrow['approved_amount'], $myrow['approved_amount']);
        
        $batch_expences_count++;
    }
        
    get_task_cost_details($iou_batch_task_costs_summary);
    
//    $task_costs_summary = calculate_task_remaining_totals($mr_details_array);
    
    begin_transaction();
    
    $batch = get_i_owe_you_batch_header($batch_no);

//    add_to_task_cost($task_costs_summary, $iou['task_id'], $iou['amount'], $iou['amount'], $iou['amount']);
    
    $info = approve_document(ST_I_OWE_YOU_BATCH, $batch_no, $batch['project_id'], $iou_batch_task_costs_summary, 
                                        $batch['next_approval_group_id'], $current_user_id, $batch['row_state'], $batch['created_by']);
    
    update_document_approval_status($info);
    
    if($info['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $info['success'],"tran_no" => $batch_no, "message" => $info['message']);
    }

    if($info['approval_status'] == AS_APPROVED)
    {            
        $rbta_msg = remove_iou_batch_iou_task_allocations($batch_no, $current_user_id);
        if($rbta_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $rbta_msg['success'], "tran_no" => $batch_no, "message" => $rbta_msg['message']);
        }
        
        // Refresh task total bdget details of the batch including row_state
        get_task_cost_details($iou_batch_task_costs_summary);
        
        $cct_msg = charge_cost_to_tasks(ST_I_OWE_YOU_BATCH, $batch_no, 
                        $iou_batch_task_costs_summary, $current_user_id);

        if($cct_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $cct_msg['success'], "tran_no" => $batch_no, "message" => $cct_msg['message']);
        }
        
        $n = update_batch_expences_approved($batch_no);
        if($batch_expences_count != $n){
            cancel_transaction();
            return array("success" => $cct_msg['success'], "tran_no" => $batch_no, "message" => "Another user has updated some of the  records");
        }
    }
    
    
//    $cioub = close_i_owe_you_batch($batch_no, $row_state);
//    if($cioub['success'] !== true)
//    {
//        cancel_transaction();
//        return $cioub;
//    }
//    
    commit_transaction();
    return array("success" => true, "tran_no" => $batch_no, "message" => $info['message']);
}


function display_project_float_message($project_id, $company_code, $employee_code)
{
    if($project_id > 0 ){
        $project_float = get_project_float_by_project_id($project_id);
        if($project_float && $project_float['inactive'] == 0){
            if($company_code == $project_float['company_code'] && $employee_code == $project_float['employee_code']){
                display_note("This transaction will be written to the Project Float of this project.");
            }                           
            else{
                $m = "Selected employee is different to the Project Float owner "
                            .get_group_company_employee_formatted_long_name($project_float['company_code'], $project_float['employee_code'])
                            .". This transaction will be created outside the Project Float of this project.";
                display_note("<font color='red'>$m</font>");
            }
        }
        else{
            display_note("No active Project Float found for the selected project.");
        }
    }
}

function can_delete_iou_expense($selected_id)
{	
    $ex = get_i_owe_you_expence_line($selected_id);
    switch ($ex['expense_category_id']) {
        case EC_STOCK_ITEM_RECEIPT:
//            $result = get_petty_cash_item_receive_items(ST_PETTY_CASH_ITEM_RECEIPT, $ex['iou_batch_no'], $selected_id);
            $result = get_petty_cash_item_receive_items_by_source_type(ST_I_OWE_YOU_BATCH, $ex['id']);
            if(db_fetch($result) > 0)
            {     
                $msg = "Line id ".$selected_id." : This line can not be deleted. It has petty cash stock item receipts associated with it.";                    
                set_focus('amount');
                return array("success" => false, "message" => $msg);
            }

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