<?php

function display_daily_tool_return_header($dti_trans_no, $type, $status=true) {
    global $Refs;
    
        $dti_header = get_daily_tool_issue_header_type_trans_no(ST_DAILY_TOOL_ISSUE, $dti_trans_no);
            $user_id = $_SESSION['wa_current_user']->user;
            $cap = can_access_project($dti_header['project_id'], $user_id);
                if ($cap['success'] !== true) {
                    display_error($cap["message"]);
                    set_focus('project_id');
                    display_footer_exit();
                    exit;
                } 

        div_start('nsit_header');
  
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                start_table(TABLESTYLE2);  
                    table_section(1, "50%");

                        label_row("Issue Trans #:", get_asset_trans_view_str(ST_DAILY_TOOL_ISSUE, $dti_header['trans_no']), "class='tableheader2'");  
                        label_row("Project:", $dti_header['project_description'], "class='tableheader2'");   
                        $_POST['project_id'] = $dti_header['project_id'];
                        hidden('project_id', $dti_header['project_id']);
                        label_row("Issued Date:", sql2date($dti_header['tran_date']), "class='tableheader2'");   
                        
                    table_section(2, "50%");
                        label_row("Issue Location:", $dti_header['location_name'], "class='tableheader2'");   
                        $gc_name = get_group_company_name($dti_header['company_code']);
                            label_row(_("Group Company:"), $gc_name, "class='tableheader2'");  
                        
                        global $approval_statuses;
                        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $dti_trans_no."&source_type_id=".ST_DAILY_TOOL_ISSUE, "Approval Status");
                        label_row($s, $approval_statuses[$dti_header['approval_status']], "class='tableheader2'");

                end_table();
            end_outer_table(2); // outer table
            
            
            $_POST['reference'] = $Refs->get_next($type);            
            $_POST['approval_status'] = 0;
            
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                table_section(1, "40%");
                    text_row("Reference:", 'reference', $Refs->get_next($type), null, null);   
                    if (! isset($_POST['location'])) {
                        $_POST['location'] = $dti_header['loc_code'];
                    }
                    asset_locations_list_row("Return Location:", 'location', null, '', false);      

                table_section(2, "20%");
                    date_row("Date:", 'tran_date');

                table_section(3, "40%");
                    textarea_row("Comment:", 'comments', null, 35, 2); 
            end_outer_table(2); // outer table
    
        div_end();
}

function display_daily_tool_return_details($dti_trans_no, $status=true) { 
    global $Ajax;
    
    $header = get_daily_tool_issue_header_type_trans_no(ST_DAILY_TOOL_ISSUE, $dti_trans_no);
    
    display_heading("Details");
    
    $Ajax->activate('dir_details');
    div_start('dir_details');
    
        start_table(TABLESTYLE, "width=99%");

            $th = array(_("ID"), _("Tool"), _("Issued Qty"), _('Budget'), _('Person'), _('Returned Qty'), _('Returning Qty'), _('Job'), 
                        _('Comment'), _(""));  
            table_header($th);

            $k = 0; //row colour counter
                $result = get_daily_tool_issue_and_return_details($dti_trans_no, 0);      
                    while ($row = db_fetch($result)) {
                        alt_table_row_color($k);
                            $id = $row['id'];

                            label_cell($id, 'align=center');
                            label_cell($row["asset_description"]);
                            $issued_qty = $row["quantity"];
                            label_cell(number_format($issued_qty, 2), 'align=right');
                            label_cell($row["task_description"]);
                            label_cell(get_group_company_employee_formatted_long_name($header["company_code"], $row["employee_code"]));  
                            $returned_quantity = $row["returned_quantity"];
                            label_cell(number_format($returned_quantity, 2), 'align=right');
                            
                            amount_cells("", "quantity_$id", null, null, null, 2);
                            
                            if (! isset($_POST["site_id_$id"])) {
                                $_POST["site_id_$id"] = $row['site_id'];
                            }
                            project_sites_list_cells("", "site_id_$id", $_POST['project_id'], null, '', false); 
                            text_cells_ex('', "line_comment_$id", 30, 400, null, 'Comment');       

                            check_cells('', "checked_$id", null, false, false, 'align=center'); 

                        end_row();        
                    }

        end_table(3);
    
    div_end();
}

