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

function display_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no){
    global $Refs;
    
    if($asset_qty_ajt_req_no > 0){
        
        $atr_header = get_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no);
        $user_id = $_SESSION['wa_current_user']->user;
        
        $project_id = $_POST['project_id'] = $atr_header['project_id'];
        $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'] = $atr_header['reference'];
        }
        if(!isset($_POST['project_id'])){
            $_POST['project_id'] = $atr_header['project_id'];
        }
        if(!isset($_POST['comment'])){
            $_POST['comment'] = $atr_header['comment'];
        }          
        if(!isset($_POST['location'])){
            $_POST['location'] = $atr_header['asset_location'];
        }
        if(!isset($_POST['tran_date'])){
            $_POST['tran_date'] = sql2date($atr_header['tran_date']);
        }
        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $atr_header['project_description'];
        }
        if(!isset($_POST['approval_status'])){
            $_POST['approval_status'] = $atr_header['approval_status'];
        }
        if(!isset($_POST['is_deduction'])){
            $_POST['is_deduction'] = $atr_header['is_deduction'];
        }
    }else{
        $_POST['reference'] = $Refs->get_next(ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST);            
        $_POST['approval_status'] = 0;
    }
  
    start_outer_table(TABLESTYLE2, "width=70%"); // outer table
        start_table(TABLESTYLE2);  
            table_section(1, "60%");

                if($asset_qty_ajt_req_no > 0){
                    label_row("Asset Quantity Adjustment Request:", "#".$asset_qty_ajt_req_no);
                    $pd_request = get_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no);
                    $reference = $pd_request['reference'];            
                    text_row("Reference:", 'reference', $reference, null, null);            
                }else{            
                    text_row("Reference:", 'reference', $Refs->get_next(ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST), null, null);   
                }
                
                if($asset_qty_ajt_req_no > 0 && get_asset_quantity_adjustment_request_details_line_count($asset_qty_ajt_req_no)){
                    label_row("Project:", $_POST['project_description']);   
                    hidden('project_id', $_POST['project_id']);
                }else{                       
                    project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true);                         
                }           
                asset_locations_list_row("Location:", 'location', null, 'Select an Asset Location', false); 
                yesno_list_row("Deduction:", "is_deduction");

            table_section(2, "40%");
                date_row("Date:", "tran_date");
                textarea_row("Comment:", 'comment', null, 40, 3); 
                global $approval_statuses;
                $s = get_project_trans_view_str(ST_APPROVAL_LOG, $asset_qty_ajt_req_no."&source_type_id=".ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST, "Approval Status");
                label_row($s, $approval_statuses[$_POST['approval_status']]);

//        end_table();
    end_outer_table(1); // outer table
}

function display_asset_quantity_adjustment_request_details($asset_qty_ajt_req_no, $selected_id){  

    display_heading("Assets Quantity Adjustment Request Details");
    br();
    $result = get_asset_quantity_adjustment_request_details($asset_qty_ajt_req_no);      
                              
    start_table(TABLESTYLE, "width=98%");
    $th = array(_("ID"), _("Asset"), _('Site'), _('Budget'), _("Comment"), _("Quantity"), _("Value"), _("Line Total"), "", "");                     

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

    $line_total = 0;
            
    while($myrow = db_fetch($result)){

        if(isset($selected_id) && $selected_id == -1 || $selected_id != $myrow['id']){
            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["site_description"]);  
//                if($myrow["is_deduction"] == 1){
//                    $deduction = "Yes";
//                }else{
//                    $deduction = "No";
//                }
//                label_cell($deduction, "align=center");
                label_cell($myrow["task_description"]."(".($myrow["task_code"]).")");  
                label_cell($myrow["line_comment"]);
                amount_cell($myrow["quantity"]);
                amount_decimal_cell($myrow["asset_value"]);
                $line_cost = $myrow["asset_value"] * $myrow["quantity"];
                amount_decimal_cell($line_cost);

                edit_button_cell("Edit".$myrow["id"], _("Edit"));    
                delete_button_cell("Delete".$myrow["id"], _("Delete"));  
            
            end_row();
        }else{
            $line_cost = $myrow["current_value"] * $myrow["quantity"];
            display_asset_quantity_adjustment_request_edit_controls($selected_id, "Edit");
            hidden("selected_id", $selected_id);
        }
        
        $line_total += $line_cost;
    }    
        if(isset($selected_id) && $selected_id == -1 || !($selected_id > 0)){
            display_asset_quantity_adjustment_request_edit_controls();
        }
        start_row();
            label_cell("Total:", "colspan=8 align=right");
            amount_cell($line_total, true); 
        end_row();  
    
    
    end_table();

    hidden("line_total", $line_total);
}

