<?php



function check_petty_cash_float_payment_data($trans_type, $trans_no)
{      
    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(!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);
    }  
    
    if($_POST['float_id'] == '-1'){            
        $message = "Please select a Petty cash float.";
        $set_focus = 'float_id';
        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 (!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);
    }
    
    $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_petty_cash_float_payment($trans_type, &$trans_no, $process)
{
    $cd = check_petty_cash_float_payment_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_petty_cash_float_payment($trans_type, $trans_no, $process);
    }else{
        handle_add_petty_cash_float_payment($trans_type, $trans_no, $process);
    }
}

function handle_add_petty_cash_float_payment($trans_type, &$trans_no, $process)
{
    begin_transaction();
    $apcf_msg = add_petty_cash_float_payment($trans_type, $trans_no, $process);
    if($apcf_msg["success"] !== true){
        cancel_transaction();
        display_error($apcf_msg["message"]);
        return;
    }else{
        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_petty_cash_float_payment($trans_type, &$trans_no, $process)
{
    begin_transaction();
    $apcf_msg = update_petty_cash_float_payment($trans_type, $trans_no, $process);
    if($apcf_msg["success"] !== true){
        cancel_transaction();
        display_error($apcf_msg["message"]);
        return;
    }else{
        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_petty_cash_float_payment($trans_type, &$trans_no, $process)
{   
    global $Refs, $systypes_array; 
     
    $amount = input_num('amount');
    if($trans_type == ST_FLOAT_PAYMENT){
        $is_return = 1;
        $amount *= -1;
    }else{
        $is_return = 0;
    }    
    
    $trans_no = get_next_trans_no($trans_type);
    $rec_id = add_petty_cash_float_adjustment($_POST['reference'], $is_return,$_POST['float_id'], $_POST['tran_date'], $amount, $_POST['comment'],
                                                $trans_type, $trans_no);
    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;
    }
    
    $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);
        } 
    }
    
    if($process){
        $ppcfp_msg = process_petty_cash_float_payment($trans_type, $trans_no, $_POST['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_petty_cash_float_payment($trans_type, $trans_no, $process)
{   
    global $Refs, $systypes_array;
    
    $amount = input_num('amount');
    if($trans_type == ST_FLOAT_PAYMENT){
        $is_return = 1;
        $amount *= -1;
    }else{
        $is_return = 0;
    }   

    $n = update_petty_cash_float_adjustment($_POST['reference'], $is_return, $_POST['float_id'], $_POST['tran_date'], $amount, $_POST['comment'],
                                                $trans_type, $trans_no);
    if($n != 1){  
        $m = ($systypes_array[$trans_type]." could not be updated.");
        return array("success"=>false, "trans_no"=>0, "message"=>$m); 
    }
    
    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);
        } 
    }
    
    if($process){
        $ppcfp_msg = process_petty_cash_float_payment($trans_type, $trans_no, $_POST['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_petty_cash_float_payment($trans_type, $trans_no, $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);            
        }
        
        add_to_petty_cash_float($trans_type, $trans_no, $float_id, $amount, $tran_date_);        
        
        $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_petty_cash_float_payment_header($trans_type, $trans_no)
{ 
    global $Refs;
    
    if($trans_no > 0){
        $pcfph_row = petty_cash_float_adjustments_header($trans_type, $trans_no);
//        $_POST['id'] = 0;
//        $_POST['reference'] = "";
//        $_POST['float_id'] = ""; 
//        $_POST['tran_date'] ="";
//        $_POST['amount'] = "";
//        $_POST['comment'] =""; 
        set_post_not_set_numeric('id',$pcfph_row['id']);
        set_post_not_set_string('reference', $pcfph_row['reference']);
        set_post_not_set_numeric('float_id',$pcfph_row['float_id']);
        set_post_not_set_date('tran_date', sql2date($pcfph_row['tran_date']));
        
        if($trans_type == ST_FLOAT_PAYMENT){
            set_post_not_set_numeric('amount', -$pcfph_row['amount']);
        }else{
            set_post_not_set_numeric('amount', $pcfph_row['amount']);            
        }
        set_post_not_set_string('comment', $pcfph_row['comment']);
    }else{
        $_POST['id'] = 0;
        set_post_not_set_string('reference', $Refs->get_next($trans_type));
        set_post_not_set_numeric('float_id', 0);
        set_post_not_set_date('tran_date', Today());
        set_post_not_set_numeric('amount', 0);
        set_post_not_set_string('comment', "");
    }
        

    hidden('selected_id', $_POST['id']);   

    start_table(TABLESTYLE2);
    
    if($trans_no>0){
        label_row(_("Transaction no.:"), $trans_no); 
        hidden('trans_no', $trans_no);
    }
    ref_row(_("Reference:"), 'reference', '', ); 
    petty_cash_floats_list_row('Petty Cash Float:', 'float_id', null, 'Select Float', false);
    date_row("Date:", "tran_date");    
    amount_row('Amount:', 'amount', $_POST['amount'], null, null, 2);
    textarea_row("Comment:", "comment", null, 30,3);
    end_table(1);

    br();
}


function display_petty_cash_float_payment_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;
}