<?php

function display_pos_credit_note_header($dii_no) {
    global $Refs;

        $type = ST_POS_CREDIT_NOTE;
    
        if ($dii_no > 0) {

            $header = get_pos_invoice_header($dii_no);
            $_POST['project_id'] = $header['project_id'];
            hidden('project_id', $header['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;
            }  

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

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

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

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

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

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


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

        } else {
            $_POST['reference'] = $Refs->get_next($type);            
            $_POST['approval_status'] = 0;
            
            $pos_credit_note_def_project = get_sys_prefs_parameter_value('pos_invoice_def_project');
            set_post_not_set_numeric("project_id", $pos_credit_note_def_project);
                    
            $pos_credit_note_def_location = get_sys_prefs_parameter_value('pos_invoice_def_location');
            set_post_not_set_string("location", $pos_credit_note_def_location);
            
            $pos_credit_note_def_float = get_sys_prefs_parameter_value('pos_invoice_def_float');
            set_post_not_set_numeric("float_id", $pos_credit_note_def_float);
            
            $pos_credit_note_def_customer = get_sys_prefs_parameter_value('pos_invoice_def_customer');
            set_post_not_set_numeric("debtor_no", $pos_credit_note_def_customer);
        }
        
        div_start('nsit_header');
  
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                start_table(TABLESTYLE2);  
                    table_section(1, "50%");

                        if ($dii_no > 0) {
                            $pd_request = get_pos_invoice_header($dii_no);
                            label_row(text_bold("POS Credit Note #:"), get_customer_trans_view_str($pd_request['type'], $pd_request['trans_no'])); 
                            value_list_row('Entry Type:', 'entry_type_id', 'UTILITY_BILL_ENTRY_TYPES', null, '', true);
                            
                            $reference = $pd_request['reference'];            
                            text_row("Reference:", 'reference', $reference, null, null);            
                        } else {  
                            value_list_row('Entry Type:', 'entry_type_id', 'UTILITY_BILL_ENTRY_TYPES', null, '', true);
                            text_row("Reference:", 'reference', $Refs->get_next($type), null, null);   
                        }
                        
                        customer_list_row('Customer:', 'debtor_no', null, '');

                        hidden('project_id', $_POST['project_id']);
                        
                        date_row("Date:", "tran_date");
                        

                    table_section(2, "50%");
                        locations_list_row("Location:", 'location', null, '', false);  
                        
                        petty_cash_floats_list_row("Float:", 'float_id');
                        
                        textarea_row("Comment:", 'comments', null, 35, 2); 

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

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

function display_pos_credit_note_details($dii_no) { 
    global $Ajax, $daily_item_types_array;
    
    display_heading("Details");
    
    $trans_no = $type = -1;
    $header = get_pos_invoice_header_record($dii_no);
        if (is_array($header)) {
            $trans_no = $header['trans_no'];
            $type = $header['type'];
        } 
    
    $Ajax->activate('nsit_details');
    div_start('nsit_details');
    
        start_table(TABLESTYLE, "width=98%");

            $th = array(_("ID"), _("Item Type"), _("Item"), _("Unit"), _("Tran Qty"), _('Unit Price'), _('Amount'), _('Line Comment'), _(""), _(""));  
            table_header($th);

            $k = $qty_total = $amount_total = 0; //row colour counter
                $result = get_pos_invoice_details($trans_no, $type);      
                    while ($row = db_fetch($result)) {
                        alt_table_row_color($k);

                            label_cell($row['trans_id'], 'align=center');
                            label_cell($daily_item_types_array[$row['daily_item_type']]);
                            if ($row['daily_item_type'] == NSIT_NON_STOCK_ITEM || $row['daily_item_type'] == NSIT_STOCK_ITEM) {
                                label_cell($row["stock_id"]." - ".$row["item_description"]);  
                            } else {
                                label_cell($row["item_description"]);
                            }
                            label_cell($row["unit_name"]);
                            
                            $dec = get_qty_dec($row["stock_id"]);
                            $tran_qty = $row["tran_qty"];
                            label_cell(number_format($tran_qty, $dec), 'align=right');
                            $qty_total += $tran_qty;
                            
                            $tran_unit_price = $row["tran_unit_price"]; 
                            amount_cell($tran_unit_price); 
                            
                            $line_total = $tran_unit_price * $tran_qty;
                            amount_cell($line_total); 
                            $amount_total += $line_total;
                            
                            label_cell(nl2br($row["line_comment"]));          

                            edit_button_cell("Edit".$row["trans_id"], _("Edit"));    
                            delete_button_cell("Delete".$row["trans_id"], _("Delete"));  

                        end_row();        
                    }
                    
                    start_row(); 
                        label_cell(text_bold("Total"), 'align=right colspan=4');
                        amount_cell($qty_total, true); 
                        label_cell("");
                        amount_cell($amount_total, true); 
                        label_cell("", 'colspan=3');
                        hidden('total_tran_qty', $qty_total);
                        hidden('total_amount', $amount_total);
                    end_row();

        end_table(3);
    
    div_end();
}

function display_pos_credit_note_details_edit_controls($selected_id, &$Mode) {
    global $Ajax, $daily_item_types_array;
    $dec = 2;

    if ($selected_id > 0 && $Mode != 'Delete') {   
        $row = get_pos_invoice_details_record($selected_id); 
            if ($Mode == 'Edit') {
                $_POST['daily_item_type'] = $row["daily_item_type"];
                $_POST['stock_id'] = $row["stock_id"];
                $_POST['item_description'] = $row["item_description"];
                $_POST['tran_unit'] = $row["tran_unit"];
                $_POST['tran_qty'] = $row["tran_qty"];
                $_POST['site_id'] = $row["project_site_id"]; 
                $_POST['tran_unit_price'] = $row["tran_unit_price"];
                $_POST['line_comment'] = $row["line_comment"];
            }
            
            if (! (strlen($_POST['stock_id']) > 0)) {
                $_POST['stock_id'] = $row["stock_id"];
            }
            if ($_POST['tran_unit'] == -1) {
                $_POST['tran_unit'] = $row["tran_unit"];
            }
            if (! ($_POST['tran_qty'] > 0)) {
                $_POST['tran_qty'] = $row["tran_qty"];
            }  
                            
            if (! (strlen($_POST['line_comment']) > 0)) {
                $_POST['line_comment'] = $row["line_comment"];
            }
    }else{
        set_post_not_set_numeric("daily_item_type", NSIT_COMMENT);
        set_post_not_set_string("tran_unit", 'Nos');
    }
    
    if(list_updated('daily_item_type')){
        if ($_POST['daily_item_type'] == NSIT_COMMENT) {
            $_POST['tran_unit'] = "Nos";
        }
    }
  
    $Ajax->activate("control_items");    
    div_start('control_items');
        start_table(TABLESTYLE2);
        
            if ($selected_id > 0 && $Mode != 'Delete') {  
                label_row('Rec Id:', $selected_id);
                label_row('Item Type:', $daily_item_types_array[$row['daily_item_type']]);
                $_POST['daily_item_type'] = $row['daily_item_type'];
                hidden('daily_item_type', $row['daily_item_type']);
            } else {
                custom_values_list_row('Item Type:', 'daily_item_type', $daily_item_types_array, null, '', true);
            }
            
                if ($_POST['daily_item_type'] == NSIT_NON_STOCK_ITEM) {

                    if ($selected_id > 0 && $Mode != 'Delete') {  
                        label_row('Daily Item:', $_POST['stock_id']);
                        hidden('stock_id', $_POST['stock_id']);
                        text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                    } else {
                        label_row('Stock Item:', non_stock_items_list('stock_id', null, false, true));
                        $itm = get_item($_POST['stock_id']);
                            if (is_array($itm)) {
                                hidden('item_description', $itm['description']);
                            } else {
                                hidden('item_description', '');
                            }
                    }

                    units_list_row('Unit:', 'tran_unit', $_POST['stock_id'], null, '');
                    $dec = get_qty_dec($_POST["stock_id"]);

                } elseif ($_POST['daily_item_type'] == NSIT_STOCK_ITEM) {

                    if ($selected_id > 0 && $Mode != 'Delete') {  
                        label_row('Stock Item:', $_POST['stock_id']);
                        hidden('stock_id', $_POST['stock_id']);
                        text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                    } else {
                        label_row('Stock Item:', stock_items_list('stock_id', null, false, true));
                        $itm = get_item($_POST['stock_id']);
                            if (is_array($itm)) {
                                hidden('item_description', $itm['description']);
                            } else {
                                hidden('item_description', '');
                            }
                    }

                    units_list_row('Unit:', 'tran_unit', $_POST['stock_id'], null, '');
                    $dec = get_qty_dec($_POST["stock_id"]);

                } elseif ($_POST['daily_item_type'] == NSIT_COMMENT) {
                    text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                    hidden('stock_id', '');

                    $units_array = build_all_item_units_array();
                    custom_values_list_row('Unit:', 'tran_unit', $units_array, null, '');
                } else {
                    hidden('stock_id', '');
                    hidden('tran_unit', '');
                    hidden('item_description', '');
            }
            
            amount_row("Quantity:", 'tran_qty', null, null, null, $dec); 

            amount_row("Unit Price:", 'tran_unit_price', null, null, null, 2);
            
            project_sites_list_row("Job:", 'site_id', $_POST['project_id'], null, '', false); 
            text_row_ex('Line Comment:', 'line_comment', 50, 400, 'Line Comment');

        end_table(2);
    div_end();
}

function can_process_pos_credit_note_header($dii_no, $approve=false) {
    global $Refs;
    
    if (isset($_POST['NewCreditNote']) || isset($_POST['ModifyCreditNote'])) {
        $type = ST_POS_CREDIT_NOTE;
    } else {
        $set_focus = '';
        $message = ("Invalid transaction type.");
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if (! ($_POST['entry_type_id'] > 0)) {
        return array("success" => false, "focus_to" => 'entry_type_id', "message" => "Please select an entry type.");   
    }
    
    $trans_no = 0;
    $header = get_pos_invoice_header_record($dii_no);
    if(isset($header['trans_no']) && $header['trans_no'] > 0){
        $trans_no = $header['trans_no'];
    }
      
    if (is_array($header)) {
        if (! ($header['approval_status'] == AS_NEW || $header['approval_status'] == AS_WITH_THE_APPROVER || 
               $header['approval_status'] == AS_AWAITING_APPROVAL || $header['approval_status'] == AS_BACK_TO_ORIGINATOR)) {
        
            $set_focus = '';
            $message = ("This document status does not allow further updating.");
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    } 
    
    if (! $Refs->is_valid($_POST['reference'])) {
        $message = ("Please enter a reference.");
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    }    
 
    $ref_msg = reference_exists($_POST['reference'], $type, $trans_no);
        if ($ref_msg) {
            $message = $ref_msg;
            $set_focus = 'reference';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
        }
      
    if (! ($dii_no > 0)) {
        if (! ($_POST['project_id'] > 0)) {
            $message = "Please select a Project.";
            $set_focus = 'project_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    }
      
    if (! ($_POST['debtor_no'] > 0)) {
            $message = "Please select a customer.";
            $set_focus = 'debtor_no';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }else{
        $def_branch = get_default_branch($_POST['debtor_no']);
        if(!(isset($def_branch['branch_code']) && $def_branch['branch_code'] > 0)) {
            $message = "Default branch not found for this customer.";
            $set_focus = 'debtor_no';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    }
    
        
    if (! ($_POST['float_id'] > 0)) {
            $message = "Please select a float.";
            $set_focus = 'float_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
    
    if (! is_date($_POST['tran_date'])) {
        $message = "Date entered is not a valid date.";
        $set_focus = '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);      
    } 
    
    $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);      
    }
              
    if ($_POST['location'] == '') {
        $message = "Please select a location.";
        $set_focus = 'location';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }

        
    if ($approve === true) {
        $header = get_pos_invoice_header_record($dii_no);
        $lines_count = get_pos_invoice_details_lines_count($header['trans_no'], $header['type']);
            if (! ($lines_count > 0)) {
                $message = "Could not be approved. No any detail lines saved.";
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
    }
        
    $row_state = 0;
    if ($dii_no > 0) {
        $row_state = $header['row_state'];
    }
    
    return array("success" => true, 'row_state' => $row_state, "message" => "");    
}

function can_process_pos_credit_note_line() {
    if (! ($_POST['daily_item_type'] > 0)) {
        $message = "Please select a daily item type.";
        $set_focus = 'daily_item_type';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if ($_POST['daily_item_type'] == NSIT_NON_STOCK_ITEM || $_POST['daily_item_type'] == NSIT_STOCK_ITEM) {
        if (! (strlen($_POST['stock_id']) > 0)) {
            $message = "Please select an item.";
            $set_focus = 'stock_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }

        if ($_POST['tran_unit'] == -1) {
            $message = "Please select a tran unit.";
            $set_focus = 'tran_unit';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    } elseif ($_POST['daily_item_type'] == NSIT_COMMENT) {
        if (! (strlen($_POST['item_description']) > 0)) {
            $message = "Item description cannot be empty.";
            $set_focus = 'item_description';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
        
        if ($_POST['tran_unit'] == '0') {
            $message = "Please select a unit.";
            $set_focus = 'tran_unit';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }
    
    $item = get_stock_item_edit_info($_POST['stock_id']);
    if ($_POST['daily_item_type'] == NSIT_NON_STOCK_ITEM){
        if (!($item['mb_flag'] == "D")) {
            $message = "Selected item is a stock item, Please select a non-stock item.";
            $set_focus = 'stock_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        } 
    }
    if ($_POST['daily_item_type'] == NSIT_STOCK_ITEM){
        if (!($item['mb_flag'] == "B" || $item['mb_flag'] == "M")) {
            $message = "Selected item is not a stock item, Please select a stock item.";
            $set_focus = 'stock_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        } 
    }
    
    if (! (input_num('tran_qty') > 0)) {
        $message = "Quantity should be greater than zero.";
        $set_focus = 'tran_qty';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if (! ($_POST['tran_unit_price'] > 0)) {
        $message = "Item unit price should be greater than zero.";
        $set_focus = 'tran_unit_price';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);          
    }

        return array("success" => true, "focus_to" => '', "message" => "");  
}

function can_delete_pos_credit_note_line($dii_no) {
   $header = get_pos_invoice_header_record($dii_no);
   
    if (is_array($header)) {
        if (! ($header['approval_status'] == AS_NEW || $header['approval_status'] == AS_WITH_THE_APPROVER || 
                $header['approval_status'] == AS_AWAITING_APPROVAL || $header['approval_status'] == AS_BACK_TO_ORIGINATOR)){
            $message = ("This document status does not allow further updating.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    } 
    
    $lines_count = get_pos_invoice_details_lines_count($header['trans_no'], $header['type']);
        if (! ($lines_count > 1)) {
            $message = ("This is the last line. Can not delete this line.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }  
    
    return array("success" => true, "focus_to" => '', "message" => "");       
}

function save_pos_credit_note_header(&$dii_no, $type) {
    global $systypes_array;
    
    $def_branch = get_default_branch($_POST['debtor_no']);
    $branch_code = $def_branch['branch_code'];
    
    $dii_no = write_pos_invoice_header($type, $dii_no, $_POST['reference'], $_POST['project_id'], $_POST['debtor_no'], $branch_code, input_num('total_tran_qty'), 
                                       input_num('total_amount'), $_POST['location'], $_POST['comments'], $_POST['tran_date'], $_POST['float_id'], 0, $_POST['entry_type_id']);  
        if ($dii_no > 0) {
            return array("success" => true, 'trans_no' => $dii_no, "message" => $systypes_array[$type]." header #$dii_no has been saved.");
        } else {
            return array("success" => false, 'trans_no' => '', "message" => "Could not be saved ".$systypes_array[$type].' header.');
        }
}

function save_pos_credit_note_line(&$dii_no, $selected_id) {    
    global $systypes_array;
    
    $standard_cost = 0; $conversion_factor = 1;
    
    $header = get_pos_invoice_header_record($dii_no);
    $trans_no = $header['trans_no'];
    $type = $header['type'];
    
    $tran_unit = $_POST['tran_unit'];
    $tran_unit_price = input_num('tran_unit_price');
    
    if ($_POST['daily_item_type'] == NSIT_STOCK_ITEM) {
        $standard_cost = get_standard_cost($_POST['stock_id']);
        get_convertion_factor2($_POST['stock_id'], $tran_unit, $conversion_factor);

    } else{ 
        $standard_cost = $tran_unit_price * 0.9;
    }
    
    $qty = input_num('tran_qty') * $conversion_factor;
    
    $af_no = write_pos_invoice_line($trans_no, $selected_id, $type, $_POST['location'], $_POST['tran_date'], $_POST['stock_id'], $_POST['daily_item_type'], 
                                    $_POST['item_description'], $_POST['tran_unit'], input_num('tran_qty'), $qty, $conversion_factor, $standard_cost, $tran_unit_price, 
                                    get_post('site_id'), $_POST['line_comment']); 
    
        if (!($af_no > 0)) { 
            if ($selected_id > 0) {
                $ln_ms = $systypes_array[$header['type']]." #$selected_id line could not be updated.";
            } else {
                $ln_ms = $systypes_array[$header['type']]." line could not be saved.";
            }
            
            return array("success" => false, 'trans_no' => $dii_no, "message" => $ln_ms);
        }
        
        update_pos_invoice_header_total($dii_no);
            
        return array("success" => true, 'trans_no' => $dii_no, "message" => $systypes_array[$header['type']]." line saved.");
        
}

function save_pos_credit_note(&$dii_no, $selected_id) {
    global $systypes_array;
    
    if (isset($_POST['NewCreditNote']) || isset($_POST['ModifyCreditNote'])) {
        $type = ST_POS_CREDIT_NOTE;
    } 
    
    $hd_msg = can_process_pos_credit_note_header($dii_no);   
        if ($hd_msg["success"] !== true) {          
            if (isset($hd_msg["focus_to"])) {
                set_focus($hd_msg["focus_to"]);            
            }
            
            return array("success" => false, "message" => $hd_msg["message"]);
        }
    
    $ln_msg = can_process_pos_credit_note_line();
        if ($ln_msg['success'] !== true) {
            if (isset($ln_msg["focus_to"])) {
                set_focus($ln_msg["focus_to"]);            
            }
            
            return array("success" => false, 'trans_no' => $dii_no, "message" => $ln_msg['message']);        
        }
       
        begin_transaction();

            $header_msg = save_pos_credit_note_header($dii_no, $type);
                if ($header_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, 'trans_no' => $dii_no, "message" => $header_msg['message']);
                }

            $line_msg = save_pos_credit_note_line($dii_no, $selected_id);
                if ($line_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, 'trans_no' => $dii_no, "message" => $line_msg['message']);
                }

        commit_transaction();

    return array("success" => true, 'trans_no' => $dii_no, "message" => $systypes_array[$type]." #$dii_no has been saved.");
}

function delete_pos_credit_note_line($dii_no, $selected_id) {
    $cd_msg = can_delete_pos_credit_note_line($dii_no, $selected_id);
        if ($cd_msg['success'] !== true) {
            return $cd_msg;
        }
        
        begin_transaction();
            delete_pos_invoice_details_record($selected_id);
            update_pos_invoice_header_total($dii_no);
        commit_transaction();

    return array("success" => true, 'trans_no' => $dii_no, "message" => "Record #$selected_id has been deleted.");
}

function save_pos_credit_note_header_only($dii_no, $approve=false) {
    global $systypes_array;
    
    $hd_msg = can_process_pos_credit_note_header($dii_no, $approve);   
        if ($hd_msg["success"] !== true) {          
            if (isset($hd_msg["focus_to"])) {
                set_focus($hd_msg["focus_to"]);            
            }
            
            return array("success" => false, "message" => $hd_msg["message"]);
        }
        
        $row_state = $hd_msg['row_state'];
        
        $type = ST_POS_CREDIT_NOTE;
    
        begin_transaction();
        
            $msg = save_pos_credit_note_header($dii_no, $type);
                if ($msg["success"] !== true) {          
                    cancel_transaction();

                    return $msg;
                } 

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

                    return $msg;
                } 
                
            $header = get_pos_invoice_header_record($dii_no);
            
            // daily item issue
            $pos_di_msg = save_pos_credit_note_to_daily_item_issue($header);
                if ($pos_di_msg["success"] !== true) {          
                    cancel_transaction();

                    return $pos_di_msg;
                }    

                $posi_dii = $pos_di_msg['posi_dii'];
                
            // stock moves
            $ap_msg = approve_pos_credit_note($posi_dii);
                if ($ap_msg["success"] !== true) {          
                    cancel_transaction();

                    return $ap_msg;
                } 
                
            $rs_af_row = update_pos_invoice_header_row_state_by_id($dii_no, $row_state);
                if ($rs_af_row != 1) {          
                    cancel_transaction();

                    return array("success" => false, "message" => "Could not approve ".$systypes_array[$header['type']].".");
                } 
                
            $new_row_state = db_new_row_state($row_state);

            $ap_msg_2 = direct_update_document_status($header['type'], $header['trans_no'], AS_APPROVED, $new_row_state);     
                if ($ap_msg_2['success'] === false ) {
                    cancel_transaction();
                    return array("success" => false, 'trans_no' => $dii_no, "message" => "Could not approve ".$systypes_array[$header['type']].".");
                }
                 
        commit_transaction();

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

function save_pos_credit_note_to_daily_item_issue($header) {
    $source_trans_no = $header['trans_no'];
    $source_type = $header['type'];
    
        $header_msg = save_pos_credit_note_daily_item_issue_header($header);
            if ($header_msg["success"] !== true) {
                cancel_transaction();
                return $header_msg;
            }

            $ins_id = $header_msg["ins_id"];

        $line_msg = save_pos_credit_note_daily_item_issue_lines($ins_id, $source_trans_no, $source_type);
            if ($line_msg['success'] !== true) {
                cancel_transaction();
                return $line_msg;
            }
            
        return array("success" => true, "message" => "", "posi_dii" => $ins_id);
}

function save_pos_credit_note_daily_item_issue_header($header) {
    global $systypes_array;
    
    $type = ST_POS_ITEM_RETURN;
    $tran_date_ = sql2date($header['tran_date']);
    
    $reference = get_next_reference_for_auto_generation($type);
    $ins_id = write_daily_item_issue_header($type, 0, $reference, $header['project_id'], 0, 0, '', '', $header['loc_code'], $header['comments'], $tran_date_, 
                                            $header['trans_no'], $header['type']);  
    
        if (! ($ins_id > 0)) {
            return array("success" => false, "message" => "Could not add ".$systypes_array[$type].' header.');
        } 
        
        return array("success" => true, "message" => "", 'ins_id' => $ins_id);
}

function save_pos_credit_note_daily_item_issue_lines($ins_id, $source_trans_no, $source_type) {    
    global $systypes_array;
    
    $header = get_daily_item_issue_header_record($ins_id);
        $trans_no = $header['trans_no'];
        $type = $header['type'];
        $tran_date_ = sql2date($header['tran_date']);
    
        $result = get_pos_invoice_details_lines($source_trans_no, $source_type);
            while ($row = db_fetch($result)) {
                $loc_code = $row['loc_code'];
                $stock_id = $row['stock_id'];
                $item_description = $row['item_description'];
                $tran_unit = $row['tran_unit'];
                $tran_qty = $row['tran_qty'];
                $qty = $row['qty'];
                $conversion_factor = $row['conversion_factor'];
                $standard_cost = $row['standard_cost'];
                $project_site_id = $row['project_site_id'];
                $line_comment = $row['line_comment'];

                $source_line_id = $row['trans_id'];
                $daily_item_type = $row['daily_item_type'];
                $base_unit_price = $row['tran_unit_price'] / $row['conversion_factor'];

                $inln_id = insert_daily_item_issue_line($trans_no, $type, $loc_code, $tran_date_, $stock_id, $daily_item_type, $item_description, $tran_unit, $tran_qty, $qty, 
                                                        $conversion_factor, $standard_cost, $project_site_id, $line_comment, 0, 0, $source_line_id, $base_unit_price);

                    if (! ($inln_id > 0)) {
                        return array("success" => false, "message" => "Could not add ".$systypes_array[$type]." detail line.");
                    } 
            }
            
            return array("success" => true, "message" => "");
}

function approve_pos_credit_note($posi_dii) {
    $header = get_daily_item_issue_header_record($posi_dii);
        $trans_no = $header['trans_no'];
        $type = $header['type'];
        $project_id = $header['project_id'];
        $tran_date_ = sql2date($header['tran_date']);
    
    $result = get_daily_item_issue_details_lines($trans_no, $type);      
        if(db_num_rows($result) == 0){
            return array("success" => false, 'trans_no' => $trans_no, "message" => "No detail record found for transaction # ".$trans_no);        
        }
    
        while ($row = db_fetch($result)) {
            $qty = $row["qty"];
            $tran_qty = $row["tran_qty"];
            $standard_cost = $row["standard_cost"];
            
            $price = $row['price'];
            
            if ($row['daily_item_type'] == NSIT_STOCK_ITEM) {
                $n = add_stock_adjustment_item($trans_no, $row["stock_id"], $row["loc_code"], $tran_date_, $header["reference"], $qty, $standard_cost, '', $row["tran_unit"], 
                                               $tran_qty, $row["conversion_factor"], $type, 0, $row["project_site_id"], $row["trans_id"], $project_id);
            } else {
                $n = add_non_stock_move($type, $row["stock_id"], $trans_no, $row["loc_code"], $tran_date_, $header["reference"], $qty, $standard_cost, 0, 1, $price, 
                                        $row["discount_percent"], $row["tran_unit"], $tran_qty, $row["conversion_factor"], 0, $row["project_site_id"], $row["trans_id"], 
                                        $row["item_description"], $project_id);
            }
            
            if(!($n > 0)){
                return array("success" => false, 'trans_no' => $trans_no, "message" => "Could not create the movement record for rec id : ".$row["trans_id"]);
            }
        }  
        
        return array("success" => true, 'trans_no' => $trans_no, "message" => "");            
}

function clear_pos_credit_note_details() {
    unset($_POST['daily_item_type']);
    unset($_POST['stock_id']);
    unset($_POST['item_description']);
    unset($_POST['tran_unit']);
    unset($_POST['tran_qty']);
    unset($_POST['site_id']);
    unset($_POST['line_comment']); 
}

?>