<?php

function display_float_to_bank_transfer($trans_type, $trans_no) { 
    global $Refs, $document_approval_statuses;
    
    $approval_status = 0;
    if ($trans_no > 0) {
        $row = petty_cash_float_adjustments_header($trans_type, $trans_no);
        set_post_not_set_string('reference', $row['reference']);
        set_post_not_set_numeric('float_id',$row['float_id']);
        set_post_not_set_numeric('to_float_id',$row['to_float_id']);
        set_post_not_set_date('tran_date', sql2date($row['tran_date']));
        set_post_not_set_numeric('amount', abs($row['amount']));            
        set_post_not_set_string('comment', $row['comment']);
        
        $approval_status = $row['approval_status'];
    } else {
        set_post_not_set_string('reference', $Refs->get_next($trans_type));
    }

    start_table(TABLESTYLE2);
        if ($trans_no > 0) {
            label_row(_("Transaction no.:"), $trans_no); 
            hidden('trans_no', $trans_no);
        }
        ref_row(_("Reference:"), 'reference'); 
        date_row("Date:", "tran_date");    
        petty_cash_floats_list_row('From Float:', 'float_id', null, '', false);
//        petty_cash_floats_list_row('To Float:', 'to_float_id', null, '', false);
        bank_accounts_list_row('To Bank Account:', 'bank_account_id', null, false, "");
        amount_row('Amount:', 'amount', null, null, null, 2);
        textarea_row("Comment:", "comment", null, 30,3);
        label_row('Approval Status:', $document_approval_statuses[$approval_status]);
    end_table(1);
}

function check_float_transfer_data($trans_type, $trans_no) {    
    if ($trans_no > 0) {
        $row = petty_cash_float_adjustments_header($trans_type, $trans_no);
            if (! (isset($row['id']) && $row['id'] > 0)) {
                return array("success" => false, "set_focus" => '', "message" => "Could not find Float transfer trans #$trans_no.");
            } elseif ($row['approval_status'] == AS_APPROVED) {
                return array("success" => false, "set_focus" => '', "message" => "Approval status of Float transfer trans #$trans_no is already processed.");
            }
    }
    
    if (strlen($_POST['reference']) == 0) {
        $message = "Reference is mandatory.";
        $set_focus = 'reference';
        return array("success" => false, "set_focus" => $set_focus, "message" => $message);
    }
    
    $refm = reference_exists($_POST['reference'], $trans_type, $trans_no);
        if ($refm != "") {
            $message = ( _($refm));
            $set_focus = ('ref');
            return array("success" => false, "set_focus" => $set_focus, "message" => $message);
        }
   
    if (! is_date($_POST['tran_date'])) {       
        $message = "Entered date is not a valid date.";
        $set_focus = 'tran_date';
        return array("success" => false, "set_focus" => $set_focus, "message" => $message);
    }        
    
    if ($_POST['float_id'] == '-1') {            
        $message = "Please select a from float.";
        $set_focus = 'float_id';
        return array("success" => false, "set_focus" => $set_focus, "message" => $message);
    }  
    
    if (!($_POST['bank_account_id'] > 0)) {            
        $message = "Please select to bank account.";
        $set_focus = 'bank_account_id';
        return array("success" => false, "set_focus" => $set_focus, "message" => $message);
    }   
    
    if (!is_date_in_fiscalyear($_POST['tran_date'])) {
        $message = (_("The entered invoice date is not in fiscal year."));
        $set_focus = ('tran_date');
        return array("success"=>false, "set_focus"=>$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, "set_focus"=>$set_focus, "message"=>$message);
    }
        
    if (! check_num('amount', 0.001)) {            
        $message = "Amount entered should be greater than zero.";
        $set_focus = 'amount';
        return array("success" => false, "set_focus" => $set_focus, "message" => $message);
    } 
    
    $denominations_total = calculate_denominations_total($trans_type, $trans_no);
    $amount = input_num('amount');
    if(abs($amount - $denominations_total) > FLOAT_COMP_DELTA ) 
    {
        $message = "Entered amount (". number_format($amount,2).") and the denominations total (". number_format($denominations_total,2).") do not natch.";
        $set_focus = ('amount'); 
        return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message); 
    }
    
    return array("success" => true, "message" => "");        
}

