<?php

function display_pos_credit_note_header_details($crd_trans_no) {
    global $document_approval_statuses;
    
    $s_type = ST_POS_CREDIT_NOTE;
    
    $row = get_pos_invoice_header_type_trans_no($s_type, $crd_trans_no);
        $_POST['project_id'] = $row['project_id'];
        hidden('project_id', $row['project_id']);

            $project_id = $_POST['project_id'];
            $user_id = $_SESSION['wa_current_user']->user;
            $cap = can_access_project($project_id, $user_id);
            if ($cap['success'] !== true) {
                display_error($cap["message"]);
                set_focus('project_id');
                display_footer_exit();
                exit;
            } 
    
        start_outer_table(TABLESTYLE2, "width=60%");

            table_section(1, "50%");
                label_row(_("Credit Note No:"), get_customer_trans_view_str($row['type'], $row['trans_no']), "class='tableheader2'");
                label_row(_("Entry Type:"), $row['entry_type_name'], "class='tableheader2'");
                label_row(_("Reference:"), $row['reference'], "class='tableheader2'");
                $customer_name = get_customer_formatted_name($row['debtor_no']);
                label_row(_("Customer:"), $customer_name, "class='tableheader2'");
                label_row(_("Date:"), sql2date($row['tran_date']), "class='tableheader2'");
                label_row(_("Location:"), $row['location_name'], "class='tableheader2'");

            table_section(2, "50%");
                label_row(_("Credit Note Total:"), number_format($row['total'], 2), "class='tableheader2'");
                label_row(_("Paid Amount:"), number_format($row['paid_amount'], 2), "class='tableheader2'");
                label_row(_("Float:"), $row['float_name'], "class='tableheader2'");
                $s = get_project_trans_view_str(ST_APPROVAL_LOG, $crd_trans_no."&source_type_id=".$s_type, "Approval Status");
                label_row($s, $document_approval_statuses[$row['approval_status']]);
                label_row(_("Comment:"), nl2br($row['comments']), "class='tableheader2'");

        end_outer_table(2);
}

function display_pos_customer_return($crd_trans_no, $pos_cst_rtn_id) {
    global $Refs;

        $type = ST_POS_CUSTOMER_RETURN;
    
        if ($pos_cst_rtn_id > 0) {
            $header = get_pos_customer_payment_record($pos_cst_rtn_id);
            
            if (! isset($_POST['reference'])) {
                $_POST['reference'] = $header['reference'];
            }

            if (! isset($_POST['tran_date'])) {
                $_POST['tran_date'] = sql2date($header['tran_date']);
            }
            
            if (! isset($_POST['float_id'])) {
                $_POST['float_id'] = $header['float_id'];
            }
            
            if (! isset($_POST['amount'])) {
                $_POST['amount'] = $header['amount'];
            }

            if (! isset($_POST['comments'])){
                $_POST['comments'] = $header['comments'];
            }        

        } else {
            $_POST['reference'] = $Refs->get_next($type);            
            $_POST['approval_status'] = 0;
            
            if (! isset($_POST['float_id'])) {
                $inv_row = get_pos_invoice_header_type_trans_no(ST_POS_CREDIT_NOTE, $crd_trans_no);
                $_POST['float_id'] = $inv_row['float_id'];
            }
        }
        
        div_start('pos_cst_rtn_header');
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                start_table(TABLESTYLE2);  
                    table_section(1, "50%");

                        $trans_no = 0;
                        if ($pos_cst_rtn_id > 0) {
                            $pd_request = get_pos_customer_payment_record($pos_cst_rtn_id);
                            label_row(text_bold("Return Trans #:"), get_customer_trans_view_str($pd_request['type'], $pd_request['trans_no'])); 
                            
                            $_POST['approval_status'] = $pd_request['approval_status'];            
                            $trans_no = $pd_request['trans_no'];            
                        } 
                        ref_row("Reference:", 'reference');   
                        date_row("Date:", "tran_date");
                        petty_cash_floats_list_row("Float:", 'float_id', null , '');

                    table_section(2, "50%");
                        amount_row("Amount:", 'amount', null, null, null, 2);
                        textarea_row("Comment:", 'comments', null, 35, 2); 

                        global $document_approval_statuses;
                        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $trans_no."&source_type_id=".$type, "Approval Status");
                        label_row($s, $document_approval_statuses[$_POST['approval_status']]);

            end_outer_table(2); // outer table
        div_end();
}

