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

function write_asset_quantity_adjustment_request_header($aqar_id, $reference, $project_id, $location, $comment, $date, $row_state, $is_deduction){
    global $Refs;
        if($aqar_id > 0){
            $msg = update_asset_quantity_adjustment_request($aqar_id, $reference, $project_id, $location, $comment, $date, $row_state, $is_deduction);
            if($msg['success'] !== true){
                return $msg;
            }
        }else{
            $msg = insert_asset_quantity_adjustment_request($reference, $project_id, $location, $comment, $date, $is_deduction);
            if($msg['success'] !== true){
                return $msg;
            }
        }
        $Refs->save(ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST, $msg['aqar_id'], $reference);
        
    return array("success" => true, "message" => "", "aqar_id" => $msg['aqar_id'], "row_state" => $row_state);
}

function update_asset_quantity_adjustment_request($aqar_id, $reference, $project_id, $location, $comment, $date, $row_state, $is_deduction){    
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
    $sql = "UPDATE ".TB_PREF."asset_quantity_adjustment_requests 
                SET reference = ".db_escape($reference).",
                    project_id = ".db_escape($project_id).",                       
                    asset_location = ".db_escape($location).",                          
                    tran_date = ".db_escape(date2sql($date)).",
                    comment = ".db_escape($comment).", 
                    is_deduction = ".db_escape($is_deduction).", 
                    updated_by = ".db_escape($updated_by).", 
                    updated_on = ".db_escape($updated_on).", 
                    row_state = ".db_escape(db_new_row_state($row_state))." 
            WHERE id = ".db_escape($aqar_id)." 
                AND row_state = ".db_escape($row_state);
          
    db_query($sql, "could not update_asset_quantity_adjustment_request"); 
    
    if(db_num_affected_rows() != 1){
        cancel_transaction();
        return array("success" => false, "message" => "Could not update Asset Quantity Adjustment Request Header #$aqar_id");
    }else{
        return array("success" => true, "message" => "", "aqar_id" => $aqar_id);
    }
}
         
function insert_asset_quantity_adjustment_request($reference, $project_id, $location, $comment, $date, $is_deduction){
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
    
    $sql = "INSERT INTO ".TB_PREF."asset_quantity_adjustment_requests 
                  ( reference, project_id, asset_location, 
                    comment, tran_date, is_deduction,
                    created_by, created_on )         
            VALUES( ".db_escape($reference).", ".db_escape($project_id).", ".db_escape($location).", 
                    ".db_escape($comment).", ".db_escape(date2sql($date)).", ".db_escape($is_deduction).",                    
                    ".db_escape($created_by).", ".db_escape($created_on).")";
     
    db_query($sql, "could not insert_asset_quantity_adjustment_request");

    if(!(db_insert_id() > 0)){
        cancel_transaction();
        return array("success" => false, "message" => "Could not Insert a New Asset Quantity Adjustment Request Header.", "aqar_id" => null);
    }else{
        return array("success" => true, "message" => "", "aqar_id" => db_insert_id());
    }
}
        
function write_asset_quantity_adjustment_request_line($asset_qty_ajt_req_no, $aqar_line_id, $asset_id, $quantity, $current_value, $site_id, 
                                                      $task_id, $line_comment){
    
  
    if($aqar_line_id > 0){
        update_asset_quantity_adjustment_request_line($aqar_line_id, $asset_id, $quantity, $current_value, $site_id, $task_id, $line_comment);      
    }else{
        insert_asset_quantity_adjustment_request_line($asset_qty_ajt_req_no, $asset_id, $quantity, $current_value, $site_id, $task_id, $line_comment);
        
    }
    return array("success" => true, "message" => "", "aqar_id" => $asset_qty_ajt_req_no);
}

function get_tool_request_total($asset_qty_ajt_req_no)
{
    $sql = "SELECT SUM(no_of_days * quantity * rate) total
            FROM ".TB_PREF."tool_request_details
            WHERE ar_id=".db_escape($asset_qty_ajt_req_no);
    
    $result = db_query($sql);
    $count = db_fetch($result);    
    
    if(isset($count['total']) && $count['total'] > 0){
        return $count['total'];
    }else{
        return 0;
    }
}

function update_asset_quantity_adjustment_request_line($aqar_line_id, $asset_id, $quantity, $current_value, $site_id, $task_id, $line_comment){
    $sql = "UPDATE ".TB_PREF."asset_quantity_adjustment_request_details 
                SET quantity = ".db_escape($quantity).", 
                    asset_id = ".db_escape($asset_id).",
                    asset_value = ".db_escape($current_value).",
                    site_id = ".db_escape($site_id).", 
                    task_id = ".db_escape($task_id).",
                    line_comment = ".db_escape($line_comment)."
                
            WHERE id = ".db_escape($aqar_line_id);
    
    db_query($sql, "Could not update_asset_quantity_adjustment_request_line");
    
}        