function save_float_to_bank_transfer($trans_type, &$trans_no, $process) {
    $cd = check_float_transfer_data($trans_type, $trans_no);
        if ($cd["success"] !== true) {
            set_focus($cd["set_focus"]);  
            display_error($cd["message"]);
            return;
        }

        if ($trans_no > 0) {
            handle_modify_foat_transfer($trans_type, $trans_no, $process);
        } else {
            handle_add_foat_transfer($trans_type, $trans_no, $process);
        }
}

function handle_add_foat_transfer($trans_type, &$trans_no, $process) {
    
    begin_transaction();
    
    $apcf_msg = add_float_transfer($trans_type, $trans_no, $process);
    if($apcf_msg["success"] !== true){
        cancel_transaction();
        display_error($apcf_msg["message"]);
        return;
    }
        
    $result = get_petty_cash_transaction_currency_denominations($trans_type, $trans_no);    
    while ($row = db_fetch($result)) {
        $prefix = $row['value_code'].'_';
        if(isset($_POST[$prefix.'quantity']) && $_POST[$prefix.'quantity'] > 0){
            $quantity = input_num($prefix.'quantity');
            $denomination_id = $row['id'];
            
            add_petty_cash_transaction_currency_denominations($trans_type, $trans_no, $denomination_id, $quantity);
        } 
    }
        
    commit_transaction();
    
    $trans_no = $apcf_msg["trans_no"]; 
    $id_name = $process==true?"Processed_Id":"Added_ID";
    meta_forward($_SERVER['PHP_SELF'], $id_name."=".$apcf_msg["trans_no"]);
    return;        
}

function handle_modify_foat_transfer($trans_type, &$trans_no, $process) {
    begin_transaction();
    
    $apcf_msg = update_foat_transfer($trans_type, $trans_no, $process);
    if($apcf_msg["success"] !== true){
        cancel_transaction();
        display_error($apcf_msg["message"]);
        return;
    }            
                
    delete_petty_cash_transaction_currency_denominations($trans_type, $trans_no);
    
    $result = get_petty_cash_transaction_currency_denominations($trans_type, $trans_no);    
    while ($row = db_fetch($result)) {
        $prefix = $row['value_code'].'_';
        if(isset($_POST[$prefix.'quantity']) && $_POST[$prefix.'quantity'] > 0){
            $quantity = input_num($prefix.'quantity');
            $denomination_id = $row['id'];
            
            add_petty_cash_transaction_currency_denominations($trans_type, $trans_no, $denomination_id, $quantity);
        } 
    }
    
    commit_transaction();
    
    $trans_no = $apcf_msg["trans_no"];
    $id_name = $process==true?"Processed_Id":"Updated_ID";
    meta_forward($_SERVER['PHP_SELF'], $id_name."=".$apcf_msg["trans_no"]); 
    return;
        
}

function add_float_transfer($trans_type, &$trans_no, $process) {   
    global $Refs, $systypes_array; 
     
    $amount = input_num('amount');
    
    $trans_no = get_next_trans_no($trans_type);
    $rec_id = add_petty_cash_float_adjustment($_POST['reference'], 0, $_POST['float_id'], $_POST['tran_date'], -$amount, $_POST['comment'], $trans_type, $trans_no, -1, 0, 
                                              0, $_POST['bank_account_id']);
    
        if (! ($rec_id > 0)) {  
            $m = ($systypes_array[$trans_type]." could not be added.");
            return array("success"=>false, "trans_no"=>0, "message"=>$m); 
        } else {
            hidden('trans_no', $trans_no);
            $_POST['trans_no'] = $trans_no;
        }

    if ($process) {
        $ppcfp_msg = process_foat_transfer($trans_type, $trans_no, $_POST['float_id'], $_POST['to_float_id'], $amount, $_POST['tran_date']);
            if ($ppcfp_msg["success"] !== true) { 
                return array("success"=>false, "trans_no"=>0, "message"=>$ppcfp_msg["message"]); 
            }
    }
    
    $Refs->save($trans_type, $trans_no, $_POST['reference']); 
    return array("success" => true, "trans_no" => $trans_no, "message" => '');
}

