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


function process_delete_fi_batch($fi_batch_no)
{
    $fi_batch = get_fi_batch_header_record($fi_batch_no);
    
    $row_state = $fi_batch['row_state'];
    
    $cdfib_msg = can_delete_fi_batch($fi_batch);
    if($cdfib_msg['success'] !== true){
        display_error($cdfib_msg['message']);
        return;
    }

    begin_transaction();

    delete_fi_accounting_entries($fi_batch_no);
    reopen_fi_batch_source_transactions($fi_batch_no);
    
    reopen_all_group_company_source_transactions($fi_batch_no);
    
    delete_fi_batch_transactions($fi_batch_no);
    
    $count = get_fi_batch_processed_entries_count($fi_batch_no);
    if($count > 0){
        $message = ("This FI batch is being processed. It can not be deleted.");
        display_error_cancel($message);
        return;  
    }
    
    $n = delete_fi_batch_header_record($fi_batch_no, $row_state);
    if($n != 1){
        $message = ("This FI batch has been updated by another user.");
        display_error_cancel($message);
        return;  
    }
    
    commit_transaction();
    
//    display_notification("All accounting entries of FI Batch $fi_batch_no has been deleted.");;
    
    meta_forward($_SERVER['PHP_SELF'], "did=$fi_batch_no");

    
}

function can_delete_fi_batch($fi_batch)
{
    if($fi_batch['gl_batch_no'] > 0){
        $message = ("This FI batch has been posted already. It can not be deleted when there are gl transactions.");
        return array("success" => false, "message" => $message);    
    }
    
    $count = get_fi_batch_processed_entries_count($fi_batch['id']);
    if($count > 0){
        $message = ("This FI batch has posted accounting entries. It can not be deleted when there are gl transactions.");
        return array("success" => false, "message" => $message);    
    }
    
    return array("success" => true, "message" => '');    
    
}

function reopen_all_group_company_source_transactions($fi_batch_no)
{
    
    $db_SAW = get_group_company_db_name('SAW');
    if(strlen($db_SAW) > 1){
        reopen_group_company_source_transactions($db_SAW, $fi_batch_no);
    }
    
    $db_SAWC = get_group_company_db_name('SAWC');
    if(strlen($db_SAWC) > 1){
        reopen_group_company_source_transactions($db_SAWC, $fi_batch_no);
    }
    
    $db_VEE = get_group_company_db_name('VEE');
    if(strlen($db_VEE) > 1){
        reopen_group_company_source_transactions($db_VEE, $fi_batch_no);
    }
    
    $db_VEEC = get_group_company_db_name('VEEC');
    if(strlen($db_VEEC) > 1){
        reopen_group_company_source_transactions($db_VEEC, $fi_batch_no);
    }
    
    $db_LPS = get_group_company_db_name('LPS');
    if(strlen($db_LPS) > 1){
        reopen_group_company_source_transactions($db_LPS, $fi_batch_no);
    }
    
}

    