function insert_asset_quantity_adjustment_request_line($asset_qty_ajt_req_no, $asset_id, $quantity, $current_value, $site_id, $task_id, $line_comment){
    $sql = "INSERT INTO ".TB_PREF."asset_quantity_adjustment_request_details 
                        ( aqar_id, asset_id, 
                          quantity, asset_value, site_id, 
                          task_id, line_comment )        
            VALUE       ( ".db_escape($asset_qty_ajt_req_no).", ".db_escape($asset_id).",
                          ".db_escape($quantity).", ".db_escape($current_value).", ".db_escape($site_id).", 
                          ".db_escape($task_id).", ".db_escape($line_comment).")";      
    db_query($sql, "could not insert_asset_quantity_adjustment_request_line");
    
    
}

function get_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no){
    $sql = "SELECT aqar.*,
                    pm.description project_description 
            FROM ".TB_PREF."asset_quantity_adjustment_requests aqar 
                LEFT JOIN ".TB_PREF."projects_master pm 
                    ON aqar.project_id = pm.project_id 
            WHERE aqar.id = ".db_escape($asset_qty_ajt_req_no);
    
    $result = db_query($sql, "Could not get_asset_quantity_adjustment_request_header");
    return db_fetch($result);
}
 
function get_asset_quantity_adjustment_request_detail_line($selected_id){
    $sql = "SELECT aqard.*         
            FROM ".TB_PREF."asset_quantity_adjustment_request_details aqard
            WHERE aqard.id = ".db_escape($selected_id);
    
    $result = db_query($sql, "could not get_asset_quantity_adjustment_request_detail_line");
    return db_fetch($result);
}

function delete_asset_quantity_adjustment_request_detail($selected_id){
    $sql = "DELETE FROM ".TB_PREF."asset_quantity_adjustment_request_details WHERE id = ".db_escape($selected_id);
    db_query($sql, "could not delete_asset_quantity_adjustment_request_detail");
    return db_num_affected_rows();
}

function get_asset_quantity_adjustment_request_details($aqar_id){
    $sql = "SELECT aqard.*,
                    am.asset_code,
                    am.description asset_description,
                    am.asset_id,
                    am.current_value,
                    am.multiple_items,
                    ps.description site_description,
                    pt.task_code,
                    pt.description task_description 

            FROM ".TB_PREF."asset_quantity_adjustment_request_details aqard 
                LEFT JOIN ".TB_PREF."asset_master am 
                    ON aqard.asset_id = am.asset_id 
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON aqard.site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt  
                    ON aqard.task_id = pt.task_id  
            WHERE aqard.aqar_id = ".db_escape($aqar_id);
    
    return db_query($sql, "Could not get_asset_quantity_adjustment_request_details");
}

function get_tool_request_detail_records($aqar_id)
{
    $sql = "SELECT ard.*
            FROM ".TB_PREF."tool_request_details ard 
            WHERE ard.ar_id=".db_escape($aqar_id);
    
    return db_query($sql, "Could not get_tool_request_detail_records");
    
}

function update_tool_request_line_issued_qty($aqar_line_id, $issued_qty)
{
    $sql = "UPDATE ".TB_PREF."tool_request_details
            SET issued_qty = ".db_escape($issued_qty)." 
            
            WHERE id=".db_escape($aqar_line_id);
   
    db_query($sql);   
    return db_num_affected_rows();
}

function get_asset_quantity_adjustment_request_details_line_count($asset_qty_ajt_req_no){
    $sql = "SELECT COUNT(id) line_count 
            FROM ".TB_PREF."asset_quantity_adjustment_request_details  
            WHERE aqar_id = ".db_escape($asset_qty_ajt_req_no);
    
    $result = db_query($sql, "could not get_asset_quantity_adjustment_request_details_line_count");
    $count =  db_fetch($result);   
    if(isset($count['line_count']) && $count['line_count'] > 0){
        return $count['line_count'];
    }    
    return 0;
}

function get_tool_request_tasks($asset_qty_ajt_req_no)
{
    $tasks = array();
    
    $sql = "SELECT task_id 
            FROM ".TB_PREF."tool_request_details 
            WHERE ar_id = ".db_escape($asset_qty_ajt_req_no)." 
                    AND project_asset = 0 ";
    
    $result = db_query($sql, "get_tool_request_tasks");
    while ($row = db_fetch($result)) {
        $tasks[] = $row['task_id'];        
    }
    
    get_task_cost_details($tasks);
    
    return $tasks;
}

