<?php
/**********************************************************************
***********************************************************************/

include_once($path_to_root . "/inventory/includes/db/adjustments_db.inc");
include_once($path_to_root . "/includes/common_functions.inc");
include_once($path_to_root . "/inventory/includes/db/lot_adjustments_db.inc");

function display_site_material_return_header(&$order, $msgss=null){
    global $Refs, $Ajax, $approval_statuses;
    
    if($order->trans_no > 0){
//        $order->from_project_id = $_POST['from_project_id'];
        $from_project_access = can_access_project($order->from_project_id, $_SESSION['wa_current_user']->user);     
        if($from_project_access['success'] !== true){
            display_error($from_project_access["message"]);
            set_focus('from_project_id');
            display_footer_exit();
            exit;
        }

        $to_project_access = can_access_project($order->to_project_id, $_SESSION['wa_current_user']->user);     
        if($to_project_access['success'] !== true){
            display_error($to_project_access["message"]);
            set_focus('to_project_id');
            display_footer_exit();
            exit;
        }
    }
    
    
    div_start('header_tbl');
    display_heading($msgss);
    br();
    start_outer_table(TABLESTYLE2, "width=80%"); // outer table
    
        table_section(1, "35%");

            if(isset($_POST['ref'])){
                $reference = $_POST['ref'];
            }else{
                if($order->trans_no > 0){
                    $reference = $order->reference;
                }else{
                    $reference = $Refs->get_next($order->trans_type);
                }
            }
            ref_row(_("Reference:"), 'ref', '', $reference);

            if(!(isset($_POST['to_location']) && strlen($_POST['to_location']) > 0)){
                $_POST['to_location'] = $order->to_location;
            }
            locations_list_row(_("Receiving  Location:"), 'to_location', null, "Select receiving location", false);

            if(is_date(($order->tran_date))){
                $_POST['tran_date'] = ($order->tran_date);
            }
            date_row(_("Date:"), 'tran_date', '', true);   
            

        table_section(2, "35%");
            if(isset($_POST['from_project_id'])){
                $order->from_project_id = $_POST['from_project_id'];
            }else{
                $_POST['from_project_id'] = $order->from_project_id;
            }

            if($order->count_items() > 0){
                $job_ref = get_job_ref($order->from_project_id);
                $order->job_reference = $job_ref['description'];
                hidden("from_project_id", $order->from_project_id);       
                label_row(_("From Project:"), $order->job_reference);
            }else{
                project_list_row(_("From Project:"), 'from_project_id', $order->from_project_id, FALSE,TRUE);
            }

//            if(list_updated('from_project_id') && $_POST['from_project_id'] != -1){
//                $job_ref = get_job_ref($_POST['from_project_id']);
//                $order->job_reference = $job_ref['description'];
//                label_row(_("From Project:"), $order->job_reference);
//            }

            if(isset($_POST['to_project_id'])){
                $order->to_project_id = $_POST['to_project_id'];
            }else{
                $_POST['to_project_id'] = $order->to_project_id;
            }
            if($order->count_items() > 0){
                $job_ref = get_job_ref($order->to_project_id);
                $order->job_reference = $job_ref['description'];
                hidden("to_project_id", $order->to_project_id);       
                label_row(_("To Project:"), $order->job_reference);
            }else{
                project_list_row(_("To Project:"), 'to_project_id', $order->to_project_id, FALSE,TRUE);
            }

//            if(list_updated('to_project_id') && $_POST['to_project_id'] != -1){
//                $job_ref = get_job_ref($_POST['to_project_id']);
//                $order->job_reference = $job_ref['description'];
//                label_row(_("To Project:"), $order->job_reference);
//            }
            
            
            if(!(isset($_POST['company_code']) && strlen($_POST['company_code']) > 0)){
                $_POST['company_code'] = $order->company_code;
            }
            group_companies_list_row("Company:", "company_code", null, false, true);

            if(!(isset($_POST['employee_code']) && strlen($_POST['employee_code']) > 0)){
                $_POST['employee_code'] = $order->employee_code;
            }
            $Ajax->activate("employee_code");
            group_company_employees_simple_list_row("Employee:", "employee_code", $_POST['company_code'], null, "Select an employee", true);

            
            


        table_section(3, "30%");
        
            if(isset($_POST['comment'])){
                $memo = $_POST['comment'];
            }else{
                $memo = $order->comment;
            }
            textarea_row(_("Comment:"), 'comment', $memo, 30, 2);
         
            if(isset($order->status)){
                label_row("Status:", $approval_statuses[$order->status]);
            }

//        table_section(4, "25%");
//            if(isset($order->status) && $order->status == AS_PROCESSED){
//                label_row("Company:",  $order->company_name);
//                label_row("Employee:",  $order->employee_name);
//                label_row("Status:", $approval_statuses[$order->status]);
//            }else{
//                if(!(isset($_POST['company_code']) && strlen($_POST['company_code']) > 0)){
//                    $_POST['company_code'] = $order->company_code;
//                }
//                group_companies_list_row("Company:", "company_code", null, false, true);
//
//                if(!(isset($_POST['employee_code']) && strlen($_POST['employee_code']) > 0)){
//                    $_POST['employee_code'] = $order->employee_code;
//                }
//                $Ajax->activate("employee_code");
//                group_company_employees_simple_list_row("Employee:", "employee_code", $_POST['company_code'], null, "Select an employee", true);
//                
//                if(isset($order->status)){
//                    label_row("Status:", $approval_statuses[$order->status]);
//                }
//            }

    end_outer_table(1); // outer table
}