function can_process_pos_customer_return($crd_trans_no, $pos_cst_rtn_id) {
    global $systypes_array, $Refs;
    
    $s_type = ST_POS_CREDIT_NOTE;
    $type = ST_POS_CUSTOMER_RETURN;
    
    $pos_crd_name = $systypes_array[$s_type];
    
    $crd_hd = get_pos_invoice_header_type_trans_no($s_type, $crd_trans_no);
        if (! (isset($crd_hd['id']) && $crd_hd['id'] > 0)) {
            return array("success" => false, "message" => "Could not find $pos_crd_name trans #$crd_trans_no.");
        }
        
    if ($pos_cst_rtn_id > 0) {
        if (! (in_array($crd_hd['approval_status'], array(AS_APPROVED, AS_PAID)))) {
            return array("success" => false, "message" => "Approval status of $pos_crd_name trans #$crd_trans_no does not allow to update this transaction.");
        }
    } else {
        if (! (in_array($crd_hd['approval_status'], array(AS_APPROVED)))) {
            return array("success" => false, "message" => "Approval status of $pos_crd_name trans #$crd_trans_no does not allow to create new transaction.");
        }
    }
        
    $trans_no = 0;
    $header = get_pos_customer_payment_record($pos_cst_rtn_id);
        if (isset($header['trans_no']) && $header['trans_no'] > 0) {
            $trans_no = $header['trans_no'];
        }
      
    if (is_array($header)) {
        if (! in_array($header['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))) {
            return array("success" => false, "message" => "This document status does not allow further updating.");
        }
    } 
    
    if (! $Refs->is_valid($_POST['reference'])) {
        return array("success" => false, "focus_to" => 'reference', "message" => "Please enter a reference.");      
    }    
 
    $ref_msg = reference_exists($_POST['reference'], $type, $trans_no);
        if ($ref_msg) {
            return array("success" => false, "focus_to" => 'reference', "message" => $ref_msg);       
        }
    
    if (! is_date($_POST['tran_date'])) {
        return array("success" => false, "focus_to" => 'tran_date', "message" => "Date entered is not a valid date.");        
    }
    
    if (! is_date_in_fiscalyear($_POST['tran_date'])) {
        return array("success" => false, "focus_to" => 'tran_date', "message" => "The entered date is not in fiscal year.");      
    } 
    
    $msg = is_accounting_period_open($_POST['tran_date']);
        if ($msg['success'] !== true) {
            return array("success" => false, "focus_to" => 'tran_date', "message" => $msg['message']);      
        }
      
    if (! ($_POST['float_id'] > 0)) {
        return array("success" => false, "focus_to" => 'float_id', "message" => "Please select a float."); 
    }
    
    if (! (input_num('amount') > 0)) {
        return array("success" => false, "focus_to" => 'amount', "message" => "Amount should be greater than zero.");          
    }
    
    $this_amount = input_num('amount');
            
    $pos_credit_note_total = $crd_hd['total'];
    $paid_amount = get_pos_customer_payments_total_by_source($s_type, $crd_trans_no, $pos_cst_rtn_id);
    $total_amount = $paid_amount + $this_amount;
    
        if ($total_amount > $pos_credit_note_total) {
            $exceeded_amount = $total_amount - $pos_credit_note_total;
            return array("success" => false, "focus_to" => 'amount', "message" => "$pos_crd_name total is exceeded by $exceeded_amount.");          
        }
              
    $row_state = 0;
    if ($pos_cst_rtn_id > 0) {
        $row_state = $header['row_state'];
    }
    
    return array("success" => true, 'row_state' => $row_state, "message" => "", 'trans_no' => $trans_no, 'crd_hd' => $crd_hd);    
}

function save_pos_customer_return($crd_trans_no, $pos_cst_rtn_id, $approve=false) {
    global $systypes_array;
    
    $hd_msg = can_process_pos_customer_return($crd_trans_no, $pos_cst_rtn_id);   
        if ($hd_msg["success"] !== true) {          
            return $hd_msg;
        }
        
        $trans_no = $hd_msg['trans_no']; $row_state = $hd_msg['row_state']; $crd_hd = $hd_msg['crd_hd'];
        $source_type = $crd_hd['type']; $source_trans_no = $crd_hd['trans_no']; $source_row_state = $crd_hd['row_state'];
        $type = ST_POS_CUSTOMER_RETURN;
    
        begin_transaction();
        
            $in_id = write_pos_customer_payment($type, $pos_cst_rtn_id, $_POST['reference'], $_POST['tran_date'], $_POST['float_id'], input_num('amount'), $_POST['comments'], 
                                                $row_state, $source_type, $source_trans_no);  
                if (! ($in_id > 0)) {
                    cancel_transaction();
                    
                    return array("success" => false, "message" => "Could not save ".$systypes_array[$type]." #$pos_cst_rtn_id.");
                } else {
                    $pos_cst_rtn_id = $in_id;
                }
                
            $af_row = calculate_and_update_pos_invoice_header_paid_amount($source_type, $source_trans_no, $source_row_state);
                if ($af_row != 1) {
                    cancel_transaction();
                    
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$source_type]." #$crd_trans_no total of paid amount.");
                }
                
            $new_crd_hd = get_pos_invoice_header_record_type_trans_no($source_type, $source_trans_no);
                if ($new_crd_hd['total'] == $new_crd_hd['paid_amount'] && $new_crd_hd['approval_status'] != AS_PAID) {
                    $ap_msg_2 = direct_update_document_status($source_type, $source_trans_no, AS_PAID, db_new_row_state($source_row_state));     
                        if ($ap_msg_2['success'] === false ) {
                            cancel_transaction();

                            return array("success" => false, "message" => "Could not update ".$systypes_array[$source_type]." approval status.");
                        }
                } elseif ($new_crd_hd['total'] > $new_crd_hd['paid_amount'] && $new_crd_hd['approval_status'] == AS_PAID) {
                    $ap_msg_2 = direct_update_document_status($source_type, $source_trans_no, AS_APPROVED, db_new_row_state($source_row_state));     
                        if ($ap_msg_2['success'] === false ) {
                            cancel_transaction();

                            return array("success" => false, "message" => "Could not update ".$systypes_array[$source_type]." approval status.");
                        }
                }

                if ($approve === false) {
                    commit_transaction();

                    return array("success" => true, "message" => $systypes_array[$type]." #$crd_trans_no has been saved.", 'pos_cst_rtn_id' => $pos_cst_rtn_id);
                } 
                
            $ap_msg = direct_update_document_status($type, $trans_no, AS_PROCESSED, db_new_row_state($row_state));     
                if ($ap_msg['success'] === false ) {
                    cancel_transaction();

                    return array("success" => false, "message" => $ap_msg['message']);
                }
                
            $amount_ = input_num('amount') * -1;
            $ins_ft_id = add_to_petty_cash_float($type, $trans_no, $_POST['float_id'], $amount_, $_POST['tran_date']);
                if (! ($ins_ft_id > 0)) {
                    cancel_transaction();
                    
                    return array("success" => false, "message" => "Could not add petty cash float transaction.");
                }
                 
        commit_transaction();

        meta_forward($_SERVER['PHP_SELF'], "type=$type&ApprovedID=$trans_no"); 
}

?>