function display_asset_quantity_adjustment_request_edit_controls($selected_id=-1, $Mode=null){
    global $Ajax;

    if($Mode == "Edit"){
        if($selected_id > 0){      
            $myrow = get_asset_quantity_adjustment_request_detail_line($selected_id); 
            $_POST['id'] = $myrow["id"];
            
            if(isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] != $selected_id){
                unset($_POST['asset_id']);
                unset($_POST['_asset_id_edit']);
            }
            if(!(isset($_POST['asset_id']) && $_POST['asset_id'] > 0)){
                unset($_POST['asset_id']);
                unset($_POST['_asset_id_edit']);
                $_POST['asset_id'] = $myrow["asset_id"];
            }
            $_POST['site_id'] = $myrow["site_id"];
//            $_POST['is_deduction'] = $myrow["is_deduction"];
//            $_POST['task_id'] = $myrow["is_deduction"];
            $_POST['line_comment'] = $myrow["line_comment"]; 
            $_POST['quantity'] = abs($myrow["quantity"]); 
            $_POST['task_id'] = $myrow["task_id"]; 
            
            hidden("previous_selected_id", $selected_id);
        }
    }

    echo "<td colspan=8>";
    start_outer_table();

        table_section(1, "5%");
        table_section(2, "35%");

            if($selected_id > 0){  
                label_row("ID:", $myrow["id"]);
                hidden('asset_id', $_POST['asset_id']);
                $asset_d = get_asset($_POST['asset_id']);
                label_row("Asset:", $asset_d["asset_code"]."-".$asset_d["description"]."-"."(".$asset_d["asset_id"].")");
                hidden('asset_id', $_POST['asset_id']);
            }else{
                $Ajax->activate("asset_list");
                div_start("asset_list");
                    asset_list_row("Asset_List:", "asset_id");
//                    asset_list_row($label, $name, $selected_id);
                div_end();
            }
            
            $multiple_items = $_POST['current_value'] = 0;
            $asset_details = get_asset($_POST['asset_id']);
            if (isset($asset_details['asset_id']) && $asset_details['asset_id'] > 0) {
                $multiple_items = $asset_details['multiple_items'];
                $_POST['current_value'] = $asset_details['current_value'];
            }

            if($multiple_items == true){            
                amount_row("Quantity:", 'quantity', null, null);  
            }else{
                if($selected_id > 0 || $_POST['asset_id'] > 0){
                    label_row("Quantity:", number_format(1, 2));
                    hidden('quantity', 1);
                }
            }
            
            if($multiple_items == true){            
                label_row("Value:", number_format($_POST['current_value'], 2));
            }else{
                $qty_one = 1;
                if(isset($_POST['asset_id']) && $_POST['asset_id'] > 0){                        
                    label_row("Value:", number_format($_POST['current_value'], 2));
                }
            }

        table_section(3, "25%");
        
            project_sites_list_row("Job:", 'site_id', $_POST['project_id'], null, 'Select To Site', false); 
            
            tasks_list_row(_("Budget:"), 'task_id', $_POST['project_id'], null, _('Select a budget'), false); 

        table_section(4, "30%");
            textarea_row("Comment:", 'line_comment', null, 35, 4); 

        table_section(5, "5%");

    end_outer_table();
    echo "</td>";
    
    if ($selected_id > 0){
        button_cell('Update_Asset_Quantity_Adjustment_Request', _("Update"), _('Confirm changes'), ICON_UPDATE);
        button_cell('cancel', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
    }else{
        submit_cells('Add_Asset_Quantity_Adjustment_Request', _("Add Item"), "colspan=2", _('Add new item to document'), true);
    }
}

function can_process_asset_quantity_adjustment_request_header_line($asset_qty_ajt_req_no){  
    $msg = can_process_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no);
    if($msg['success'] !== true){
        if(isset($msg["focus_to"])){
            set_focus($msg["focus_to"]);            
        }
        return $msg;
    }
    if(!isset($_POST['Save_Asset_Transfer_Request_Header'])){
        $msg2 = can_process_asset_quantity_adjustment_request_line();
        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_quantity_adjustment_request_header($asset_qty_ajt_req_no){  
    global $Refs;
    
    $header_id = $row_state = 0;
    $atr_header = get_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no);
    if (isset($atr_header['id']) && $atr_header['id'] > 0) {
        $header_id = $atr_header['id'];
        $row_state = $atr_header["row_state"]; 
    }
        
    if($header_id > 0){
        if(!($atr_header['approval_status'] == AS_NEW || $atr_header['approval_status'] == AS_WITH_THE_APPROVER || 
             $atr_header['approval_status'] == AS_AWAITING_APPROVAL || $atr_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);
        }

        $msg = can_edit_document(ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST, $atr_header['project_id'], $atr_header['next_approval_group_id'], $_SESSION['wa_current_user']->user, 
                                 $atr_header['created_by'], $asset_qty_ajt_req_no);
        if($msg['success'] !== true){
            return $msg;
        }
    }
    
    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_QUANTITY_ADJUSTMENT_REQUEST, $header_id);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
    }
       
    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($_POST['location'] == ''){
        $message = "Please select a Location.";
        $set_focus = 'location';
        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);        
    }
  
    return array("success" => true, "message" => "", "row_state" => $row_state);    
}

