<?php


function display_fi_batches($tran_date_)
{
    global $systypes_array;
    
    $tran_date = date2sql($tran_date_);
    display_heading("FI Batches");
    
    $result = get_unposted_fi_batches($tran_date);
    
    start_table(TABLESTYLE, "width=70%");
    
    $th = array(_('FI Batch No'),_('Cutoff Date'), _('Transaction Type'),_('Created By'),_('Created On'), _('Transaction Count'), _('Select'));              

    table_header($th);    
    
    $k = 0;
    while($row = db_fetch($result)){
        alt_table_row_color($k);
            $link = get_journal_trans_view_str(ST_FI_BATCH, $row['id']);
            label_cell($link, "align=center");  
            label_cell($row['cutoff_date'], 'align=center');
            
            if($row['trans_type'] > 0){
                $type_name = $systypes_array[$row['trans_type']];
            }
            else{
                $type_name = "Multiple Transaction Types";
            }
            label_cell($type_name);
            label_cell($row['user_name'], 'align=center');
            label_cell($row['created_on'], 'align=center');
            
            $transaction_count = get_fi_batch_transaction_count($row['id']);
            label_cell($transaction_count, 'align=center');
            
            check_cells(null, 'select_fib_'.$row['id'], null, true, false, 'align=center');
        end_row();
    }

    end_table(2);
}

function build_selected_fi_batches_array($tran_date, &$ids, &$details=array(), &$types=array())
{
    
    
    $result = get_unposted_fi_batches($tran_date);
    while($row = db_fetch($result)){
        if(isset($_POST['select_fib_'.$row['id']]) && $_POST['select_fib_'.$row['id']] == 1){
            $ids[]= $row['id'];
            
            $line = array("id"=>$row['id'], "row_state"=>$row['row_state']);
            $details[] = $line;
            
            $types[]= $row['trans_type'];
        }
    }
    
    $ids[]= -999999;
    

}

function display_fi_batch_accounts_summary($tran_date_)
{
    global $systypes_array;
    
    display_heading("Accounts Summary");
    
//    $a = array();
    $ids = array();
    $details = array();
    $types = array();
    $tran_date = date2sql($tran_date_);
    build_selected_fi_batches_array($tran_date, $ids, $details, $types);
    
    $types = array_unique($types);
    if(count($types) > 1){
        $warning = "Please select ".$systypes_array[ST_FI_BATCH]."es of the same transaction type.<br>";
        $warning .= "That will create a separate ".$systypes_array[ST_GL_BATCH]." for the selected transaction type.";
        display_error($warning);
    }
    
//    return;
    $result = get_unposted_fi_accounts_summary($ids);
    
    start_table(TABLESTYLE, "width=60%");
    
    $th = array(_('Account'), _('Project'), _('Records'), _('Debit'),  _('Credit'));              

    table_header($th);    
    
    $k = $total_debits = $total_credits = 0;
//    $acc_summary_array = array();
    
    while($row = db_fetch($result)){
        alt_table_row_color($k);
            $account_name = $row['account']." - ".$row['account_name'];
            label_cell($account_name);
            
            $project_text = get_project_formatted_code($row['project_id'], $row['project_code']); 
            label_cell($project_text, "align=center");
            
            label_cell($row['records_count'], "align=center");
            
            
            $debit = $credit = 0;
            
            if($row['total'] > 0){
                $debit = round($row['total'],2);
                label_cell(number_format($debit,2), 'align=right'); 
                label_cell('');
                
                $total_debits += $debit;
            }
            else{
                $credit = -round($row['total'],2);
                label_cell('');
                label_cell(number_format($credit,2), 'align=right'); 
                
                $total_credits += $credit;
                
            }
            
            $line = array("account" => $row['account'],
                            "debit" => $debit,
                            "credit" => $credit);
            
//            $acc_summary_array[] = $line;
        end_row();
    }

    start_row();
    label_cell(text_bold("Total"), 'colspan=3 align=right'); 
    label_cell(text_bold(number_format($total_debits,2)), 'align=right'); 
    label_cell(text_bold(number_format($total_credits,2)), 'align=right'); 
    end_row();
    end_table(2);
    
//    $total_credits += 10;
    
    if(abs($total_debits) > 0 || abs($total_credits) > 0){
        if(abs(abs($total_debits) - abs($total_credits)) > 0.0001){
            $m = "Total debits and total credits do not match. Please contact system administrator.";
            display_note("<font color='red'>".text_bold($m)."</font>");
        }
        else{
            submit_center_first('PostFIAccountingEntries', _("Post Selected Batches"), '', 'process');
        }
        
    }
    
    if($total_debits - $total_credits){
        
    }

}


