<?php

function display_daily_tool_issue_header($trans_no, $type) {
    global $Refs;
    
        if ($trans_no > 0) {

            $header = get_daily_tool_issue_header_type_trans_no($type, $trans_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['company_code'])) {
                $_POST['company_code'] = $header['company_code'];
            }
            
            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 ($trans_no > 0) {
                            $pd_request = get_daily_tool_issue_header_type_trans_no($type, $trans_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 ($trans_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");
                        
                        asset_locations_list_row("Location:", 'location', null, '', false);      

                    table_section(2, "50%");
                        
                        group_companies_list_row("Company:", 'company_code', null, '', true);    
                        textarea_row("Comment:", 'comments', null, 35, 2); 

                        global $approval_statuses;
                        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $trans_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_tool_issue_details($trans_no, $type, $Mode, $selected_id) { 
    global $Ajax;
    
    display_heading("Details");
    
    $Ajax->activate('nsit_details');
    div_start('nsit_details');
    
        start_table(TABLESTYLE, "width=98%");

            $th = array(_("ID"), _("Item Description"), _("Tran Qty"), _("Returned Qty"), _('Budget'), _('Rate Category'), _('Rate'), _('Employee'), 
                        _('Site'), _('Line Comment'), _(''), _(''));  
            table_header($th);
        
            $header = get_daily_tool_issue_header_record_type_trans_no($type, $trans_no);

            $k = 0; //row colour counter
                $result = get_daily_tool_issue_details($trans_no, $type);      
                    while ($row = db_fetch($result)) {
                        if ($selected_id != $row["id"]) {
                            alt_table_row_color($k); 

                                label_cell($row['id'], 'align=center');
                                label_cell($row["asset_description"]);
                                label_cell(number_format($row["quantity"], 2), 'align=right');
                                label_cell(number_format($row["returned_quantity"], 2), 'align=right');
                                label_cell($row["task_description"]);
                                label_cell($row["rate_description"]);
                                label_cell(number_format($row["rate"], 2), 'align=right');
                                label_cell(get_group_company_employee_formatted_long_name($header["company_code"], $row["employee_code"]));          
                                label_cell($row["site_description"]);          
                                label_cell(nl2br($row["line_comment"]));  

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

                            end_row();     
                        } else {
                            start_row();
                                display_daily_tool_issue_details_edit_controls($selected_id, $Mode);
                            end_row();
                        }
                    }
                
                if (! ($selected_id > 0)) {
                    display_daily_tool_issue_details_edit_controls($selected_id, $Mode);
                }

        end_table(3);
    
    div_end();
}

function display_daily_tool_issue_details_edit_controls($selected_id, &$Mode) {
    global $Ajax;
    
    if ($selected_id > 0 && $Mode != 'Delete') {   
        $row = get_daily_tool_issue_details_record($selected_id); 
            if ($Mode == 'Edit') {
                $_POST['asset_id'] = $row["asset_id"];
                $_POST['quantity'] = $row["quantity"];
                $_POST['site_id'] = $row["site_id"];
                $_POST['employee_code'] = $row['employee_code'];
                $_POST['task_id'] = $row["task_id"];
                $_POST['line_comment'] = $row["line_comment"];
            }

            if (! (strlen($_POST['asset_id']) > 0)) {
                $_POST['asset_id'] = $row["asset_id"];
            }
            if (! ($_POST['quantity'] > 0)) {
                $_POST['quantity'] = $row["quantity"];
            }
            if (! ($_POST['task_id'] > 0)) {
                $_POST['task_id'] = $row["task_id"];
            }
            if (! (strlen($_POST['employee_code']) > 0)) {
                $_POST['employee_code'] = $row["employee_code"];
            }
            if (! (strlen($_POST['line_comment']) > 0)) {
                $_POST['line_comment'] = $row["line_comment"];
            }
    }

    echo "<td colspan=10>";
  
        $Ajax->activate("control_tools");    
        div_start('control_tools');
        start_outer_table(TABLESTYLE);
        
            table_section(1);
                if ($selected_id > 0) {        
                    $asset_details = get_asset($_POST['asset_id']);
                    if (isset($asset_details['asset_id']) && $asset_details['asset_id'] > 0) {
                        label_row("Asset:", $asset_details['asset_code']." - ".$asset_details['description']." - "."(".$asset_details['asset_id'].")");
                        hidden('asset_id', $asset_details['asset_id']);
                    } else {
                        label_row("Asset:", '');
                        hidden('asset_id', 0);
                    }
                } else {
                    label_row(_("Asset:"), tool_list('asset_id', null, false, true));
                }

                $rate_description = '';
                $asset_rate = get_tool_rate_category($_POST['asset_id']);
                if (isset($asset_rate['id']) && $asset_rate['id'] > 0) {
                    $rate_description = $asset_rate['rate_description'];
                }
                label_row("Rate Category:", $rate_description);

                $multiple_items = false;
                $asset_details = get_asset($_POST['asset_id']);
                if (isset($asset_details['asset_id']) && $asset_details['asset_id'] > 0) {
                    $multiple_items = $asset_details['multiple_items'];
                }

                $Ajax->activate('quantity');


                if ($multiple_items == true) {            
                    amount_row("Quantity:", 'quantity', null, null, null, 0);
                } else {
                    label_row("Quantity:", 1);
                    hidden('quantity', 1);
                }
                
            table_section(2);

                tasks_list_row(_("Budget:"), 'task_id', $_POST['project_id'], null, _(''), false); 
                group_company_employees_simple_list_row(_("Select an Employee:"), 'employee_code', $_POST['company_code'],'', "", "", false);    
                project_sites_list_row("Job:", 'site_id', $_POST['project_id'], null, '', false); 

            table_section(3);

                textarea_row("Comment:", 'line_comment', null, 35, 2); 

        end_outer_table();
        div_end();

    echo "</td>";

        if ($selected_id > 0) {
            hidden('selected_id', $selected_id);
            button_cell('Update_DTI', _("Update"), _('Confirm changes'), ICON_UPDATE);
            button_cell('Cancel', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
        } else {
            submit_cells('Add_DTI', _("Add Item"), "colspan=2 align=center", _('Add new tool'), true);
        }
}

function can_process_daily_tool_issue_header($trans_no, $type, $approve=false) {
    global $Refs;
    
    $header = get_daily_tool_issue_header_record_type_trans_no($type, $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);
        }
        
        $trans_no = $header['trans_no'];
    } 
    
    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 (! ($trans_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, "set_focus"=>$set_focus, "message"=>$message);
    }
        
    $msg = is_accounting_period_open($_POST['tran_date']);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']);
        $set_focus = ('tran_date');
        return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);
    }
    
              
    if ($_POST['location'] == '') {
        $message = "Please select a location.";
        $set_focus = 'location';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if (! (strlen($_POST['company_code']) > 0)) {
        $message = "Please select a group company.";
        $focus = ('company_code');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
        
    if ($approve === true) {
        $lines_count = get_daily_tool_issue_details_lines_count($trans_no, $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 ($trans_no > 0) {
        $row_state = $header['row_state'];
    }
    
    return array("success" => true, 'row_state' => $row_state, "message" => "");    
}

function can_process_daily_tool_issue_line() {
    if (! ($_POST['asset_id'] > 0)) {
        $message = "Please select a tool.";
        $set_focus = 'asset_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if (! (input_num('quantity') > 0)) {
        $message = "Quantity should be greater than zero.";
        $set_focus = 'quantity';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    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 (! (strlen($_POST['employee_code']) > 0)) {
        $message = "Please select an employee.";
        $focus = ('company_code');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }

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

function can_delete_daily_tool_issue_line($trans_no, $type) {
   $header = get_daily_tool_issue_header_record_type_trans_no($type, $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)){
            $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_tool_issue_details_lines_count($trans_no, $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_tool_issue_header(&$trans_no, $type) {
    $msg = write_daily_tool_issue_header($type, $trans_no, $_POST['reference'], $_POST['project_id'], $_POST['company_code'], $_POST['location'], 
                                         $_POST['comments'], $_POST['tran_date']); 
    
        if ($msg['success'] === true) {
            $trans_no = $msg['trans_no'];
        } 
        
        return $msg;
}

function save_daily_tool_issue_line(&$trans_no, $type, $selected_id) {    
    global $systypes_array;
    
    $asset_rate = get_tool_rate_category($_POST['asset_id']);
        $rate_category_id = $asset_rate['id'];
        $rate = $asset_rate['rate'];
    
    $af_no = write_daily_tool_issue_line($trans_no, $selected_id, $type, $_POST['location'], $_POST['asset_id'], $rate_category_id, $rate, 
                                         input_num('quantity'), $_POST['employee_code'], get_post('site_id'), $_POST['line_comment'], $_POST['task_id']); 
    
        if ($af_no > 0) {
            return array("success" => true, 'trans_no' => $trans_no, "message" => $systypes_array[$type]." line saved.");
        } else {
            if ($selected_id > 0) {
                $ln_ms = $systypes_array[$type]." #$selected_id line could not be updated.";
            } else {
                $ln_ms = $systypes_array[$type]." line could not be saved.";
            }

                return array("success" => false, 'trans_no' => $trans_no, "message" => $ln_ms);
        }
}

function save_daily_tool_issue(&$trans_no, $type, $selected_id) {
    global $systypes_array;

    $hd_msg = can_process_daily_tool_issue_header($trans_no, $type);   
        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_tool_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' => $trans_no, "message" => $ln_msg['message']);        
        }
       
        begin_transaction();

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

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

        commit_transaction();

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

function delete_daily_tool_issue_line($trans_no, $type, $selected_id) {
    $cd_msg = can_delete_daily_tool_issue_line($trans_no, $type);
        if ($cd_msg['success'] !== true) {
            return $cd_msg;
        }
        
        begin_transaction();
            delete_daily_tool_issue_details_record($selected_id);
        commit_transaction();

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

function save_daily_tool_issue_header_only($trans_no, $type, $approve=false) {
    $hd_msg = can_process_daily_tool_issue_header($trans_no, $type, $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"]);
        }
        
        begin_transaction();
        
            $msg = save_daily_tool_issue_header($trans_no, $type);
                if ($msg["success"] !== true) {          
                    cancel_transaction();

                    return $msg;
                } 

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

                    return $msg;
                } 

            $header = get_daily_tool_issue_header_record_type_trans_no($type, $trans_no);
            $ap_msg = approve_daily_tool_issue($trans_no, $type, $header['tran_date']);
                if ($ap_msg["success"] !== true) {          
                    cancel_transaction();

                    return $ap_msg;
                } 

            $af_row = update_daily_tool_issue_header_approval_status($trans_no, $type, AS_NEW, AS_APPROVED);
                if (! ($af_row > 0)) {          
                    cancel_transaction();

                    return array("success" => true, 'trans_no' => $trans_no, "message" => "Could not be updated approval status.");
                } 
                
            commit_transaction();

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

function approve_daily_tool_issue($trans_no, $type, $tran_date) {
    $tran_date_ = sql2date($tran_date);
    
    $header = get_daily_tool_issue_header_record_type_trans_no($type, $trans_no);
    
    $result = get_daily_tool_issue_details($trans_no, $type);      
        while ($row = db_fetch($result)) {
            $quantity = -$row["quantity"];
            
            add_asset_move($type, $trans_no, $row["id"], $header["reference"], $tran_date_, $row["asset_id"], $row["loc_code"], $row["site_id"], 
                           $row["task_id"], $quantity, $header["project_id"]);
        }  
        
            return array("success" => true, 'trans_no' => $trans_no, "message" => "");
}

function clear_daily_tool_issue_details() {
    unset($_POST['asset_id']);
    unset($_POST['employee_code']);
    unset($_POST['quantity']);
    unset($_POST['task_id']);
    unset($_POST['site_id']);
    unset($_POST['line_comment']);
}

function view_daily_tool_issue_header($type, $trans_no) {
    global $document_approval_statuses;
    
    $row = get_daily_tool_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(_("Company:"), get_group_company_name($row['company_code']), "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_tool_issue_details($type, $trans_no) {
    start_table(TABLESTYLE, "width=98%");

        $th = array(_("ID"), _("Tool"), _("Issued Qty"), _("Returned Qty"), _('Budget'), _('Rate Category'), _('Rate'), _('Employee'), _('Job'), 
                    _('Comment'));  
        table_header($th);
        
        $header = get_daily_tool_issue_header_record_type_trans_no($type, $trans_no);

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

                        label_cell($row['id'], 'align=center');
                        label_cell($row["asset_description"]);
                        label_cell(number_format($row["quantity"], 2), 'align=right');
                        label_cell(number_format($row["returned_quantity"], 2), 'align=right');
                        label_cell($row["task_description"]);
                        label_cell($row["rate_description"]);
                        label_cell(number_format($row["rate"], 2), 'align=right');
                        label_cell(get_group_company_employee_formatted_long_name($header["company_code"], $row["employee_code"]));          
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();        
                }

    end_table(3);
}

function view_daily_tool_return_headers_by_issue_trans_no($trans_no) {
    $result = get_daily_tool_return_headers_by_issue_trans_no($trans_no);   
        if (! (db_num_rows($result) > 0)) {
            return;
        }
    
    global $systypes_array;
    
    display_heading("Returns for this ".$systypes_array[ST_DAILY_TOOL_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_asset_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);
}

?>