<?php

function display_daily_item_issue_header($dii_no) {
    global $Refs;
    
    if (isset($_POST['NewIssue']) || isset($_POST['ModifyIssue'])) {
        $type = ST_DAILY_ITEM_ISSUE;
    } 
    
        if ($dii_no > 0) {

            $header = get_daily_item_issue_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['reference'])) {
                $_POST['reference'] = $header['reference'];
            }

            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['group_company_code'])) {
                $_POST['group_company_code'] = $header['group_company_code'];
            }
            
            if (! isset($_POST['movement_type']) || ! ($_POST['movement_type'] > 0)) {
                $_POST['movement_type'] = $header['movement_type'];
            }
            
            if (! isset($_POST['approval_status'])) {
                $_POST['approval_status'] = $header['approval_status'];
            }

        } else {
            $_POST['reference'] = $Refs->get_next($type);            
            $_POST['approval_status'] = 0;
        }
        
        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_daily_item_issue_header($dii_no);
                            label_row("Trans #:", $pd_request['trans_no']);  
                            
                            $reference = $pd_request['reference'];            
                            text_row("Reference:", 'reference', $reference, null, null);            
                        } else {            
                            text_row("Reference:", 'reference', $Refs->get_next($type), null, null);   
                        }

                        if ($dii_no > 0) {
                            label_row("Project:", $_POST['project_description']);   
                        } else {
                            project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true);                         
                        } 
                        
                        date_row("Date:", "tran_date");
                        
                        locations_list_row("Location:", 'location', null, '', false);  

                    table_section(2, "50%");
                        
                        if ($dii_no > 0) {
                            $header = get_daily_item_issue_header_record($dii_no);
                                $type = $header['type'];
                                $_POST['movement_type'] = $header['movement_type'];
                                hidden('movement_type', $header['movement_type']);
                                
                                $movement_type = get_movement_type($header['movement_type']);
                                    label_row(_("Movement Type:"), $movement_type['name']);
                                    
                                    if ($header['linked_field_type'] == IMLF_EMPLOYEE) {
                                        $gc_name = get_group_company_name($header['group_company_code']);
                                            label_row(_("Group Company:"), $gc_name);
                                    }
                            
                                    $_POST['linked_field_type'] = $movement_type['linked_field'];
                                    hidden('linked_field_type', $movement_type['linked_field']);
                                    $_POST['group_company_code'] = $header['group_company_code'];
                                    hidden('group_company_code', $header['group_company_code']);
                        } else {
                            movement_types_list_row(_("Movement Type:"), 'movement_type', $type, null, '', true);
                            
                            $movement_type = get_movement_type($_POST['movement_type']);
                            if(isset($movement_type['linked_field']) && $movement_type['linked_field'] > 0){
                                if ($movement_type['linked_field'] == IMLF_EMPLOYEE) {
                                    group_companies_list_row("Group Company:", 'group_company_code', null, '', true);    
                                }
                            
                                $_POST['linked_field_type'] = $movement_type['linked_field'];
                            }else{
                                $_POST['linked_field_type'] = 0;                                
                            }
                                
                            hidden('linked_field_type', $_POST['linked_field_type']);
                        }
                        
                        if (list_updated('movement_type')) {
                            unset($_POST['linked_field_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_table();
            end_outer_table(2); // outer table
    
        div_end();
}

function display_daily_item_issue_details($dii_no) { 
    global $Ajax, $daily_item_types_array;
    
    display_heading("Details");
    
    $trans_no = $type = -1;
    $header = get_daily_item_issue_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"), _('Budget'), _('Item Cost'), _('Person'), _('Site'), 
                        _('Line Comment'), _(""), _(""));  
            table_header($th);

            $k = 0; //row colour counter
                $result = get_daily_item_issue_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"]);
                            label_cell(number_format($row["tran_qty"], $dec), 'align=right');
                            
                            if ($row['daily_item_type'] == NSIT_COMMENT) {
                                label_cell('No budget required');
                            } else {
                                label_cell($row["task_description"]);
                            }
                            
                            $tran_unit_cost = $row["standard_cost"] * $row["conversion_factor"];
                                if ($tran_unit_cost > 0) {
                                    label_cell(number_format($tran_unit_cost, $dec), 'align=right');
                                } else {
                                    label_cell('');
                                }
                            
                            $lf_name = get_movement_type_linked_field_values($_POST['linked_field_type'], $row['linked_field_id'], $_POST['group_company_code']);
                                label_cell($lf_name["value"]);          
                            
                            label_cell($row["site_description"]);          
                            label_cell(nl2br($row["line_comment"]));          

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

                        end_row();        
                    }

        end_table(3);
    
    div_end();
}

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

    if ($selected_id > 0 && $Mode != 'Delete') {   
        $row = get_daily_item_issue_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['linked_field_id'] = $row['linked_field_id'];
                $_POST['task_id'] = $row["task_id"];
                $_POST['item_cost'] = $row["standard_cost"] * $row["conversion_factor"];
                $_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 (! ($_POST['task_id'] > 0)) {
                $_POST['task_id'] = $row["task_id"];
            }
            if (! ($_POST['item_cost'] > 0)) {
                $_POST['item_cost'] = $row["standard_cost"] * $row["conversion_factor"];
            }
            
            $movement_type = get_movement_type($_POST['movement_type']);
                if ($movement_type['linked_field'] != IMLF_EMPLOYEE) {
                    if (! isset($_POST['linked_field_id']) || ! ($_POST['linked_field_id'] > 0)) {
                        $_POST['linked_field_id'] = $row['linked_field_id'];
                    }
                } else {
                    if (! isset($_POST['linked_field_id']) || ! (strlen($_POST['linked_field_id']) > 0)) {
                        $_POST['linked_field_id'] = $row['linked_field_id'];
                    }
                }
                
            if (! (strlen($_POST['line_comment']) > 0)) {
                $_POST['line_comment'] = $row["line_comment"];
            }
    }
  
    $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);
            
            $movement_type = get_movement_type($_POST['movement_type']);
            
                $linked_field = 0;
                if(isset($movement_type['linked_field']) && $movement_type['linked_field'] > 0){
                    $linked_field = $movement_type['linked_field'];
                }
                switch ($linked_field) {
                    case IMLF_CUSTOMER:
                        customer_list_row(_("Customer:"), 'linked_field_id', null, '');
                        break;
                    case IMLF_SUPPLIER:
                        supplier_list_row(_("Supplier:"), 'linked_field_id', null, '');
                        break;
                    case IMLF_EMPLOYEE:
                        group_company_employees_simple_list_row(_("Employee:"), 'linked_field_id', $_POST['group_company_code'], null, "");    
                        break;
                    case IMLF_VEHICLE:
                        vehicles_list_row(_("Vehicle:"), 'linked_field_id', null, '');
                        break;
                    case IMLF_ASSET:
                        label_row(_("Asset:"), asset_list('linked_field_id', null, ''));
                        break;
                    default:
                        hidden('linked_field_id', 0);
                        break;
                }
                
            if ($_POST['daily_item_type'] == NSIT_NON_STOCK_ITEM || $_POST['daily_item_type'] == NSIT_STOCK_ITEM) {
                tasks_list_row('Budget:', 'task_id', $_POST['project_id'], null, _(''));
            } else {
                $_POST['task_id'] = 0;
                hidden('task_id', 0);
            }
            
            if ($_POST['daily_item_type'] == NSIT_NON_STOCK_ITEM) {
                amount_row("Item Cost:", 'item_cost', null, null, null, 0);
            } else {
                $_POST['item_cost'] = 0;
                hidden('item_cost', 0);
            }
            
            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 build_all_item_units_array() {
    $units_array = array();
    
        $result = get_all_item_units_units();
            while ($row = db_fetch($result)) {
                $units_array[$row['unit_code']] = $row['unit_name'];
            }
            
        return $units_array;
}