function can_post_fi_accounting_entries($ids_array, $types_array)
{
    global $systypes_array;
    
    $types = array_unique($types_array);
    if(count($types) > 1){
        $message = "Please select ".$systypes_array[ST_FI_BATCH]."es of the same transaction type.<br>";
        $set_focus = "";
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!(is_date($_POST['tran_date']))){
        $message = ("Transaction date is not a valid date.");
        $set_focus = "tran_date";
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
    
    if(!(is_date($_POST['confirm_tran_date']))){
        $message = ("Re-entered transaction date is not a valid date.");
        $set_focus = "confirm_tran_date";
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
    
    if($_POST['confirm_tran_date'] != $_POST['tran_date']){
        $message = ("Transaction date and re-entered transaction date do not match.");
        $set_focus = "confirm_tran_date";
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
    
    if(!(is_date_in_fiscalyear($_POST['tran_date']))){
        $message = ("The entered date is not in fiscal year.");
        $set_focus = "tran_date";
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
    
    $fiscalyear = get_fiscalyear_record_by_from_date_to_date($_POST['tran_date'], $_POST['tran_date']);
    $msg = check_fi_transactions_outside_fiscal_year($fiscalyear['begin'], $fiscalyear['end'], $ids_array);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']);
        $set_focus = "";
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    $msg = is_accounting_period_open($_POST['tran_date']);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']);
        $set_focus = "tran_date";
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    return array("success" => true, "message" => '');    
    
}


function post_fi_accounting_entries($tran_date_)
{
    global $systypes_array;
    
    $tran_date = date2sql($tran_date_);
    
    $ids = array();
    $details = array();
    $types = array();
    build_selected_fi_batches_array($tran_date, $ids, $details, $types);
    
    $cpfi_msg = can_post_fi_accounting_entries($ids, $types);
    if($cpfi_msg['success'] !== true){
        display_error($cpfi_msg['message']);
        set_focus($cpfi_msg['focus_to']);
        return;
    }
    
//    return;
    
    set_global_gl_batch_date($tran_date_);
//    sleep(20);
    begin_transaction();
    
//    $tran_date_ = $_POST['tran_date'];
    
    $types = array_unique($types);
    if(count($types) > 1){
        $memo_ = "Multiple Transaction Types";
        $gl_batch_type = ST_GL_BATCH;
    }
    elseif(count($types) == 1){
        $memo_ = $systypes_array[$types[0]];
        $gl_batch_type = $types[0] + 1000;
    }
    else{
        $memo_ = "";
        $gl_batch_type = -99;
    }
    
    if(!array_key_exists($gl_batch_type,$systypes_array)){
        display_error("GL Batch transaction type ".$gl_batch_type." not defined");
        set_focus($cpfi_msg['focus_to']);
        return;
    }
    
//    $result = get_unposted_fi_accounts_summary($ids);  
    
    $gl_batch_no = create_next_gl_batch_no($gl_batch_type, $tran_date_);

    foreach ($ids as $fi_batch_no) {
        
        $res_fi_trans_h = get_fi_batch_transactions($fi_batch_no);   
        while($fi_trans_h = db_fetch($res_fi_trans_h)){            
            $type = $fi_trans_h["type"];
            $type_no = $fi_trans_h["type_no"];
            $tran_date = $fi_trans_h["tran_date"];
            
            $total_debits = $total_credits = 0;
            
            $error_prefix = $systypes_array[$type]." #".$type_no." : ";
            if (!is_date_in_fiscalyear($tran_date, true)) {
                cancel_transaction();
                display_error(_($error_prefix."The entered date is not in fiscal year.")); 
                return;
            }

            $msg = is_accounting_period_open($tran_date, true);
            if ($msg['success'] !== true)
            {
                cancel_transaction();
                display_error($error_prefix.$msg['message']); 
                return;
            }
            
            $res_fi_trans_d = get_fi_transaction($fi_batch_no, $type, $type_no);
            while($row = db_fetch($res_fi_trans_d)){

                $fi_counter = $row['counter'];
                $account = $row['account'];
                $amount = $row['amount'];
                $fi_trans_date = $row['tran_date'];
                $project_id = $row['dimension_id'];
                $person_type_id = $row['person_type_id'];
                $person_id = $row['person_id'];
                
                $fi_trans_date_ = sql2date($fi_trans_date);

                $debit = $credit = 0;            
                if($amount > 0){
                    $debit = round($amount,2);                
                    $total_debits += $debit;
                }
                else{
                    $credit = -round($amount,2);
                    $total_credits += $credit;
                }
                
                $person_name = "";
                switch ($person_id) {
                    case PT_CUSTOMER:
                        $person_name = get_customer_formatted_name($person_id);
                        break;
                    case PT_SUPPLIER:
                        $person_name = get_supplier_formatted_name($person_id);
                        break;
                    case PT_EMPLOYEE:
                        $person_name = get_employee_formatted_long_name_by_id($person_id);
                        break;
                    case PT_FLOAT:
                        $person_name = get_float_formatted_name($person_id);
                        break; 

                    default:
                        break;
                }

                add_gl_trans($type, $type_no, $fi_trans_date_, $account, $project_id, 0, $memo_, $amount,
                        null, $person_type_id, $person_id);

                $gl_counter = db_insert_id();
 
                update_fi_trans_record_gl_counter($fi_counter, $gl_counter, $gl_batch_no);


            }
//            if(abs(abs($total_debits) - abs($total_credits)) > 0.0001){
//                cancel_transaction();
//                $m = "Total debits and total credits do not match in the transaction ".$systypes_array[$type]." #".$type_no.". This batch posting is cancelled. Please contact system administrator.";
//                display_error($m);
//                return;
//            }
            $gl_trans_balance = get_gl_transaction_balance($type, $type_no);
            if(abs($gl_trans_balance) > 0.0001){
                cancel_transaction();
                $m = "Total debits and total credits do not match in the transaction ".$systypes_array[$type]." #".$type_no.". This batch posting is cancelled. Please contact system administrator.";
                display_error($m);
                return;
            }
            
            add_audit_trail($type, $type_no, $fi_trans_date_);
            
        }
    }

    $unposted_count = get_gl_batch_unposted_fi_transactions_count($ids);
    if($unposted_count != 0){
        cancel_transaction();
        $m = "There are $unposted_count lines not posted. This batch posting is cancelled. Please contact system administrator.";
        display_error($m);
        return;
    }
    
    
    foreach ($details as $value) {
        $n = update_fi_batch_posted($value['id'], $value['row_state'], $gl_batch_no);
        if($n != 1){
            cancel_transaction();
            $message = ("Another user has updated FI Batch # ".$value['id']);
            display_error($message);
            return;
        }
    }

    commit_transaction();
    
    unset($_POST['confirm_tran_date']);
    
//    meta_forward($_SERVER['PHP_SELF'], "glb=$gl_batch_no");
    
}

function post_fi_accounting_entries_as_gl_batches($tran_date_)
{
    global $systypes_array;
    
    $tran_date = date2sql($tran_date_);
    
    $ids = array();
    $details = array();
    $types = array();
    build_selected_fi_batches_array($tran_date, $ids, $details, $types);
    
    $cpfi_msg = can_post_fi_accounting_entries($ids, $types);
    if($cpfi_msg['success'] !== true){
        display_error($cpfi_msg['message']);
        set_focus($cpfi_msg['focus_to']);
        return;
    }
    
//    return;
    
    set_global_gl_batch_date($tran_date_);
//    sleep(20);
    begin_transaction();
    
//    $tran_date_ = $_POST['tran_date'];
    
    $types = array_unique($types);
    if(count($types) > 1){
        $memo_ = "Multiple Transaction Types";
        $gl_batch_type = ST_GL_BATCH;
    }
    elseif(count($types) == 1){
        $memo_ = $systypes_array[$types[0]];
        $gl_batch_type = $types[0] + 1000;
    }
    else{
        $memo_ = "";
        $gl_batch_type = -99;
    }
    
    if(!array_key_exists($gl_batch_type,$systypes_array)){
        display_error("GL Batch transaction type ".$gl_batch_type." not defined");
        set_focus($cpfi_msg['focus_to']);
        return;
    }
    
    $result = get_unposted_fi_accounts_summary($ids);  
    
    $total_debits = $total_credits = $project_id = 0;
    
    $gl_batch_no = create_next_gl_batch_no($gl_batch_type, $tran_date_);

    while($row = db_fetch($result)){

        $account = $row['account'];
        $amount = $row['total'];
        $project_id = $row['project_id'];

        $debit = $credit = 0;            
        if($row['total'] > 0){
            $debit = round($row['total'],2);                
            $total_debits += $debit;
        }
        else{
            $credit = -round($row['total'],2);
            $total_credits += $credit;

        }
        
        add_gl_trans($gl_batch_type, $gl_batch_no, $tran_date_, $account, $project_id, 0, $memo_, $amount); 
        
        $gl_counter = db_insert_id();
         
        update_fi_trans_gl_counter($ids, $account, $project_id, $gl_counter, $gl_batch_no);


    }
    

    if(abs(abs($total_debits) - abs($total_credits)) > 0.0001){
        cancel_transaction();
        $m = "Total debits and total credits do not match. This batch posting is cancelled. Please contact system administrator.";
        display_error($m);
        return;
    }
        
    $gl_batch_balance = get_gl_batch_balance($gl_batch_no);
    if(abs($gl_batch_balance) > 0.0001){
        cancel_transaction();
        $m = "Total debits and total credits in the database do not match . This batch posting is cancelled. Please contact system administrator.";
        display_error($m);
        return;
    }
    
    $unposted_count = get_gl_batch_unposted_fi_transactions_count($ids);
    if($unposted_count != 0){
        cancel_transaction();
        $m = "There are $unposted_count lines not posted. This batch posting is cancelled. Please contact system administrator.";
        display_error($m);
        return;
    }
    
    add_audit_trail($gl_batch_type, $gl_batch_no, $tran_date_);
    
    foreach ($details as $value) {
        $n = update_fi_batch_posted($value['id'], $value['row_state'], $gl_batch_no);
        if($n != 1){
            cancel_transaction();
            $message = ("Another user has updated FI Batch # ".$value['id']);
            display_error($message);
            return;
        }
    }

    commit_transaction();
    
    unset($_POST['confirm_tran_date']);
    
    meta_forward($_SERVER['PHP_SELF'], "glb=$gl_batch_no");
    
}