function update_foat_transfer($trans_type, $trans_no, $process) {   
    global $Refs, $systypes_array;
    
    $amount = input_num('amount');
    $is_return = 0;

    
    $n = update_petty_cash_float_adjustment($_POST['reference'], $is_return, $_POST['float_id'], $_POST['tran_date'], -abs($amount), $_POST['comment'], $trans_type, $trans_no, 
                                            0, $_POST['bank_account_id']);
    
    if ($process) {
        $ppcfp_msg = process_foat_transfer($trans_type, $trans_no, $_POST['float_id'], $_POST['to_float_id'], $amount, $_POST['tran_date']);
            if ($ppcfp_msg["success"] !== true) { 
                return array("success" => false, "trans_no" =>0, "message" => $ppcfp_msg["message"]); 
            }
    }

    $Refs->save($trans_type, $trans_no, $_POST['reference']); 
    return array("success"=>true, "trans_no"=>$trans_no, "message"=>'');
}

function process_foat_transfer($trans_type, $trans_no, $float_id, $to_float_id, $amount, $tran_date_) {
    global $systypes_array;
        
    $trans = get_petty_cash_float_trans_record($float_id, $trans_type, $trans_no);
        if (isset($trans['id']) && $trans['id'] > 0) {
            $m = $systypes_array[$trans_type]." #".$trans_no." has been processed already.";
            return array("success" => false, "trans_no" => $trans_no, "message" => $m);            
        }
        
        $in_id = add_to_petty_cash_float($trans_type, $trans_no, $float_id, $amount*-1, $tran_date_); 
            if (! ($in_id > 0)) {
                $m = $systypes_array[$trans_type]." #".$trans_no." could not process.";
                return array("success" => false, "trans_no" => $trans_no, "message" => $m);            
            }
        
        $in_id_2 = add_to_petty_cash_float($trans_type, $trans_no, $to_float_id, $amount, $tran_date_);        
            if (! ($in_id_2 > 0)) {
                $m = $systypes_array[$trans_type]." #".$trans_no." could not process.";
                return array("success" => false, "trans_no" => $trans_no, "message" => $m);            
            }
        
        $n = update_petty_cash_float_adjustment_approved($trans_type, $trans_no); 
            if ($n != 1) {
                return array("success" => false, "message" => "Another user has updated ".$systypes_array[$trans_type]." #".$trans_no);
            }
     
        return array("success" => true, "trans_no" => $trans_no, "message" => '');
}

function display_float_to_bank_transfer_details($type_id, $type_no)
{ 
    start_table(TABLESTYLE2, 'width=20%');    
    
    $th = array(_("Denomination"),_("Quantity"), "Amount");
    table_header($th);
    
    $total = 0;
    $result = get_petty_cash_transaction_currency_denominations($type_id, $type_no);    
    while ($row = db_fetch($result)) {
        $prefix = $row['value_code'].'_';
        if(isset($_POST[$prefix.'quantity']) && $_POST[$prefix.'quantity'] > 0){
            $v = input_num($prefix.'quantity');
        }else{
            $v = $row['quantity'];
        }
            
        $_POST[$prefix.'quantity'] = $v;
        
        start_row();
            label_cell($row['value_name'].spaces(5), 'align=right');
            amount_cells(null, $prefix.'quantity', null, null, null, 0);
            $denomination_value = (int)$row['value_code'];
            $quantity = input_num($prefix.'quantity');
            $line_total =  $denomination_value * $quantity;
            label_cell(number_format($line_total, 2), 'align=right');
        end_row();
        
        $total += $line_total;
    }
    
    start_row();
        label_cell("Total", 'align=right colspan=2'); 
        label_cell(number_format($total, 2), 'align=right');
    end_row();    
    
    end_table();
    
}



function calculate_denominations_total($trans_type, $trans_no)
{ 

    $total = 0;
    $result = get_petty_cash_transaction_currency_denominations($trans_type, $trans_no);    
    while ($row = db_fetch($result)) {
        $prefix = $row['value_code'].'_';
        if(isset($_POST[$prefix.'quantity']) && $_POST[$prefix.'quantity'] > 0){
            $v = input_num($prefix.'quantity');
        }else{
            $v = 0;
        }

        $denomination_value = (int)$row['value_code']; 
        $line_total =  $denomination_value * $v;  
        
        $total += $line_total;
    }
     
    return $total;
}