//---------------------------------------------------------------------------------

function site_material_return_item_edit_controls(&$order, $line_no=-1){
    global $Ajax;
    $id = find_submit('Edit');
        
    if(list_updated("tran_unit")){
        if(isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] !== $id){
            if(!($id > 0)){
                hidden("Edit".$_POST['previous_selected_id'], $_POST['previous_selected_id']);
                $id = $_POST['previous_selected_id'];
                hidden("Edit$id", $id);
                $_POST["Edit$id"] = $line_no = $id;
            }
        }
    }

        echo "<td colspan=11>";
        start_outer_table();
        
        table_section(1, "30%");
        
            $dec2 = 0;
            if($line_no != -1 && $line_no == $id){
                label_row("Row Id:", $order->line_items[$id]->row_id , "");
                $_POST['stock_id'] = $order->line_items[$id]->stock_id;
                $_POST['qty'] = qty_format($order->line_items[$id]->quantity, $order->line_items[$id]->stock_id, $dec);
                $_POST['tran_qty'] = qty_format($order->line_items[$id]->tran_qty, $order->line_items[$id]->stock_id, $dec);
                $_POST['std_cost'] = price_decimal_format($order->line_items[$id]->standard_cost, $dec2);

                if(!list_updated("tran_unit")){
                    $_POST['units'] = $order->line_items[$id]->units;
                }
                $_POST['from_task_id'] = $order->line_items[$id]->from_task_id;
                $_POST['to_task_id'] = $order->line_items[$id]->to_task_id;
                $_POST['from_project_site_id'] = $order->line_items[$id]->from_project_site_id;
                $_POST['to_project_site_id'] = $order->line_items[$id]->to_project_site_id;
                $_SESSION['lot_detail_line'] = $order->line_items[$id]->lot_details;
                $_POST['stock_control_method'] = $order->line_items[$id]->stock_control_method;

                $_POST['user_entered_tran_unit_cost'] = $order->line_items[$id]->user_entered_tran_unit_cost;
                $_POST['pri_line_id'] = $order->line_items[$id]->pri_line_id;

                hidden('stock_id', $_POST['stock_id']);
                label_row("Item Id:", $_POST['stock_id'], "");
                label_row("Item Description:", $order->line_items[$id]->item_description, "", 'nowrap');
                $Ajax->activate('items_table');

            }else{
                label_cell("");
                stock_costable_items_list_row("Item:", 'stock_id', null, false, true);
                if(list_updated('stock_id')){
                    $Ajax->activate('units');
                    $Ajax->activate('tran_unit');
                    $Ajax->activate('tran_qty');
                    $Ajax->activate('qty');
                    $Ajax->activate('std_cost');
                }

                if(list_updated('tran_unit')){
                    $Ajax->activate('std_cost');
                } 

                $dec = 2;
                $standard_cost = 0;
                $units = $stock_control_method = '';
                $item_info = get_item_edit_info($_POST['stock_id']);
                if (isset($item_info['units']) && strlen($item_info['units']) > 0) {
                    $dec = $item_info['decimals'];
                    $standard_cost = $item_info["standard_cost"];
                    $units = $item_info["units"];
                    $stock_control_method = $item_info["stock_control_method"];
                }
                $_POST['qty'] = number_format2(0, $dec);
                $_POST['std_cost'] = price_decimal_format($standard_cost, $dec2);
                $_POST['units'] = $units;
                $_POST['stock_control_method'] = $stock_control_method;

                hidden('qty', $_POST['qty']);
                hidden('units', $_POST['units']);

                
            }
            
            
        table_section(2, "30%");

            if($line_no != -1 && $line_no == $id){
                $original_unit = $order->line_items[$id]->tran_unit;
                if(isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] != $id){
                    $_POST['tran_unit'] = $original_unit;
                }
                units_list_row("Tran Unit:", 'tran_unit', $_POST['stock_id'], null, false, true);
            }else{
                units_list_row("Tran Unit:", 'tran_unit', $_POST['stock_id'], null, false, true);
                $original_unit = $_POST['tran_unit'];
            }


            hidden("previous_selected_id", $id);



            $tran_unit = $_POST['tran_unit'];
            $convesion_factor = 1;
            get_convertion_factor2($_POST['stock_id'], $tran_unit, $convesion_factor);
            $_POST['tran_unit'] = $tran_unit;
            hidden("convesion_factor", $convesion_factor);

            if($line_no != -1 && $line_no == $id){
                $line_ref = $order->line_items[$id]->line_ref;
                $tran_qty = $order->line_items[$id]->tran_qty;
            }else{
                $line_ref = $order->get_line_ref();
                $tran_qty = 0;
            }
            
            qty_row("Tran Quantity:", "tran_qty", 0, "", "", 2);

            
            if(!(isset($_POST['user_entered_tran_unit_cost']) && $_POST['user_entered_tran_unit_cost'] > 0)){
                $tran_unit_cost = $pri_line_id = 0;
                get_purchase_requistion_issue_item_tran_unit_cost_details($_POST['stock_id'], $_POST['std_cost'], $convesion_factor,
                                                                            $tran_unit_cost, $pri_line_id);
                $_POST['user_entered_tran_unit_cost'] = $tran_unit_cost;
                $_POST['pri_line_id'] = $pri_line_id;
            }

            if(!(isset($_POST['pri_line_id']) && $_POST['pri_line_id'] > 0)){
                $_POST['pri_line_id'] = 0;
            }
            hidden("pri_line_id", $_POST['pri_line_id']);
            
            amount_row("Unit Cost:", "user_entered_tran_unit_cost", 8, "", null,2);
            
        table_section(3, "30%");
        
            $Ajax->activate("from_task_id");
            $Ajax->activate("to_task_id");
            $Ajax->activate("from_project_site_id");
            $Ajax->activate("to_project_site_id");
            tasks_list_row("From Budget:", 'from_task_id', $_POST['from_project_id'], null, _('Select a from budget'));
            tasks_list_row("To Budget:", 'to_task_id', $_POST['to_project_id'], null, _('Select a to budget'));
            project_sites_list_row("From Project Site:", 'from_project_site_id', $_POST['from_project_id'], null, _('Select a from project site'));
            project_sites_list_row("To Project Site:", 'to_project_site_id', $_POST['to_project_id'], null, _('Select a to project site'));
            
