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

function display_asset_transfer_header($asset_tran_req_no){
    global $Refs;
    $atr_header = get_asset_transfer_request_header($asset_tran_req_no);

//    if(!isset($_POST['reference']) && $atr_header['reference'] > 0){
//        if(strlen($atr_header['reference']) > 0){
//            $_POST['reference'] = $atr_header['reference'];
//        }
//    }

    start_outer_table(TABLESTYLE2, "width=60%"); // outer table
        start_table(TABLESTYLE2);  
            table_section(1, "70%");

                label_row("Asset Transfer Request:", "#".$asset_tran_req_no);
                text_row("Reference:", 'reference', $Refs->get_next(ST_ASSET_TRANSFER), null, null);   
                label_row("From Project:", $atr_header['from_project_description']);   
                label_row("To Project:", $atr_header['to_project_description']);                       
                label_row("From Location:", $atr_header['from_location_name']);   
                label_row("To Location:", $atr_header['to_location_name']);   
                
                hidden("from_asset_location", $atr_header['from_asset_location']);   
                hidden("to_asset_location", $atr_header['to_asset_location']);   

            table_section(2, "30%");
                date_row("Date:", "tran_date");
                group_companies_list_row("Company:", 'company_code', null, false, true);
                group_company_employees_simple_list_row("Employee:", 'employee_code', $_POST['company_code'], null, false, false);
                textarea_row("Comment:", 'comment', null, 40, 3); 
                global $approval_statuses;
                $s = get_project_trans_view_str(ST_APPROVAL_LOG, $asset_tran_req_no."&source_type_id=".ST_ASSET_TRANSFER_REQUEST, "Request_Record_Status");
                label_row($s, $approval_statuses[$atr_header['approval_status']]);

                hidden('from_project_id', $atr_header['from_project_id']);
                hidden('to_project_id', $atr_header['to_project_id']);
                
        end_table();
    end_outer_table(1); // outer table
}

function display_asset_transfer_details($asset_tran_no){      
    display_heading("Assets Transfer Details");
    br();
    $result = get_asset_transfer_details($asset_tran_no);      
                              
    start_table(TABLESTYLE, "width=98%");
    $th = array(_("ID"), _("Asset"), _('From Site'), _('To Site'), _("Req. Comment"), _("Value"), 
                _("Req. Quantity"), _("Transferred. Qty"), _("Quantity"), _("Transfer Comment"), _("Line Total"), "");                     

    table_header($th);
    $k = 0; //row colour counter
    $line_total = 0;
            
    while($myrow = db_fetch($result)){
        alt_table_row_color($k);

            label_cell($myrow['id'], "align=center");
            label_cell($myrow["asset_code"]."-".$myrow["asset_description"]."-"."(".$myrow["asset_id"].")");  
            label_cell($myrow["from_site_description"]);          
            label_cell($myrow["to_site_description"]);          
            label_cell($myrow["line_comment"]);
            amount_decimal_cell($myrow["asset_value"]);
            
            amount_cell($myrow["req_quantity"]);
            amount_cell($myrow["transferred_qty"]);
            if(!(isset($_POST["this_quantity_".$myrow['id']]) && $_POST["this_quantity_".$myrow['id']] > 0)){
                $_POST["this_quantity_".$myrow['id']] = ($myrow["req_quantity"] - $myrow["transferred_qty"]);
            }

            if($myrow['req_quantity'] > $myrow["transferred_qty"]){
                amount_cells("", "this_quantity_".$myrow['id']);
                text_cells("", "at_line_comment_".$myrow['id'], null, 50);
            }else{
                label_cell("");
                label_cell("");
            }

            if(isset($_POST["selected_".$myrow["id"]]) && $_POST["selected_".$myrow["id"]] > 0){
                $line_cost = $myrow["asset_value"] * $_POST["this_quantity_".$myrow['id']];
            }else{
                $line_cost = 0;
            }
            
            amount_decimal_cell($line_cost);

            if($myrow['req_quantity'] > $myrow["transferred_qty"]){
                check_cells("", "selected_".$myrow["id"], null, false, false, "align=center");    
            }else{
                label_cell("");
            }

        end_row();
            
        $line_total += $line_cost;
    }    
       
        start_row();
            label_cell("Total:", "colspan=10 align=right");
            amount_cell($line_total, true); 
        end_row();  

    end_table();
    hidden("lines_total", $line_total);
}

