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

function display_asset_quantity_adjustment_header($asset_qty_ajt_req_no){
    global $Refs;
    $aqar_header = get_asset_quantity_adjustment_header($asset_qty_ajt_req_no);

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

                label_row("Asset Quantity Adjustment Request:", "#".$asset_qty_ajt_req_no);
                text_row("Reference:", 'reference', $Refs->get_next(ST_ASSET_QUANTITY_ADJUSTMENT), null, null);   
                label_row("Project:", $aqar_header['project_description']);                        
                label_row("Location:", $aqar_header['location_name']);   
                label_row("Is Deduction:", get_yes_no_name($aqar_header['is_deduction'])); 
                hidden("is_deduction", $aqar_header['is_deduction']);

            table_section(2, "40%");
                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_qty_ajt_req_no."&source_type_id=".ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST, "Request_Record_Status");
                label_row($s, $approval_statuses[$aqar_header['approval_status']]);

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

function display_asset_quantity_adjustment_details($asset_qty_ajt_no){      
    display_heading("Assets Quantity Adjustment Details");
    br();
    $result = get_asset_quantity_adjustment_details($asset_qty_ajt_no);      
                              
    start_table(TABLESTYLE, "width=98%");
    $th = array(_("ID"), _("Asset"), _('Site'), _("Budget"), _("Request Comment"), _("Value"), _("Req. Quantity"), _("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["site_description"]);  

            $req_quantity = $myrow["req_quantity"];
            
            label_cell($myrow["task_description"]);
            label_cell($myrow["line_comment"]);
            amount_decimal_cell($myrow["asset_value"]);
            
            
            amount_cell($req_quantity);
            $line_cost = $myrow["asset_value"] * $req_quantity;
            amount_decimal_cell($line_cost);

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

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

function can_process_asset_quantity_adjustment_header_and_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;
    }

    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;
    global $approval_statuses;
    $aqar_header["row_state"] = null; 
    
    $aqar_header = get_asset_quantity_adjustment_header($asset_qty_ajt_req_no, AS_APPROVED);
    if(!($aqar_header['id'] > 0)){
        $aqar_header_status = get_asset_quantity_adjustment_header($asset_qty_ajt_req_no);
        $message = ("Asset Quantity Adjustent Request record #$asset_qty_ajt_req_no status does not allow to process. 
                     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_QUANTITY_ADJUSTMENT, 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);
    }
    
    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" => $aqar_header['row_state']);    
}

function save_asset_quantity_adjustment(&$asset_qty_ajt_req_no, $row_state, $reference){
    
    global $Refs;
    
    $req_h = get_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no);
    
    $saqah_msg = save_asset_quantity_adjustment_header($asset_qty_ajt_req_no);
        if($saqah_msg["success"] !== true){
            return $saqah_msg;
        }
    $asset_qty_ajt_no = $saqah_msg['aqa_id'];
    
    $result = get_asset_quantity_adjustment_request_details($asset_qty_ajt_req_no);
    while($row = db_fetch($result)){
        $aaqal_msg = add_asset_quantity_adjustment_line($asset_qty_ajt_no, $row["id"], $row['asset_id'], $row['quantity'], $row['asset_value'], $row['task_id']); 
        if($aaqal_msg['success'] !== true){
            return array("success" => false, 'aqar_id' => $asset_qty_ajt_req_no, "message" => $aaqal_msg['message']);
        }
        
        $line_id = $aaqal_msg['aqa_id'];
        $tran_date_ = $_POST['tran_date'];
        $project_id = $req_h['project_id'];
        $loc_code = $req_h['asset_location'];
        $asset_id = $row['asset_id'];
        $site_id = $row['site_id'];
        $task_id = $row['task_id'];
        $qty = $row['quantity']; 
        add_asset_move(ST_ASSET_QUANTITY_ADJUSTMENT, $asset_qty_ajt_no, $line_id, $reference, $tran_date_, $asset_id, $loc_code, $site_id, $task_id, $qty, $project_id);
    }

    $Refs->save(ST_ASSET_QUANTITY_ADJUSTMENT, $asset_qty_ajt_no, $reference);
    
    
    $aqa_result = get_asset_quantity_adjustment_detail_records($asset_qty_ajt_no);
    while ($myrow = db_fetch($aqa_result))
    {
        $a['row_id'] = $myrow['id'];
        $a['stock_id'] = $myrow['asset_id'];
        $a['task_id'] = $myrow['task_id'];
        $a['requested_qty'] = $myrow['quantity'];
        $a['high_value_item'] = 0;
        $a['reference_cost'] = $myrow['asset_value'];
        $a['standard_cost'] = $myrow['asset_value'];
        $a['total_issued_qty'] = $myrow['quantity'];
        $a['qty'] = $myrow['quantity']; 

        $mr_details_array[] = $a;

    }
                
    $current_user_id = $_SESSION['wa_current_user']->user;
    $mr_tasks_summary = calculate_task_remaining_totals($mr_details_array);
    
    if($_POST['is_deduction'] == 0){ // Receiving assets into the project increase costs
        $apc_msg = remove_task_allocations(ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST, $asset_qty_ajt_req_no, $mr_tasks_summary, $current_user_id);
        if($apc_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $apc_msg['success'], "tran_no" => $asset_qty_ajt_no, "message" => $apc_msg['message']);
        }

        foreach ($mr_tasks_summary as &$summary_line) {
            $summary_line['row_state'] = db_new_row_state($summary_line['row_state']);
        }
        $cct_msg = charge_cost_to_tasks(ST_ASSET_QUANTITY_ADJUSTMENT, $asset_qty_ajt_no, 
                                    $mr_tasks_summary, $current_user_id);

        if($cct_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $cct_msg['success'], "tran_no" => $asset_qty_ajt_no, "message" => $cct_msg['message']);
        }
    }
    else{// Issueing assets reduce the cost of project
        $rcft_msg = remove_costs_from_tasks(ST_ASSET_QUANTITY_ADJUSTMENT, $asset_qty_ajt_no, 
                        $mr_tasks_summary, $current_user_id); 

        if($rcft_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $rcft_msg['success'], "tran_no" => $asset_qty_ajt_no, "message" => $rcft_msg['message']);
        }
    }
    
    $msg = direct_update_document_status(ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST, $asset_qty_ajt_req_no, AS_COMPLETED, $row_state);
    if($msg['success'] !== true){
        return $msg;
    }

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