//        table_section(4, "10%");
//        
//            br(2);
//            label_cell("&nbsp");
//            label_cell("&nbsp");
//            label_cell("&nbsp");

            
            
        end_outer_table();
        
        if($id != -1){
                button_cell('UpdateItem', _("Update"), _('Confirm changes'), ICON_UPDATE);
                button_cell('CancelItemChanges', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
                hidden('LineNo', $line_no);
                hidden('line_ref', $order->get_line_ref());
                set_focus('qty');
            }else{
                submit_cells('AddItem', _("Add"), "align=center colspan=2", _('Add new item to document'), true, ICON_SUBMIT);
                hidden('line_ref', $order->get_line_ref());
            }
            
        echo "</td>";
}

//-----------------------------------------------------------------------------------------------

function can_commit_site_material_return($order_name){
    global $Refs;
    $smr = get_session_variable($order_name);

    if($smr->trans_no > 0){
        if(!(in_array($smr->status, array(AS_NEW, AS_AWAITING_APPROVAL, 0, '')))){
            $message = (_("Status of this document does not allow future updating."));
            $focus = ('');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
        }
    }
    
    
    if(!(strlen($smr->to_location) > 0)){
        $input_error = 1;
        $message = ( _('Select to location.'));
        $focus = ('to_location');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    

    if(!($smr->from_project_id > 0)){
        $input_error = 1;
        $message = ( _('Select from project.'));
        $focus = ('from_project_id');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    $from_project = get_project_record($smr->from_project_id);
    if($from_project['purchase_to_stock'] == true){
        $input_error = 1;
        $message = ( _('From project has to be a non stock project [Purchase to Stock = No].'));
        $focus = ('from_project_id');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    if(!($smr->to_project_id > 0)){
        $input_error = 1;
        $message = ( _('Select to project.'));
        $focus = ('to_project_id');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    $to_project = get_project_record($smr->to_project_id);
    if($to_project['purchase_to_stock'] == false){
        $input_error = 1;
        $message = ( _('To project has to be a stock project [Purchase to Stock = Yes].'));
        $focus = ('to_project_id');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
//    $from_project_access = can_access_project($smr->from_project_id, $_SESSION['wa_current_user']->user);     
//    if($from_project_access['success'] !== true){
//        return array("success" => false, "focus_to" => 'from_project_id', "message" => $from_project_access['message']);
//    }
//    
//    $to_project_access = can_access_project($smr->to_project_id, $_SESSION['wa_current_user']->user);     
//    if($from_project_access['success'] !== true){
//        return array("success" => false, "focus_to" => 'to_project_id', "message" => $to_project_access['message']);
//    }
    
    if($smr->from_project_id == $smr->to_project_id){
        $input_error = 1;
        $message = ( _('Can not select same project for both from project and to project.'));
        $focus = ('to_project_id');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }

    if(!$Refs->is_valid($smr->reference)){
        $message = ( _("You must enter a reference."));
        $focus = ('ref');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }

    $ref_msg = reference_exists($smr->reference, ST_SITE_MATERIAL_RETURN, $smr->trans_no);
    if($ref_msg){
        $message = ( $ref_msg);
        $focus = ('ref');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
           
    if(!is_date($smr->tran_date)){
        $message = (_("The entered date is invalid."));
        $focus = ('tran_date');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    if (!is_date_in_fiscalyear($smr->tran_date)){
        $message = (_("The entered date is not in fiscal year."));
        $focus = ('tran_date');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    $msg = is_accounting_period_open($smr->tran_date);
    if ($msg['success'] !== true)
    { 
        $message = $msg['message'];
        $focus = ('tran_date');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    if(!(strlen($smr->company_code) > 0)){
        $input_error = 1;
        $message = ( _('Select a company.'));
        $focus = ('company_code');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    if(!(strlen($smr->employee_code) > 0)){
        $input_error = 1;
        $message = ( _('Select a employee.'));
        $focus = ('employee_code');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }

    
    
    if($smr->trans_no > 0){
        if(count($smr->line_items) == 0){
            $message = (_("You must enter at least one non empty item line."));
            $focus = ('stock_id');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
        }
    }
    
    $failed_item = $smr->check_qoh($smr->from_location, $smr->tran_date);
    if ($failed_item >= 0){
        $line = $smr->line_items[$failed_item];
        $message = (_("The adjustment cannot be processed because an adjustment item would cause a negative inventory balance :") .
                      " " . $line->stock_id . " - " .  $line->item_description);
            $_POST['Edit'.$failed_item] = 1; // enter edit mode
            unset($_POST['Process']);
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    
    $vtqd_msg = validate_transaction_quantity_details($smr);
    if($vtqd_msg['success'] !== true){
        $message = ($vtqd_msg['message']);
        $focus = "";
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    return array("success" => true);
}

function save_site_material_return($items, $to_location, $date_, $reference, $comment, $from_project_id, $to_project_id, $tran_type, $trans_no=0, $row_state=0, 
                                   $company_code='', $employee_code=''){
    
    global $Refs, $systypes_array;
    
    begin_transaction();
        $args = func_get_args();
        $args = (object)array_combine(array('items', 'to_location', 'date_', 'reference', 'comment', 'from_project_id', 'to_project_id', 'tran_type', 
                                            'trans_no', 'row_state', 'company_code', 'employee_code'), $args);

        if($trans_no > 0){
            $msg = update_site_material_return_header($trans_no, $date_, $reference, $to_location, $from_project_id, $to_project_id, $comment, $row_state, 
                                                      $company_code, $employee_code);
            if($msg['success'] !== true){
                cancel_transaction();
                return $msg;
            }else{
                $smr_no = $msg['trans_no'];
                $row_state = db_new_row_state($row_state);
            }
        }else{
            $msg = add_site_material_return_header($date_, $reference, $to_location, $from_project_id, $to_project_id, $comment, $company_code, $employee_code);
            if($msg['success'] !== true){
                cancel_transaction();
                return $msg;
            }else{
                $smr_no = $msg['trans_no'];
                set_session_variable("ST_SITE_MATERIAL_RETURN_no", $smr_no);
            }
            
            $Refs->save($tran_type, $smr_no, $reference);
        }  

        if(isset($_POST['UpdateItem']) || isset($_POST['AddItem'])){
            if(!isset($_POST['UpdateItem'])){
                $curr_id = (count($items)-1);
            }else{
                $curr_id = $_POST['previous_selected_id'];
//                $curr_id = find_submit('Edit');
            }

            $standard_cost = get_standard_cost($items[$curr_id]->stock_id);
            $tran_unit_cost = $items[$curr_id]->user_entered_tran_unit_cost;

            $msg = save_site_material_return_detail($items[$curr_id]->row_id, $smr_no, $items[$curr_id]->stock_id, $items[$curr_id]->quantity, $standard_cost, 
                                                        $tran_unit_cost, $items[$curr_id]->tran_unit, $items[$curr_id]->tran_qty, $items[$curr_id]->conversion_factor, 
                                                        $items[$curr_id]->from_task_id, $items[$curr_id]->to_task_id, $items[$curr_id]->from_project_site_id, 
                                                        $items[$curr_id]->to_project_site_id, $items[$curr_id]->pri_line_id); 

            if($msg['success'] !== true){
                cancel_transaction();
                return $msg;
            }
            
            $total_msg = update_site_material_return_header_total($smr_no, $row_state);
            if($total_msg['success'] !== true){
                cancel_transaction();
                return $total_msg;
            }

            commit_transaction();
            unset($_POST['Edit'.$curr_id]);
            return array("success" => true, "message" => $systypes_array[ST_SITE_MATERIAL_RETURN]." #".$smr_no." has beeen saved.", "tran_no" => $smr_no);
        }
        
    commit_transaction();
    return array("success" => true, "message" => $systypes_array[ST_SITE_MATERIAL_RETURN]." #".$smr_no." header has beeen saved.", "tran_no" => $smr_no);
}

function commit_site_material_return($order_name){
    $smr = get_session_variable($order_name);
    $asa_msg = save_site_material_return($smr->line_items, $smr->to_location, $smr->tran_date, $smr->reference, $smr->comment, $smr->from_project_id, 
                                         $smr->to_project_id, $smr->trans_type, $smr->trans_no, $smr->row_state, $smr->company_code, $smr->employee_code);
        
    if($asa_msg['success'] !== true){
        display_error($asa_msg['message']);  
    }else{
        $trans_no = $asa_msg['tran_no'];
        new_doc_date($_POST['tran_date']);
        $smr->clear_site_material_return_items();
        unset($smr);
        unset($_POST['previous_selected_id']);
        return $trans_no;
    }
}

function save_site_material_return_detail($row_id, $smr_no, $stock_id, $quantity, $standard_cost, $tran_unit_cost, $tran_unit, $tran_qty, $conversion_factor, 
                                              $from_task_id, $to_task_id, $from_project_site_id, $to_project_site_id, $pri_line_id){
       
    if(isset($row_id) && $row_id > 0){
        return update_existing_site_material_return_details($row_id, $smr_no, $quantity, $standard_cost, $tran_unit_cost, $tran_unit, $tran_qty, $conversion_factor, 
                                                            $from_task_id, $to_task_id, $from_project_site_id, $to_project_site_id, $pri_line_id);
    }else{
        return add_site_material_return_detail($smr_no, $stock_id, $quantity, $standard_cost, $tran_unit_cost, $tran_unit, $tran_qty, $conversion_factor, $from_task_id, 
                                               $to_task_id, $from_project_site_id, $to_project_site_id, $pri_line_id);
    }
}

//--------------------------------------------------------------------------------------------------

function line_start_focus(){
    global $Ajax;
    $Ajax->activate('items_table');
    set_focus('_stock_id_edit');
}

//-----------------------------------------------------------------------------------------------

function handle_new_site_material_return_order($order_name){
    if(isset($_SESSION[$order_name])){
        unset($_SESSION[$order_name]);
    }

    $_SESSION[$order_name] = new site_material_returns_cart(ST_SITE_MATERIAL_RETURN);
    $_POST['tran_date'] = new_doc_date();
    if(!is_date_in_fiscalyear($_POST['tran_date']))
        $_POST['tran_date'] = end_fiscalyear();
    $_SESSION[$order_name]->tran_date = $_POST['tran_date'];	
}

//-----------------------------------------------------------------------------------------------

function handle_load_existing_site_material_return_order($order_name, $order_no){
    if(isset($_SESSION[$order_name])){
        unset($_SESSION[$order_name]);
    }

    $_SESSION[$order_name] = new site_material_returns_cart(ST_SITE_MATERIAL_RETURN, $order_no);

    if(!is_date(($_SESSION[$order_name]->tran_date))){
        $_POST['tran_date'] = new_doc_date();
        if(!is_date_in_fiscalyear($_POST['tran_date']))
            $_POST['tran_date'] = end_fiscalyear();
        $_SESSION[$order_name]->tran_date = $_POST['tran_date'];	
    }
}

//-----------------------------------------------------------------------------------------------

function check_inventory_adjustment_request_item_data(&$order){
    if(isset($_POST['AddItem'])){
        $slected_line = count($order->line_items) -1;
    }else{
        $slected_line = $_POST['previous_selected_id'];
    }

    if(!($order->line_items[$slected_line]->tran_qty > 0)){
        display_error(_("The quantity entered is negative or invalid."));
        set_focus('tran_qty');
        return false;
    }
    
    if(!($order->line_items[$slected_line]->tran_qty > 0)){
        display_error(_("The quantity entered is negative or invalid."));
        set_focus('tran_qty');
        return false;
    }

    if($order->line_items[$slected_line]->from_task_id <= 0 ){
        display_error(_("Please select a from budget."));
        set_focus('from_task_id');
        return false;
    }
    
    if($order->line_items[$slected_line]->to_task_id <= 0 ){
        display_error(_("Please select a to budget."));
        set_focus('to_task_id');
        return false;
    }
    
    if(!($order->line_items[$slected_line]->user_entered_tran_unit_cost > 0 )){
        display_error(_("Unit cost should be greater than zero."));
        set_focus('user_entered_tran_unit_cost');
        return false;
    }
    
    return true;
}

//-----------------------------------------------------------------------------------------------

function handle_update_site_material_return_item($order_name){  
    $smr_cart = get_session_variable($order_name);
    copy_to_cart_for_save_site_material_return_header($smr_cart);
    
    $inv_adj = &$smr_cart;
    $line_no = $_POST['previous_selected_id'];
    $alternate_unit = get_convertion_factor($_POST['tran_unit'], $_POST['stock_id']);
    $conversion_factor = $alternate_unit['convertion_factor']; 
    if(!isset($_POST['pri_line_id'])){ $_POST['pri_line_id'] = 0; }

    $inv_adj->update_site_material_return_cart_item($line_no, input_num('tran_qty')*$conversion_factor, input_num('std_cost'), $_POST['tran_unit'], input_num('tran_qty'), 
                                                    $conversion_factor, $_POST['from_project_site_id'], $_POST['to_project_site_id'], $_POST['from_task_id'], 
                                                    $_POST['to_task_id'], input_num('user_entered_tran_unit_cost'), $_POST['pri_line_id']);

    $lot_details = get_selected_lot_serial_info('guid', $inv_adj->line_items[$line_no]); 
    $inv_adj->line_items[$line_no]->lot_details = $lot_details;

    if(!check_inventory_adjustment_request_item_data($smr_cart)){
        $_POST['Edit'.$line_no] = 1;
        return;
    }
 
    $reth = can_commit_site_material_return($order_name);
    if($reth["success"] !== true){
        $_POST['Edit'.$line_no] = 1; // Stay in the editing line
        display_error($reth["message"]);
        return false;
    }
    
    return commit_site_material_return($order_name); 
}

//-----------------------------------------------------------------------------------------------

function handle_delete_site_material_return_item($order_name, $id){
    $row_id = $_SESSION[$order_name]->line_items[$id]->row_id;
    $trans_no = $_SESSION[$order_name]->trans_no;

    $reth = can_commit_site_material_return($order_name);
    if($reth["success"] !== true){
        $id = find_submit('Delete');
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        return $reth;
    }
    
    return delete_site_material_return_details_record($trans_no, $row_id);
}

//-----------------------------------------------------------------------------------------------

function handle_new_site_material_return_item($cart){
    $smr_cart = get_session_variable($cart);
    copy_to_cart_for_save_site_material_return_header($smr_cart);

    $conversion_factor = 1;
    $alternate_unit = get_convertion_factor($_POST['tran_unit'], $_POST['stock_id']);
    if (isset($alternate_unit['convertion_factor']) && strlen($alternate_unit['convertion_factor']) > 0) {
        $conversion_factor = $alternate_unit['convertion_factor'];   
    }
    $submitted_item_array_index = find_submit('Edit');
        
    $status = add_site_material_return_to_order($smr_cart, $_POST['stock_id'], input_num('qty'), input_num('std_cost'), $_POST['tran_unit'], input_num('tran_qty'), 
                                                $conversion_factor, $_POST['from_project_site_id'], $_POST['to_project_site_id'], $_POST['from_task_id'], $_POST['to_task_id'],
                                                input_num('user_entered_tran_unit_cost'), $_POST['pri_line_id'], $submitted_item_array_index);
    
    if($status !== true){
        return 0;
    }
    
    $reth = can_commit_site_material_return($cart);
    if($reth["success"] !== true){
        $id = find_submit('Edit');
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        display_error($reth["message"]);
        return false;
    }
    
    if(!check_inventory_adjustment_request_item_data($smr_cart)){
        return false;
    }
    
    set_line_ref($smr_cart, count($smr_cart->line_items) -1);
    $lot_details = get_selected_lot_serial_info(null, count($smr_cart->line_items) - 1); 

    if(isset($lot_details) && $lot_details != ""){
//        count($smr_cart->line_items)->lot_details = $lot_details;    // commented by Loshan due to invalid php code on 2025-06-27
    }

    return commit_site_material_return($cart); 
}

function add_site_material_return_to_order(&$order, $new_item, $new_item_qty, $standard_cost, $tran_unit, $tran_qty, $conversion_factor, $from_project_site_id, 
                                            $to_project_site_id, $from_task_id, $to_task_id, $user_entered_tran_unit_cost, $pri_line_id, $submitted_item_array_index){
    $line_no = 0;
    if (is_array($order->line_items)) {
        $line_no = count($order->line_items);
    }
    
    return $order->add_site_material_return_to_cart($line_no, $new_item, $new_item_qty, $standard_cost, $tran_unit, $tran_qty, $conversion_factor, 
                                                    $from_project_site_id, $to_project_site_id, $from_task_id, $to_task_id, $user_entered_tran_unit_cost, $pri_line_id, 
                                                    $submitted_item_array_index);
}

function handle_save_site_material_return_header($cart){
    $smr_cart = get_session_variable($cart);
    copy_to_cart_for_save_site_material_return_header($smr_cart);
    
    $reth = can_commit_site_material_return($cart);
    if($reth["success"] !== true){
        $id = find_submit('Edit');
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        display_error($reth["message"]);
        return $smr_cart->trans_no;
    }
    
    return commit_site_material_return($cart); 
}

function handle_save_and_process_site_material_return($order_name){
    
    global $loc_notification, $path_to_root, $Refs;
    $type = ST_SITE_MATERIAL_RETURN;
    $current_user = $_SESSION['wa_current_user']->user;
    
    $smr_header = get_session_variable($order_name);
    copy_to_cart_for_save_site_material_return_header($smr_header);
    
    $reth = can_commit_site_material_return($order_name);
    if($reth["success"] !== true){
        return $reth;
    }
    
    begin_transaction();

    $msg = update_site_material_return_header($smr_header->trans_no, $smr_header->tran_date, $smr_header->reference, $smr_header->to_location, 
                                              $smr_header->from_project_id, $smr_header->to_project_id, $smr_header->comment, $smr_header->row_state, $smr_header->company_code,
                                              $smr_header->employee_code);
    if($msg['success'] !== true){
        cancel_transaction();
        return $msg;
    }else{
        $order_no = $msg["trans_no"];
    }
    
    load_existing_or_new_site_material_return_order($order_no, $order_name);
    $smr_cart = get_session_variable($order_name);
    
    if($loc_notification == 1){
        include_once($path_to_root ."/inventory/includes/inventory_db.inc");
        $st_ids = array();
        $st_names = array();
        $st_num = array();
        $st_reorder = array();
    }   
    
    foreach($smr_cart->line_items as $line_item){
        if($loc_notification == 1){
            $loc = calculate_reorder_level($smr_cart->from_location, $line_item, $st_ids, $st_names, $st_num, $st_reorder);
        }

        if($line_item->tran_qty > 0){
            $receiving_item_base_unit_cost = $line_item->user_entered_tran_unit_cost / $line_item->conversion_factor;
            $receiving_qty = $line_item->tran_qty * $line_item->conversion_factor;
            
            $qoh = get_qoh_on_date($line_item->stock_id);
            $standard_cost = $line_item->standard_cost;
            
            add_stock_move($type, $line_item->stock_id, $order_no, $smr_cart->to_location, $smr_cart->tran_date, $smr_cart->reference, 
                                                $receiving_qty, $receiving_item_base_unit_cost, 0, 1, 0, 0, '', 
                                                $line_item->tran_unit, $line_item->tran_qty, $line_item->conversion_factor, 0, $line_item->to_project_site_id, 
                                                $line_item->row_id, $smr_header->to_project_id);
            
            
            $qoh = $qoh >= 0 ? $qoh : 0;
            $new_item_total_value = $line_item->tran_qty * $line_item->user_entered_tran_unit_cost;
            $stock_item_new_standard_cost = (($qoh * $standard_cost) + $new_item_total_value) / ($qoh + ($line_item->tran_qty * $line_item->conversion_factor));
            
            $stk_item = get_stock_item_edit_info($line_item->stock_id);
            $new_material_cost = $stock_item_new_standard_cost - ($stk_item['labour_cost'] + $stk_item['overhead_cost']);
            $new_material_cost = $new_material_cost >= 0 ? $new_material_cost : 0;
            update_stock_item_material_cost($line_item->stock_id, $new_material_cost);
            
            $ailqdm_msg2 = add_item_line_quantity_detail_movements($type, $order_no, $smr_cart->from_location, $smr_cart->tran_date, $line_item, true, '');
            if($ailqdm_msg2['success'] !== true){
                cancel_transaction();
                return array("success" => $ailqdm_msg2['success'], "tran_no" => $order_no, "message" => $ailqdm_msg2['message']);
            }
        }
    }
    
    
    add_audit_trail($type, $order_no, $smr_cart->tran_date);

    $mr_details = get_site_material_return_details($order_no);
    $mr_details_array = array();
    while($myrow = db_fetch($mr_details)){
        if($myrow['tran_qty'] > 0){
            $a['row_id'] = $myrow['id'];
            $a['stock_id'] = $myrow['stock_id'];
            $a['task_id'] = $myrow['from_task_id'];
            $a['requested_qty'] = $myrow['qty'];
            $a['high_value_item'] = 0;
            $a['reference_cost'] = $myrow['standard_cost'];
            $a['standard_cost'] = $myrow['standard_cost'];
            $a['total_issued_qty'] = 0;
            $a['qty'] = $myrow['qty'];

            $mr_details_array[] = $a;
        }
    }
  
    $mr_tasks_summary = calculate_task_remaining_totals($mr_details_array);

    $apc_msg = remove_costs_from_tasks($type, $order_no, $mr_tasks_summary, $current_user);
    if($apc_msg['success'] !== true){
        cancel_transaction();
        return array("success" => $apc_msg['success'], "tran_no" => $order_no, "message" => $apc_msg['message']);
    }
    
    $mi_details = get_site_material_return_details($order_no);
    $mi_details_array = array();
    while($myrow = db_fetch($mi_details)){
        if($myrow['tran_qty'] > 0){
            $b['row_id'] = $myrow['id'];
            $b['stock_id'] = $myrow['stock_id'];
            $b['task_id'] = $myrow['to_task_id'];
            $b['requested_qty'] = $myrow['qty'];
            $b['high_value_item'] = 0;
            $b['reference_cost'] = $myrow['standard_cost'];
            $b['standard_cost'] = $myrow['standard_cost'];
            $b['total_issued_qty'] = 0;
            $b['qty'] = $myrow['qty'];

            $mi_details_array[] = $b;
        }
    }
    
    $mi_tasks_summary = calculate_task_remaining_totals($mi_details_array);
    $cct_msg = charge_cost_to_tasks($type, $order_no, $mi_tasks_summary, $current_user);
    
    if($cct_msg['success'] !== true){
        cancel_transaction();
        return array("success" => $cct_msg['success'], "tran_no" => $order_no, "message" => $cct_msg['message']);
    }
    
    $status_msg = update_site_material_return_header_status($order_no, AS_NEW, AS_PROCESSED);
    if($status_msg['success'] !== true){
        cancel_transaction();
        return array("success" => $status_msg['success'], "tran_no" => $order_no, "message" => $status_msg['message']);
    }
    
    commit_transaction();
    return array("success" => true, "tran_no" => $order_no, "message" => "Site material return #$order_no has been processed.");
}

function copy_to_cart_for_save_site_material_return_header($cart){
    $cart->reference = $_POST['ref'];
    $cart->to_location =  $_POST['to_location'];
    $cart->tran_date =  $_POST['tran_date'];
    $cart->from_project_id =  $_POST['from_project_id'];
    $cart->to_project_id =  $_POST['to_project_id'];
    $cart->comment =  $_POST['comment'];
    $cart->company_code =  $_POST['company_code'];
    $cart->employee_code =  $_POST['employee_code'];
}

function load_existing_or_new_site_material_return_order($order_no=0, $order_name=''){
    if($order_no > 0){
        $id = find_submit("Edit");
        if(!(isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] > -1 && $id == $_POST['previous_selected_id'])){
//            if(isset($_SESSION[$order_name]->trans_no) && $order_no != $_SESSION[$order_name]->trans_no){
//                handle_load_existing_site_material_return_order($order_name, $order_no);
//            }elseif(!(isset($_SESSION[$order_name]))){
//                handle_load_existing_site_material_return_order($order_name, $order_no);
//            }else{
//                handle_load_existing_site_material_return_order($order_name, $order_no);
//            }
             handle_load_existing_site_material_return_order($order_name, $order_no);
        }
        else{
            handle_load_existing_site_material_return_order($order_name, $order_no);
        }
    }else{
        handle_new_site_material_return_order($order_name);
    }
}

function get_purchase_requistion_issue_item_tran_unit_cost_details($stock_id, $std_cost, $conversion_factor, &$tran_unit_cost, &$pri_line_id){
    $latest_pr_issue_cost = 0;

    $l_pr_i_cost = get_latest_purchase_requistion_issue_item_unit_cost($stock_id);

    while($lprc_row = db_fetch($l_pr_i_cost)){
        if($lprc_row['unit_cost'] > 0){
            $latest_pr_issue_tran_unit_cost = $lprc_row['unit_cost'] * $conversion_factor;
            $tran_unit_cost = $latest_pr_issue_tran_unit_cost;
//            $_POST['user_entered_tran_unit_cost'] = $latest_pr_issue_tran_unit_cost;
            $pri_line_id = $lprc_row['id'];
//            $_POST['pri_line_id'] = $pri_line_id;
//            hidden("pri_line_id", $pri_line_id);
            break;
        }
    }

    if(!($latest_pr_issue_cost > 0)){
        $tran_unit_cost = $std_cost * $conversion_factor;
        $pri_line_id = 0;
//        $_POST['user_entered_tran_unit_cost'] = $std_cost * $conversion_factor;
//        $_POST['pri_line_id'] = 0;
//        hidden("pri_line_id", 0);
    }
}
            
//---------------------------------------------------------------------------------

function display_site_material_return_items($title, &$order){
    global $Ajax;
    
    $id = find_submit('Edit');
    if(list_updated("tran_unit")){
        if(isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] !== $id){
            if(!($id > 0)){
                hidden("Edit".$_POST['previous_selected_id'], $_POST['previous_selected_id']);
                $id = $_POST['previous_selected_id'];
                hidden("Edit$id", $id);
                $_POST["Edit$id"] = $line_no = $id;
            }
        }
    }

    display_heading($title);
//    br();
    $Ajax->activate('items_table');
    div_start('items_table');
    
        start_table(TABLESTYLE, "width=98%");
            $th = array(_("ID"), _("Item Code"), _("Item Description"), _("Unit"), _("Quantity"), _("Unit Cost"), _("From Budget"), _("To Budget"), _("From Site"), 
                        _("To Site"), _("Total"), "", "");
//            if(count($order->line_items) && $order->status !== AS_PROCESSED){
//                $th[] = '';
//                $th[] = '';
//            }

            table_header($th);
            $total = 0;
            $k = 0;  //row colour counter

            $id = find_submit('Edit');
            
            if(isset($order->line_items) && count($order->line_items) > 0){
                foreach($order->line_items as $line_no => $stock_item){
                    $total += ($stock_item->user_entered_tran_unit_cost * $stock_item->tran_qty);

                    if($id != $line_no){
                        alt_table_row_color($k);
                            label_cell($stock_item->row_id, "align=center");
                            view_stock_status_cell($stock_item->stock_id);
                            label_cell($stock_item->item_description);
                            label_cell($stock_item->alternate_unit_name);
                            qty_cell($stock_item->tran_qty, false, get_qty_dec($stock_item->stock_id));
                            amount_decimal_cell($stock_item->user_entered_tran_unit_cost);
                            label_cell($stock_item->from_task_description);
                            label_cell($stock_item->to_task_description);
                            label_cell($stock_item->from_project_site_description);
                            label_cell($stock_item->to_project_site_description);
                            amount_cell($stock_item->user_entered_tran_unit_cost * $stock_item->tran_qty);

//                            if(isset($order->status) && $order->status !== AS_PROCESSED){
                                edit_button_cell("Edit$line_no", _("Edit"), _('Edit site material return line'));
                                delete_button_cell("Delete$line_no", _("Delete"), _('Remove line from site material return'));
//                            }
                        end_row();

                    }else{
                        site_material_return_item_edit_controls($order, $line_no);
                    }
                }
            }

            if($id == -1){
                site_material_return_item_edit_controls($order);
            }

            start_row();
                label_row(_("Total:"), number_format2($total,user_price_dec()), "align=right colspan=10", "align=right");
            end_row();

        end_table();
    div_end();
}