function can_process_asset_quantity_adjustment_request_line(){

    if(!($_POST['asset_id'] > 0)){
        $message = "Please select an asset.";
        $set_focus = 'asset_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }

    $asset_details = get_asset($_POST['asset_id']);
    $multiple_items = $asset_details['multiple_items'];
    if($multiple_items == 1){
        if(!(check_num('quantity', 0.00001))){
            $message = "Quantity should be greater than zero.";
            $set_focus = 'quantity';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }else{
        if(input_num('quantity') > 1){
            $message = "This is a single item asset. Quantity should be one.";
            $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);  
    }

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

function save_asset_quantity_adjustment_request(&$asset_qty_ajt_req_no, $selected_id, $row_state){
    $msg = save_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no, $row_state);
        if($msg["success"] !== true){
            return $msg;
        }
    $asset_qty_ajt_req_no = $msg['aqar_id'];
    
    $msg = save_asset_quantity_adjustment_request_detail($asset_qty_ajt_req_no, $selected_id);
        if($msg['success'] !== true){
            return array("success" => false, 'aqar_id' => $asset_qty_ajt_req_no, "message" => $msg['message']);
        }

    return array("success" => true, 'aqar_id' => $asset_qty_ajt_req_no, "message" => "Asset Quantity Adjustment Request #$asset_qty_ajt_req_no has been saved.");
}

function save_asset_quantity_adjustment_request_header(&$asset_qty_ajt_req_no, $row_state){
    $msg = write_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no, $_POST['reference'], $_POST['project_id'], $_POST['location'], $_POST['comment'], 
                                                          $_POST['tran_date'], $row_state, $_POST['is_deduction']);  
                         
    if($msg['success'] === true){
        return array("success" => true, "message" => "Asset Quantity Adjustment Request Header #".$msg['aqar_id']." has been saved.", 'aqar_id' => $msg['aqar_id']);
    }else{
        return $msg;
    }
}

function save_asset_quantity_adjustment_request_detail(&$asset_qty_ajt_req_no, $selected_id){       
    $current_value = get_asset($_POST['asset_id']);
    $msg = write_asset_quantity_adjustment_request_line($asset_qty_ajt_req_no, $selected_id, $_POST['asset_id'], input_num('quantity'), $current_value['current_value'], 
                                                        $_POST['site_id'], $_POST['task_id'], $_POST['line_comment']); 
    
    if($msg['success'] !== true){
        return $msg;
    }
    
    $msg = update_asset_quantity_adjustment_request_header_total($asset_qty_ajt_req_no);
    if($msg['success'] !== true){
        return $msg;
    }
    return array("success" => true, 'aqar_id' => $asset_qty_ajt_req_no, "message" => "Asset Quantity Adjustment Request Line saved.");
  
}

function can_delete_asset_quantity_adjustment_request_details_line($asset_qty_ajt_req_no){
   $arh = get_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no);
   
   if($asset_qty_ajt_req_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);
        }
    } 
   
    return array("success" => true, "focus_to" => '', "message" => "");       
}

function can_release_asset_quantity_adjustment_request($asset_qty_ajt_req_no){
    $line_count = get_asset_quantity_adjustment_request_details_line_count($asset_qty_ajt_req_no);
    if(!($line_count > 0)){
        $message = ("There are no Asset Quantity Adjustment request details entered. Can not release this Asset Quantity Adjustment request.");
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    $row_state = get_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no);
    return array("success" => true, "focus_to" => '', "message" => "", "row_state" => $row_state['row_state']);    
}

function release_asset_quantity_adjustment_request($asset_qty_ajt_req_no, $row_state){    
    begin_transaction();
        $msg = save_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no, $row_state);
        if($msg['success'] !== true){
            cancel_transaction();
            return $msg;
        } 

        $msg = release_asset_quantity_adjustment_request_for_approval($asset_qty_ajt_req_no);
        if($msg['success'] !== true){
            cancel_transaction();
            return $msg;
        }
    commit_transaction();
    clear_session_variable("ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST_atr_no");
    set_session_variable('ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST_message', $msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_ATR_No=$asset_qty_ajt_req_no");    
}

?>