function can_process_daily_item_issue_header($dii_no, $approve=false) {
    global $Refs;
    
    if (isset($_POST['NewIssue']) || isset($_POST['ModifyIssue'])) {
        $type = ST_DAILY_ITEM_ISSUE;
    } else {
        $set_focus = '';
        $message = ("Invalid transaction type.");
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    $trans_no = 0;
    $header = get_daily_item_issue_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 (! 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 (! ($_POST['movement_type'] > 0)) {
        $message = ( _('Select a movement type.'));
        $focus = ('movement_type');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
        
    $movement_type = get_movement_type($_POST['movement_type']);
        if ($movement_type['linked_field'] == IMLF_EMPLOYEE) {
            if (! (strlen($_POST['group_company_code']) > 0)) {
                $message = "Please select a group company.";
                $focus = ('group_company_code');
                return array("success" => false, "focus_to" => $focus, "message" => $message);
            }
        } 
        
    if ($approve === true) {
        $header = get_daily_item_issue_header_record($dii_no);
        $lines_count = get_daily_item_issue_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_daily_item_issue_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 (! (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 (! (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);  
    }
    
    $movement_type = get_movement_type($_POST['movement_type']);
        if ($movement_type['linked_field'] > 0) {
            if (! ($_POST['linked_field_id'] > 0)) {
                switch ($movement_type['linked_field']) {
                    case IMLF_CUSTOMER:
                        $message = "Please select a customer.";
                        break;
                    case IMLF_SUPPLIER:
                        $message = "Please select a suppler.";
                        break;
                    case IMLF_EMPLOYEE:
                        $message = "Please select an employee.";
                        break;
                    case IMLF_VEHICLE:
                        $message = "Please select a vehicle.";
                        break;
                    case IMLF_ASSET:
                        $message = "Please select an asset.";
                        break;
                }

                $set_focus = ('linked_field_id');
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
        } 
        
    if ($movement_type['linked_field'] == IMLF_ASSET) {
        $asset_row = get_asset($_POST['linked_field_id']);
            if ($asset_row['type'] == AT_VEHICLE) {
                $message = 'Selected asset is a Vehicle. Only the assets of types "Fixed Asset" and "Tool" are allowed under this Movement Type.';
                $set_focus = 'linked_field_id';
                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 (! ($_POST['task_id'] > 0)) {
            $message = "Please select a budget.";
            $set_focus = 'task_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }
    
    if ($_POST['daily_item_type'] == NSIT_NON_STOCK_ITEM) {
        if (! ($_POST['item_cost'] > 0)) {
            $message = "Item cost should be greater than zero.";
            $set_focus = 'item_cost';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }

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

function can_delete_daily_item_issue_line($dii_no) {
   $header = get_daily_item_issue_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_daily_item_issue_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_daily_item_issue_header(&$dii_no, $type) {
    global $systypes_array;
    
    if ($_POST['linked_field_type'] != IMLF_EMPLOYEE) {
        $_POST['group_company_code'] = '';
    }
            
    $dii_no = write_daily_item_issue_header($type, $dii_no, $_POST['reference'], $_POST['project_id'], $_POST['movement_type'], 
                                             $_POST['linked_field_type'], '', $_POST['group_company_code'], $_POST['location'], $_POST['comments'], 
                                             $_POST['tran_date']); 
    
        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_daily_item_issue_line(&$dii_no, $selected_id) {    
    global $systypes_array;
    
    $standard_cost = 0; $conversion_factor = 1;
    
    $header = get_daily_item_issue_header_record($dii_no);
    $trans_no = $header['trans_no'];
    $type = $header['type'];
    
    $tran_unit = $_POST['tran_unit'];
    
    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);

    } elseif ($_POST['daily_item_type'] == NSIT_NON_STOCK_ITEM) {
        $tran_unit_cost = input_num('item_cost');
        get_convertion_factor2($_POST['stock_id'], $tran_unit, $conversion_factor);
        $standard_cost = $tran_unit_cost/$conversion_factor;
    }
    
    $qty = input_num('tran_qty') * $conversion_factor;
    
    $af_no = write_daily_item_issue_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, get_post('site_id'), $_POST['line_comment'], $_POST['linked_field_id'],
                                         $_POST['task_id']); 
    
        if ($af_no > 0) {
            return array("success" => true, 'trans_no' => $dii_no, "message" => $systypes_array[$header['type']]." line saved.");
        } else {
            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);
        }
}

function save_daily_item_issue(&$dii_no, $selected_id) {
    global $systypes_array;
    
    if (isset($_POST['NewIssue']) || isset($_POST['ModifyIssue'])) {
        $type = ST_DAILY_ITEM_ISSUE;
    } 
    
    $hd_msg = can_process_daily_item_issue_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_daily_item_issue_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_daily_item_issue_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_daily_item_issue_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_daily_item_issue_line($dii_no, $selected_id) {
    $cd_msg = can_delete_daily_item_issue_line($dii_no, $selected_id);
        if ($cd_msg['success'] !== true) {
            return $cd_msg;
        }
        
        begin_transaction();
            delete_daily_item_issue_details_record($selected_id);
        commit_transaction();

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

function save_daily_item_issue_header_only($dii_no, $approve=false) {
    $hd_msg = can_process_daily_item_issue_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"]);
        }
        
        $type = ST_DAILY_ITEM_ISSUE;
    
        begin_transaction();
        
            $msg = save_daily_item_issue_header($dii_no, $type);
                if ($msg["success"] !== true) {          
                    cancel_transaction();

                    return $msg;
                } 

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

                    return $msg;
                } 

            $header = get_daily_item_issue_header_record($dii_no);
            $ap_msg = approve_daily_item_issue($header['trans_no'], $header['type'], $header['tran_date'],$header['project_id']);
                if ($ap_msg["success"] !== true) {          
                    cancel_transaction();

                    return $ap_msg;
                } 

            $af_row = update_daily_item_issue_header_approval_status($dii_no, AS_NEW, AS_APPROVED);
                if (! ($af_row > 0)) {          
                    cancel_transaction();

                    return array("success" => true, 'trans_no' => $dii_no, "message" => "Could not be updated approval status.");
                } 
                 
            // budget update 
            $dii_details_array = $b = array();
            
            $result = get_daily_item_issue_details($header['trans_no'], $type);      
                while ($row = db_fetch($result)) {
                    if ($row['daily_item_type'] != NSIT_COMMENT) {
                        $qty = $row['qty'];
                        $b['row_id'] = $row['trans_id'];
                        $b['stock_id'] = $row['stock_id'];
                        $b['task_id'] = $row['task_id'];
                        $b['requested_qty'] = $row['qty'];
                        $b['high_value_item'] = 0;
                        
                        $standard_cost = $row['standard_cost'];
                        $b['reference_cost'] = $standard_cost; 
                        $b['standard_cost'] = $standard_cost;
                        $b['charging_cost'] = $standard_cost;
                        $b['total_issued_qty'] = $qty;
                        $b['qty'] = $qty;
                        
                        $dii_details_array[] = $b;
                    }
                }

            $mi_tasks_summary = calculate_task_remaining_totals($dii_details_array);
            $created_by = $_SESSION['wa_current_user']->user;
    
            $mtrec_msg = charge_cost_to_tasks($type, $header['trans_no'], $mi_tasks_summary, $created_by);
                if ($mtrec_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => $mtrec_msg['success'], "tran_no" => $header['trans_no'], "message" => $mtrec_msg['message']);
                }

            commit_transaction();

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

function approve_daily_item_issue($trans_no, $type, $tran_date, $project_id) {
    $tran_date_ = sql2date($tran_date);
    
    $result = get_daily_item_issue_details($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"];
            
            if ($row['mb_flag'] == 'B' || $row['mb_flag'] == 'M') {
//            if ($row['daily_item_type'] == NSIT_STOCK_ITEM) {
                $n = add_stock_adjustment_item($trans_no, $row["stock_id"], $row["loc_code"], $tran_date_, $row["reference"], $qty, $standard_cost, '', 
                                          $row["tran_unit"], $tran_qty, $row["conversion_factor"], $type, $row["task_id"], $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_, $row["reference"], $qty, $standard_cost, 
                                   $row["person_id"], $row["visible"], $row["price"], $row["discount_percent"], $row["tran_unit"], $tran_qty, 
                                   $row["conversion_factor"], $row["task_id"], $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_daily_item_issue_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']);
    unset($_POST['linked_field_id']);
}

function view_daily_item_issue_header($type, $trans_no) {
    global $document_approval_statuses;
    
    $row = get_daily_item_issue_header_type_trans_no($type, $trans_no);
    
        start_outer_table(TABLESTYLE2, "width=60%");

            table_section(1, "50%");
                label_row(_("Reference:"), $row['reference'], "class='tableheader2'");
                label_row(_("Porject:"), $row['project_description'], "class='tableheader2'");
                label_row(_("Date:"), sql2date($row['tran_date']), "class='tableheader2'");

            table_section(2, "50%");
                label_row(_("Location:"), $row['location_name'], "class='tableheader2'");
                label_row(_("Movement Type:"), $row['movement_type_name'], "class='tableheader2'");
                label_row(_("Approval Status:"), $document_approval_statuses[$row['approval_status']], "class='tableheader2'");

        end_outer_table(2);

        if (strlen($row['comments']) > 0) {
            start_table(TABLESTYLE2);
                label_row(_("Comment:"), nl2br($row['comments']), "class='tableheader2'");
            end_table(3);
        }
}

function view_daily_item_issue_details($type, $trans_no) {
    global $daily_item_types_array, $inventory_movement_type_linked_fields;
    
    $header = get_daily_item_issue_header_type_trans_no($type, $trans_no);
        $linked_field_type = $header['linked_field_type'];
        $link_f_name = $inventory_movement_type_linked_fields[$linked_field_type];
    
    start_table(TABLESTYLE, "width=98%");

        $th = array(_("ID"), _("Item Type"), _("Description"), _("Unit"), _("Issued Qty"), _("Returned Qty"), _('Budget'), _('Cost'), _("$link_f_name"), 
                    _('Job'), _('Comment'));  
        table_header($th);

        $k = 0; //row colour counter
            $result = get_daily_item_issue_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"]);
                        label_cell(number_format($row["tran_qty"], 2), 'align=right');
                        label_cell(number_format($row["returned_quantity"] / $row["conversion_factor"], 2), 'align=right');
                        
                        if ($row['daily_item_type'] == NSIT_COMMENT) {
                            label_cell('No budget required');
                        } else {
                            label_cell($row["task_description"]);
                        }
                        $tran_unit_cost = $row["conversion_factor"] * $row["standard_cost"];
                            if ($tran_unit_cost > 0) {
                                label_cell(number_format($tran_unit_cost, 2), 'align=right');
                            } else {
                                label_cell('');
                            }
                            
                        $lf_name = get_movement_type_linked_field_values($linked_field_type, $row['linked_field_id'], $header['group_company_code']);
                            label_cell($lf_name["value"]); 
                        
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();        
                }

    end_table(3);
}

function view_daily_item_return_headers_by_request_trans_no($trans_no) {
    $result = get_daily_item_return_headers_by_request_trans_no($trans_no);   
        if (! (db_num_rows($result) > 0)) {
            return;
        }
    
    global $systypes_array;
    
    display_heading("Returns for this ".$systypes_array[ST_DAILY_ITEM_ISSUE]);
    
        start_table(TABLESTYLE, "width=40%");

            $th = array(_("Trans #"), _("Trans Date"), _("Location"));  
            table_header($th);

            $k = 0; //row colour counter
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);
                        label_cell(get_inventory_trans_view_str($row['type'], $row['trans_no']), 'align=center');
                        label_cell(sql2date($row["tran_date"]), 'align=center');
                        label_cell($row['location_name']);
                    end_row();        
                }

        end_table(3);
}

?>