function can_process_daily_tool_return_header($dti_trans_no, $type) {
    global $Refs, $systypes_array;
    
    $dti_header = get_daily_tool_issue_header_type_trans_no(ST_DAILY_TOOL_ISSUE, $dti_trans_no);
        if (! ($dti_header['approval_status'] == AS_APPROVED)) {
            $set_focus = '';
            $message = ($systypes_array[ST_DAILY_TOOL_ISSUE]." record is not approved. Please approve it first.");
            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, 0);
        if ($ref_msg) {
            $message = $ref_msg;
            $set_focus = 'reference';
            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);
    }
    
    $issued_date = sql2date($dti_header['tran_date']);
    $return_date = $_POST['tran_date'];
    if (date1_greater_date2($issued_date, $return_date)) {
        $message = "Returning date cannot be before the issuing date.";
        $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);
    }
    
        $row_state = $dti_header['row_state'];
    
    return array("success" => true, 'row_state' => $row_state, "message" => "");    
}

function can_process_daily_tool_issue_lines($dti_trans_no) {
    $selected_lines_count = 0;
        $result = get_daily_tool_issue_and_return_details($dti_trans_no, 0);        
            while ($row = db_fetch($result)) {
                $id = $row['id'];
                
                if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                    
                    $quantity = input_num("quantity_$id");

                    if (! ($quantity > 0)) {
                        $message = "Line #$id quantity should be greater than zero.";
                        $set_focus = "quantity_$id";
                        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
                    }
                    
                    // check max returnable qty

                    $returned_quantity = get_daily_tool_issue_line_returned_total($id);
                        $max_returnable_qty = ($row["quantity"] - abs($returned_quantity));
                        
                        if ($quantity > $max_returnable_qty) {
                            $message = "Line #$id : Allowed maximum returnable quantity is $max_returnable_qty.";
                            $set_focus = "quantity_$id";
                            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
                        }
                        
                    $selected_lines_count++;
                }
            }
            
            if (! ($selected_lines_count > 0)) {
                $message = "You should select at least one line before saving.";
                $set_focus = "";
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
            }

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

function save_daily_tool_return_header($dti_trans_no, $type) {
    $dti_hd = get_daily_tool_issue_header_type_trans_no(ST_DAILY_TOOL_ISSUE, $dti_trans_no);
    
        return write_daily_tool_return_header_by_type_trans_no($type, $dti_trans_no, $_POST['reference'], $dti_hd['project_id'], $dti_hd['company_code'], 
                                                               $_POST['location'], $_POST['comments'], $_POST['tran_date']); 
}

function save_daily_tool_return_lines($trans_no, $type, $dti_trans_no) {    
    global $systypes_array;
        
        $result = get_daily_tool_issue_and_return_details($dti_trans_no, $trans_no);      
            while ($row = db_fetch($result)) {
                $id = $row['id'];
                
                if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                    
                    $asset_id = $row['asset_id'];
                    $quantity = -input_num("quantity_$id");
                    $site_id = $_POST["site_id_$id"];
                    $line_comment = $_POST["line_comment_$id"];
                    
                    $af_no = write_daily_tool_issue_line($trans_no, 0, $type, $_POST['location'], $asset_id, $row['rate_category_id'], $row['rate'], 
                                                         $quantity, $row['employee_code'], $site_id, $line_comment, $row['task_id'], $id); 

                        if (! ($af_no > 0)) {
                            $ln_ms = $systypes_array[$type]." line #$id could not be saved.";
                            return array("success" => false, 'trans_no' => $trans_no, "message" => $ln_ms);
                        } 
        
                        update_daily_tool_issue_line_returned_total($id);
                }
            }

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