function save_asset_quantity_adjustment_header(&$asset_qty_ajt_req_no){  
    $msg = write_asset_quantity_adjustment_header($asset_qty_ajt_req_no, $_POST['reference'], $_POST['company_code'], $_POST['employee_code'], $_POST['tran_date'], 
                                                  $_POST['comment'], $_POST['lines_total'], $_POST['is_deduction']);  
    return $msg;
}

function can_delete_asset_transfer_request_details_line($asset_qty_ajt_no, $selected_id){
   $arh = get_asset_quantity_adjustment_header($asset_qty_ajt_no);
   
   if($asset_qty_ajt_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_qty_ajt_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_qty_ajt_no){
    $line_count = get_asset_transfer_request_details_line_count($asset_qty_ajt_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_quantity_adjustment_header($asset_qty_ajt_no);
    return array("success" => true, "focus_to" => '', "message" => "", "row_state" => $row_state['row_state']);    
}

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

    $msg = release_asset_transfer_request_for_approval($asset_qty_ajt_no);
    if($msg['success'] !== true){
        cancel_transaction();
        display_error($msg['message']);
        return $msg;
    }
    commit_transaction();
    clear_session_variable("ST_ASSET_QUANTITY_ADJUSTMENT_aqa_no");
    set_session_variable('ST_ASSET_QUANTITY_ADJUSTMENT_message', $msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_AQAR_No=$asset_qty_ajt_no");    
}

?>