function get_asset_quantity_adjustment_request_task_remaining_totals($asset_qty_ajt_req_no){
    $sql = "SELECT task_id, 
                SUM(quantity * asset_value) task_cost 
            FROM ".TB_PREF."asset_quantity_adjustment_request_details  
            WHERE aqar_id = ".db_escape($asset_qty_ajt_req_no)." 
            GROUP BY task_id";
    
    return db_query($sql, "could not get_asset_quantity_adjustment_request_task_remaining_totals");
}

function calculate_asset_quantity_adjustment_request_task_remaining_totals($asset_qty_ajt_req_no){
    $task_costs = array();
    $result = get_asset_quantity_adjustment_request_task_remaining_totals($asset_qty_ajt_req_no);

    while($row = db_fetch($result)){            
        add_to_task_cost($task_costs, $row['task_id'], $row['task_cost'], $row['task_cost'], $row['task_cost']);
    }
    get_task_cost_details($task_costs);
    return $task_costs;
}
   
function release_asset_quantity_adjustment_request_for_approval($asset_qty_ajt_req_no){
    $current_user_id = $_SESSION['wa_current_user']->user;
    $aqarh = get_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no);
    
    $tasks_summary = calculate_asset_quantity_adjustment_request_task_remaining_totals($asset_qty_ajt_req_no); 
    
    $info = approve_document(ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST, $asset_qty_ajt_req_no, $aqarh['project_id'], $tasks_summary, $aqarh['next_approval_group_id'], 
                             $current_user_id, $aqarh['row_state'], $aqarh['created_by'], $aqarh['total']);

    if($info['success'] !== true){
        return array("success" => $info['success'],"tran_no" => $asset_qty_ajt_req_no, "message" => $info['message']);
    }

    if($info['approval_status'] != AS_APPROVED){            
        commit_transaction();
        return array("success" => true, "tran_no" => $asset_qty_ajt_req_no, "message" => $info['message']);
    }
    
    if($aqarh['is_deduction'] == 0){// Receiving assets into the project increase the costs
        $apc_msg = allocate_to_tasks(ST_ASSET_QUANTITY_ADJUSTMENT_REQUEST, $asset_qty_ajt_req_no, $tasks_summary, $current_user_id);
        if($apc_msg['success'] !== true){
            return array("success" => $apc_msg['success'], "tran_no" => $asset_qty_ajt_req_no, "message" => $info['message']);
        }
    }

    return array("success" => true, "aqar_id" => $asset_qty_ajt_req_no, "message" => $info['message']);  
}

function update_asset_quantity_adjustment_request_header_total($asset_qty_ajt_req_no){
    
    $total = get_asset_quantity_adjustment_request_lines_total($asset_qty_ajt_req_no);
    $row_state = get_asset_quantity_adjustment_request_header($asset_qty_ajt_req_no);
    
    $sql = "UPDATE ".TB_PREF."asset_quantity_adjustment_requests  
            SET row_state = ".db_escape(db_new_row_state($row_state['row_state'])).", 
                total = ".db_escape($total)." 
            WHERE id = ".db_escape($asset_qty_ajt_req_no)." 
                AND row_state = ".db_escape($row_state['row_state']);
    
    db_query($sql, "could not update_asset_quantity_adjustment_request_header_total");
    
    $n = db_num_affected_rows();
    if($n != 1){
        cancel_transaction();
        return array("success" => false, "message" => "Could not update Asset Quantity Adjustment Request Header Total #$asset_qty_ajt_req_no");
    }else{
        return array("success" => true, "message" => "", "aqar_line_id" => $asset_qty_ajt_req_no);
    }
}

function get_asset_quantity_adjustment_request_lines_total($asset_qty_ajt_req_no){
    $sql = "SELECT SUM(asset_value * quantity) total 
            FROM ".TB_PREF."asset_quantity_adjustment_request_details 
            WHERE aqar_id = ".db_escape($asset_qty_ajt_req_no);    
    $result = db_query($sql, "could not get_asset_quantity_adjustment_request_lines_total");
    return db_result_value($result, "total");
}

function check_all_asset_quantity_adjustment_request_lines_fully_transferred($asset_issue_id){
    $sql = "SELECT id num_recs  
            FROM ".TB_PREF."asset_quantity_adjustment_request_details   
            WHERE quantity > transferred_qty    
                AND aqar_id = ".db_escape($asset_issue_id);
    
    $result = db_query($sql, "could not check_all_asset_quantity_adjustment_request_lines_fully_transferred");
    $num_recs = db_num_rows($result);
    
    if($num_recs > 0){
        return false;
    }else{
        return true;
    }
}

?>