function save_daily_tool_return($dti_trans_no, $type) {
    global $systypes_array;
    
    $hd_msg = can_process_daily_tool_return_header($dti_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_lines($dti_trans_no);
        if ($ln_msg['success'] !== true) {
            if (isset($ln_msg["focus_to"])) {
                set_focus($ln_msg["focus_to"]);            
            }
            
            return array("success" => false, "message" => $ln_msg['message']);        
        }
       
        begin_transaction();

            $trans_no = save_daily_tool_return_header($dti_trans_no, $type);
                if (! ($trans_no > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not be saved ".$systypes_array[$type]." header.");
                }

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

        commit_transaction();

        meta_forward($_SERVER['PHP_SELF'], "SavedID=$trans_no"); 
}

function approve_daily_tool_return($trans_no, $type, $dti_trans_no) {
    global $systypes_array;
    
        $tran_date = $_POST['tran_date'];
        
        $ap_msg = add_daily_tool_retrun_moves($trans_no, $type, $tran_date);
            if ($ap_msg["success"] !== true) {          
                return $ap_msg;
            } 

        $af_row = update_daily_tool_return_header_approval_status($trans_no, AS_NEW, AS_APPROVED);
            if (! ($af_row > 0)) {          
                return array("success" => false, 'trans_no' => $trans_no, "message" => "Could not be updated approval status.");
            } 
            
        $dti_hd = get_daily_tool_issue_header_type_trans_no(ST_DAILY_TOOL_ISSUE, $dti_trans_no);
            $issued_date = sql2date($dti_hd['tran_date']);
            
            $num_dates_ = date_diff2($tran_date, $issued_date, 'd');
            $num_dates = ($num_dates_ > 0) ? $num_dates_ : 1;
                
            // budget update 
            $dtr_details_array = array();
            
            $result = get_daily_tool_issue_details($trans_no, $type);      
                while ($row = db_fetch($result)) {
                    $qty = abs($row['quantity']);
                    
                    $b['row_id'] = $row['id'];
                    $b['asset_id'] = $row['asset_id'];
                    $b['task_id'] = $row['task_id'];
                    $b['requested_qty'] = $qty;
                    $b['high_value_item'] = 0;

                    $standard_cost = $row['rate'] * $num_dates;
                    $b['reference_cost'] = $standard_cost; 
                    $b['standard_cost'] = $standard_cost;
                    $b['charging_cost'] = $standard_cost;
                    $b['total_issued_qty'] = $qty;
                    $b['qty'] = $qty;

                        $dtr_details_array[] = $b;
                }

            $mi_tasks_summary = calculate_task_remaining_totals($dtr_details_array);
            $created_by = $_SESSION['wa_current_user']->user;
    
            $mtrec_msg = charge_cost_to_tasks($type, $trans_no, $mi_tasks_summary, $created_by);
                if ($mtrec_msg['success'] !== true) {
                    return array("success" => $mtrec_msg['success'], "tran_no" => $trans_no, "message" => $mtrec_msg['message']);
                }
                
        return array("success" => true, 'trans_no' => $trans_no, "message" => $systypes_array[$type].' has been approved.');
}

function add_daily_tool_retrun_moves($trans_no, $type, $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 = abs($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 view_daily_tool_return_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("Issue #:", get_asset_trans_view_str(ST_DAILY_TOOL_ISSUE, $row['source_id']), "class='tableheader2'");
                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_return_details($type, $trans_no) {
    start_table(TABLESTYLE, "width=98%");

        $th = array(_("ID"), _("Tool"), _("Qty"), _('Budget'), _('Rate Category'), _('Rate'), _('No. Days Used'), _('Cost'), _('Employee'), _('Job'), 
                    _('Comment'), _('Issued Line'));  
        table_header($th);
        
        $header = get_daily_tool_return_header_with_issue_header_record_by_return_trans_no($trans_no);
            $issued_date = sql2date($header['iss_tran_date']);
            $returned_date = sql2date($header['tran_date']);
                $num_dates_ = date_diff2($returned_date, $issued_date, 'd');
                $num_dates = ($num_dates_ > 0) ? $num_dates_ : 1;
            
        $k = 0; //row colour counter
            $result = get_daily_tool_issue_details($trans_no, $type);      
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k); 

                        $rate = $row["rate"];
                        $qty = abs($row["quantity"]);
                        $charging_cost = ($rate * $num_dates * $qty);
                        
                        label_cell($row['id'], 'align=center');
                        label_cell($row["asset_description"]);
                        label_cell($qty, 'align=right');
                        label_cell($row["task_description"]);
                        label_cell($row["rate_description"]);
                        label_cell(number_format($rate, 2), 'align=right');
                        label_cell(number_format($num_dates, 2), 'align=right');
                        label_cell(number_format($charging_cost, 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"]));          
                        label_cell($row['source_line_id'], 'align=center');

                    end_row();        
                }

    end_table(3);
}

?>