function can_process_asset_transfer_header_and_line($asset_tran_req_no){  
    $msg = can_process_asset_transfer_request_header($asset_tran_req_no);
    if($msg['success'] !== true){
        if(isset($msg["focus_to"])){
            set_focus($msg["focus_to"]);            
        }
        return $msg;
    }

    $msg2 = can_process_asset_transfer_line($asset_tran_req_no);
    if($msg2['success'] !== true){
        if(isset($msg2["focus_to"])){
            set_focus($msg2["focus_to"]);            
        }
        return $msg2;
    }

    return array("success" => true, "message" => "", "row_state" => $msg['row_state']);
}

function can_process_asset_transfer_request_header($asset_tran_req_no){  
    global $Refs, $approval_statuses;
    $atr_header["row_state"] = null; 
    
    $atr_header = get_asset_transfer_header($asset_tran_req_no, AS_APPROVED);
    if(!($atr_header['id'] > 0)){
        $aqar_header_status = get_asset_transfer_header($asset_tran_req_no);
        $message = ("Asset Transfer Request record #$asset_tran_req_no status does not allow to transfer assets. 
                     Current Status - ". $approval_statuses[$aqar_header_status['approval_status']]);
        return array("success" => false, "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'], ST_ASSET_TRANSFER, 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(!(strlen($_POST['company_code']) > 0)){
        $message = "Please select a company.";
        $set_focus = 'company_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    if(!(strlen($_POST['employee_code']) > 0)){
        $message = "Please select an employee.";
        $set_focus = 'employee_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
  
    return array("success" => true, "message" => "", "row_state" => $atr_header['row_state']);    
}

function can_process_asset_transfer_line($asset_tran_req_no){
    $slected_any_row= false;
    
    $result = get_asset_transfer_details($asset_tran_req_no);
        while($row = db_fetch($result)){
            if(isset($_POST["selected_".$row["id"]]) && $_POST["selected_".$row["id"]] == true){
                if($row['req_quantity'] < ($row['transferred_qty'] + input_num("this_quantity_".$row['id']))){
                    $message = "(Quantity + Transferred Quantity) should be smaller than or equal to Requested Quantity Line #".$row["id"];
                    $set_focus = "this_quantity_".$row['id'];
                    return array("success" => false, "focus_to" => $set_focus, "message" => $message);
                }
                
                $slected_any_row = true;
            }
        }
    
    if ($slected_any_row !== true) {
        $message = "At least one line should be selected before proccessing.";
        return array("success" => false, "focus_to" => '', "message" => $message);        
    }

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

function save_asset_transfer(&$asset_tran_req_no, $row_state){
    $msg = save_asset_transfer_header($asset_tran_req_no);
        if($msg["success"] !== true){
            return $msg;
        }
    $asset_tran_no = $msg['at_id'];
    
    $result = get_asset_transfer_request_details($asset_tran_req_no);
    while($row = db_fetch($result)){
        if(isset($_POST["selected_".$row["id"]]) && $_POST["selected_".$row["id"]] == true){
            $req = $row['quantity'];
            $tranfred = $row['transferred_qty'];
            $ths = input_num("this_quantity_".$row['id']);
            $tot = $tranfred + $ths;
            if($row['quantity'] < ($row['transferred_qty'] + input_num("this_quantity_".$row['id']))){
                return array("success" => false, 'atr_line_id' => $row["id"], "focus_to" => "this_quantity_".$row['id'] , "message" => "Another user has change quatity.");
            }
                
            $issue_qty = input_num("this_quantity_".$row['id']);
            $aatl_msg = add_asset_transfer_line($asset_tran_no, $row["id"], $row['asset_id'], $issue_qty, 
                                           $row['asset_value'], $_POST["at_line_comment_".$row['id']]); 

            if($aatl_msg['success'] !== true){
                return array("success" => false, 'atr_id' => $asset_tran_no, "message" => $aatl_msg['message']);
            }

            $asset_issue_line_id = $aatl_msg['at_line_id'];
            $msg = update_asset_transfer_detail_line_total($row["id"], $row['row_state']);
            if($msg['success'] !== true){
                return $msg;
            }

            add_asset_move(ST_ASSET_TRANSFER, $asset_tran_no, $asset_issue_line_id, $_POST['reference'], 
                        $_POST['tran_date'], $row['asset_id'], $_POST['from_asset_location'], $row['from_site_id'], 
                        0, -$issue_qty, $_POST['from_project_id']);
            
            add_asset_move(ST_ASSET_TRANSFER, $asset_tran_no, $asset_issue_line_id, $_POST['reference'], 
                        $_POST['tran_date'], $row['asset_id'], $_POST['to_asset_location'], $row['to_site_id'], 
                        0, $issue_qty, $_POST['to_project_id']);
        }
    }
    
    if(check_all_asset_transfer_request_lines_fully_transferred($asset_tran_req_no)){
        $msg = direct_update_document_status(ST_ASSET_TRANSFER_REQUEST, $asset_tran_req_no, AS_COMPLETED, $row_state);
        if($msg['success'] !== true){
            return $msg;
        }
    }

    return array("success" => true, 'atr_id' => $asset_tran_no, "message" => "Asset Transfer #$asset_tran_req_no has been proceed.");
}

function save_asset_transfer_header(&$asset_tran_req_no){  
    $msg = write_asset_transfer_header($asset_tran_req_no, $_POST['reference'], $_POST['company_code'], $_POST['employee_code'], $_POST['tran_date'], 
                                       $_POST['comment'], $_POST['lines_total']);  
    return $msg;
}

function can_delete_asset_transfer_request_details_line($asset_tran_no, $selected_id){
   $arh = get_asset_transfer_header($asset_tran_no);
   
   if($asset_tran_no > 0){
        if(!($arh['approval_status'] == AS_NEW || $arh['approval_status'] == AS_WITH_THE_APPROVER || 
             $arh['approval_status'] == AS_AWAITING_APPROVAL || $arh['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);
        }
    } 
    
    $line_count = get_asset_transfer_request_details_line_count($asset_tran_no);
    if(!($line_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 can_release_asset_transfer_request($asset_tran_no){
    $line_count = get_asset_transfer_request_details_line_count($asset_tran_no);
    if(!($line_count > 0)){
        $message = ("There are no asset transfer request details entered. Can not release this asset transfer request.");
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    $row_state = get_asset_transfer_header($asset_tran_no);
    return array("success" => true, "focus_to" => '', "message" => "", "row_state" => $row_state['row_state']);    
}

function release_asset_transfer_request($asset_tran_no, $row_state){    
    
    $msg = save_asset_transfer_request_header($asset_tran_no, $row_state);
    if($msg['success'] !== true){
        cancel_transaction();
        display_error($msg['message']);
        return $msg;
    } 

    $msg = release_asset_transfer_request_for_approval($asset_tran_no);
    if($msg['success'] !== true){
        cancel_transaction();
        display_error($msg['message']);
        return $msg;
    }
    commit_transaction();
    clear_session_variable("ST_ASSET_TRANSFER_at_no");
    set_session_variable('ST_ASSET_TRANSFER_message', $msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_ATR_No=$asset_tran_no");    
}

?>