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

//-------------------------------------------------------------------------------------------------------------
include_once($path_to_root . "/inventory/includes/db/material_requisitions_db.inc");
include_once($path_to_root . "/includes/common_functions.inc");

function add_issue_materials(&$items, $im_reference, $issuing_location, 
                            $project_id, $memo_, 
                            $source_mr_no, $mr_row_state, $approval_status,
                            $employee_company_code, $employee_code, $im_date,                             
                            $movement_type, $linked_field_type, $linked_field_id, $group_company_code)
{
	global $loc_notification, $path_to_root, $Refs;
//    $mr_no = $_SESSION['im_items']->order_id;
        $current_user_id = $_SESSION['wa_current_user']->user;
        $type = ST_MATERIAL_ISSUE;
        $date = sql2date(date('Y/m/d'));
        
        $created_by = $_SESSION['wa_current_user']->user;

	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('items', 'im_reference', 'issuing_location', 
                                        'project_id', '$memo_', 
                                        'source_mr_no', ',$mr_row_state', 'approval_status',
                                        'company_code', 'employee_code', 'im_date',
                                        'movement_type', 'linked_field_type', 'linked_field_id', 'group_company_code'), $args);
	$args->trans_no = 0;
	hook_db_prewrite($args, $type);

    if($im_reference == '' || $im_reference == null )
    {
        $im_reference = get_next_trans_no($type);
    }

    //$mrt_no = get_next_trans_no($type);

//    if($approval_status == AS_COMPLETED){
//        $new_approval_status =  AS_COMPLETED;
//    }
//    else{
//        $new_approval_status = AS_ISSUED;
//    }
    
    $new_approval_status = AS_ISSUED;
    
    $umrs_msg = update_mr_status($source_mr_no, $new_approval_status, $mr_row_state, $created_by);
    if($umrs_msg['success'] !== true)
    {
        cancel_transaction();
        return array("passed" => false, "tran_no" => $source_mr_no, "message" => $umrs_msg['message']);
    }
    
    $im_no = add_issue_materials_header($im_reference, $issuing_location, 
                                        $project_id, $memo_, $source_mr_no, 
                                        $employee_company_code, $employee_code,                                         
                                        $movement_type, $linked_field_type, $linked_field_id, $group_company_code,
                                        $im_date, $created_by);

    if(!$im_no > 0)
    {
        cancel_transaction();
        return array("passed" => false, "tran_no" => $im_no, "message" => "Could not create material issue");
    }

    if ($loc_notification == 1){
        include_once($path_to_root . "/inventory/includes/inventory_db.inc");
        $st_ids = array();
        $st_names = array();
        $st_num = array();
        $st_reorder = array();
    }
     
        
    foreach ($items as &$line_item){
        if($line_item->check_issue_item == true){
            if ($loc_notification == 1){
                $loc = calculate_reorder_level($issuing_location, $line_item, $st_ids, $st_names, $st_num, $st_reorder); 
            }

            if($line_item->tran_qty > 0){
                $item_info = get_item_edit_info($line_item->stock_id);
                $line_item->standard_cost = $item_info['standard_cost'];
                
                $issue_material_detail_id = add_issue_material_item($im_no, $line_item->row_id,
                        $line_item->stock_id, $line_item->tran_qty * $line_item->convertion_factor, $line_item->standard_cost, 
                        $line_item->tran_unit, $line_item->tran_qty,
                        $line_item->convertion_factor, $line_item->task_id,
                        $line_item->project_site_id);
                
                $line_item->target_line_id = $issue_material_detail_id;

//                add_stock_move(ST_MATERIAL_ISSUE, $line_item->stock_id, $im_no, $issuing_location,
//                        $date, $im_reference, -$line_item->tran_qty * $line_item->convertion_factor, $item_info['standard_cost'], 
//                        null, null, null, null, 
//                        null, $line_item->tran_unit,-$line_item->tran_qty, $line_item->convertion_factor,
//                        $line_item->task_id, $line_item->project_site_id, $line_item->row_id);

                add_stock_adjustment_item($im_no, $line_item->stock_id, $issuing_location, $im_date, 
                                $im_reference, -$line_item->tran_qty * $line_item->convertion_factor, $line_item->standard_cost, "", 
                                $line_item->tran_unit, -$line_item->tran_qty, $line_item->convertion_factor, ST_MATERIAL_ISSUE, 
                                $line_item->task_id, $line_item->project_site_id, $line_item->row_id, $project_id);


                $ailqdm_msg =  add_item_line_quantity_detail_movements(ST_MATERIAL_ISSUE, $im_no, $issuing_location, 
                                                                        $im_date, $line_item, false, '');
                if($ailqdm_msg['success'] !== true){
                    cancel_transaction();
                    return array("success" => $ailqdm_msg['success'], "tran_no" => $im_no, "message" => $ailqdm_msg['message']);
                }

                update_mr_item_issued_qty($line_item->row_id, $line_item->tran_qty*$line_item->convertion_factor);

            }
        }
    }

    $Refs->save(ST_MATERIAL_ISSUE, $im_no, $im_reference);
    add_audit_trail(ST_MATERIAL_ISSUE, $im_no, $im_date);
	
//	if ($loc_notification == 1 && count($st_ids) > 0)
//		send_reorder_email($loc, $st_ids, $st_names, $st_num, $st_reorder);  
        
        
    $args->trans_no = $im_no;
    hook_db_postwrite($args, $type);

    $mr_details = get_mr_details($source_mr_no);

    while ($myrow = db_fetch($mr_details))
    {
        $a['row_id'] = $myrow['id'];
        $a['stock_id'] = $myrow['stock_id'];
        $a['task_id'] = $myrow['task_id'];
        $a['requested_qty'] = $myrow['requested_qty'];
        $a['high_value_item'] = $myrow['high_value_item'];
        $a['reference_cost'] = $myrow['price'];
        $a['standard_cost'] = $myrow['price'];
        $a['total_issued_qty'] = $myrow['issued_qty'];
        $a['qty'] = $myrow['requested_qty']; - $a['total_issued_qty'];

        $mr_details_array[] = $a;

    }

//    foreach ($mr_details_array as &$mr_line){
//        $mr_line['qty'] = 0;
//        foreach ($items as $im_detail_item){
//            if($im_detail_item->row_id == $mr_line['row_id'] && $im_detail_item->check_issue_item){
//                $mr_line['qty'] = $im_detail_item->tran_qty * $im_detail_item->convertion_factor;
//                break;
//            }
//        }
//    }
                
    $mr_tasks_summary = calculate_task_remaining_totals($mr_details_array);
    
//    $apc_msg = allocate_to_tasks(ST_MATERIAL_REQ, $mr_no, $mr_tasks_summary, $current_user_id);
    $apc_msg = reallocate_to_tasks(ST_MATERIAL_REQ, $source_mr_no, $mr_tasks_summary, $current_user_id);
    if($apc_msg['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $apc_msg['success'], "tran_no" => $source_mr_no, "message" => $apc_msg['message']);
    }

    foreach ($items as &$im_item){
        if($im_item->check_issue_item == true){
            if($im_item->tran_qty > 0){
                $qty = $im_item->tran_qty * $im_item->convertion_factor;
                $b['row_id'] = $im_item->row_id;
                $b['stock_id'] = $im_item->stock_id;
                $b['task_id'] = $im_item->task_id;
                $b['requested_qty'] = $qty;
                $b['high_value_item'] = 0;
                $b['reference_cost'] = $im_item->standard_cost;
                $b['standard_cost'] = $im_item->standard_cost;
                $b['total_issued_qty'] = $qty;
                $b['qty'] = $qty;

                $mi_details_array[] = $b;
            }
        }
    }
    
    $mi_tasks_summary = calculate_task_remaining_totals($mi_details_array);
    
    $cct_msg = charge_cost_to_tasks(ST_MATERIAL_ISSUE, $im_no, 
                                $mi_tasks_summary, $current_user_id);
    
    if($cct_msg['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $cct_msg['success'], "tran_no" => $im_no, "message" => $cct_msg['message']);
    }
    
    commit_transaction();
    
//    if($mr_complete){
//        close_mr($source_mr_no);
//    }
//    else{
//        if(check_all_mr_lines_issued($source_mr_no)=== true){
//            close_mr($source_mr_no);
//        }
//    }
//            
	
        
    return array("success" => true, "tran_no" => $im_no, "message" => "Material issue $im_no has been created");
}

//-------------------------------------------------------------------------------------------------------------

function add_issue_materials_header($reference, $issuing_location,
                                    $project_id, $comment, $source_mr_no, 
                                    $company_code, $employee_code, 
                                    $movement_type, $linked_field_type, $linked_field_id, $group_company_code,
                                    $im_date, $created_by)
{
	//$mr_date = date2sql($date_);
        $created_on = date('Y-m-d H:i:s');

	$sql = "INSERT INTO ".TB_PREF."issue_materials(reference,"
                        . " issuing_location,"
                        . " project_id,"
                        . " source_mr_no, "
                        . " company_code, "
                        . " employee_code, "
                        . " im_date, "
                        . " comment, "
                        . " movement_type, "
                        . " linked_field_type, "
                        . " linked_field_id, "
                        . " group_company_code, "
                        . " created_by, created_on) "
                . "VALUES (".db_escape($reference).", "
                        .db_escape($issuing_location).", "
                        .db_escape($project_id).", "
                        .db_escape($source_mr_no).", "
                        .db_escape($company_code).", "
                        .db_escape($employee_code).", "
                        .db_escape(date2sql($im_date)).", "
                        .db_escape($comment).", "
                        .db_escape($movement_type).", "
                        .db_escape($linked_field_type).", "
                        .db_escape($linked_field_id).", "
                        .db_escape($group_company_code).", "
                        .db_escape($created_by).", ".db_escape($created_on).")";

		$error_msg = "The material issue could not be created";

	db_query($sql, $error_msg);

	return db_insert_id();
}
//--------------------------------------------------------------------------------------------------

function add_issue_material_item($im_no, $mr_line_id,
                    $item_code, $qty_issued, $unit_cost,
                    $tran_unit, $tran_qty,
                    $conversion_factor, $task_id,
                    $site_id)
{
    $sql = "INSERT INTO ".TB_PREF."issue_material_details (
                    im_no, mr_line_id,
                    item_code, qty_issued, unit_cost,
                    tran_unit, tran_qty,
                    conversion_factor, task_id,
                    site_id) 
            VALUES (".db_escape($im_no).", ".db_escape($mr_line_id).", "
                        .db_escape($item_code).", ".db_escape($qty_issued).", ".db_escape($unit_cost).", "
                        .db_escape($tran_unit).", ".db_escape($tran_qty).", "
                        .db_escape($conversion_factor).", ".db_escape($task_id).", "
                        .db_escape($site_id).")";
    
    db_query($sql, "Could not add_issue_material_item.");
    
    return db_insert_id();
}


function get_material_issue_header($mrt_no)
{
    $sql = "SELECT mrt.*, 
                    il.location_name issuing_location_name,
                    u.real_name created_user_name 
            FROM ".TB_PREF."material_requisition_transfers mrt,
                    ".TB_PREF."locations il,
                    ".TB_PREF."users u 
            WHERE mrt.issuing_location = il.loc_code AND 
                    mrt.created_by = u.id AND  
                    mrt_no = '".$mrt_no."'";
    
    $result = db_query($sql);
    return db_fetch($result);
    
}

//--------------------------------------------------------------------------------------------------

function get_material_issue_details($mrt_no, $type)
{
    $sql = "SELECT  smoves.stock_id ,
                    smoves.qty ,
                    smaster.description  
            FROM    ".TB_PREF."stock_moves smoves,
                    ".TB_PREF."stock_master smaster  
            WHERE   smoves.stock_id = smaster.stock_id AND 
                    smoves.trans_no = '".$mrt_no."' AND type = '".$type."'";
    
    $result = db_query($sql);
    
    return $result;
    
}

function get_issue_material_details($im_no)
{
    $sql = "SELECT  imd.*,
                    sm.description item_description,
                    pt.description task_description,
                    ps.description site_description 
            FROM ".TB_PREF."issue_material_details imd 
                    LEFT JOIN ".TB_PREF."stock_master sm ON  
                            imd.item_code = sm.stock_id 
                    LEFT JOIN ".TB_PREF."project_tasks pt ON  
                            imd.task_id = pt.task_id  
                    LEFT JOIN ".TB_PREF."project_sites ps ON  
                            imd.site_id = ps.id 
            WHERE imd.im_no = '".$im_no."'";
    
    $result = db_query($sql);
    
    return $result;
    
}

function get_issue_materials($im_no)
{
    $sql = "SELECT DISTINCT im.*, 
                   il.location_name issuing_location_name,
                   apn.value_name task_description,
                   pm.description project_description,
                    u.real_name created_user_name 
            FROM ".TB_PREF."issue_materials im
            LEFT JOIN ".TB_PREF."locations il ON
                    im.issuing_location = il.loc_code 
            LEFT JOIN ".TB_PREF."projects_master pm ON
                pm.project_id = im.project_id
            LEFT JOIN ".TB_PREF."project_tasks pt ON
                im.task_id = pt.task_id 
            LEFT JOIN ".TB_PREF."list_values apn ON
                pt.type_id = apn.id
            LEFT JOIN ".TB_PREF."users u ON
                 im.created_by = u.id
            WHERE im_no = '".$im_no."'";
    
    $result = db_query($sql);
    return db_fetch($result);
    
}

function get_issue_material_header($im_no)
{
    $sql = "SELECT im.*, 
                    il.location_name issuing_location_name,
                    pm.description project_description,
                    u.real_name created_user_name 
            FROM ".TB_PREF."issue_materials im
                    LEFT JOIN ".TB_PREF."locations il ON
                            im.issuing_location = il.loc_code 
                    LEFT JOIN ".TB_PREF."projects_master pm ON
                            pm.project_id = im.project_id
                    LEFT JOIN ".TB_PREF."users u ON
                            im.created_by = u.id
            WHERE im_no = '".$im_no."'";
    
    $result = db_query($sql);
    return db_fetch($result);
    
}

function get_material_issues_for_mr($mrf_no)
{
     $sql = "SELECT im.*, 
                    il.location_name issuing_location_name,
                    pm.description project_description,
                    u.real_name created_user_name 
            FROM ".TB_PREF."issue_materials im
                    LEFT JOIN ".TB_PREF."locations il ON
                            im.issuing_location = il.loc_code 
                    LEFT JOIN ".TB_PREF."projects_master pm ON
                            pm.project_id = im.project_id
                    LEFT JOIN ".TB_PREF."users u ON
                            im.created_by = u.id
            WHERE im.source_mr_no = '".$mrf_no."'";
    
    return $result = db_query($sql);
    
    
}

function get_issue_material_details_qty_issued($mr_line_id) {
    $sql = "SELECT SUM(qty_issued) total_qty_issued 
            FROM ".TB_PREF."issue_material_details   
            WHERE mr_line_id = ".db_escape($mr_line_id);
    
        $result = db_query($sql, 'get_issue_material_details_qty_issued');
        return db_result_value($result, 'total_qty_issued');
}


function get_mr_item_total_issued_qty($pr_line_id)
{
    $sql = "SELECT SUM(qty_issued) total_issued_qty  
            FROM ".TB_PREF."issue_material_details  
            WHERE mr_line_id = ".db_escape($pr_line_id);
    
    $result = db_query($sql, "get_mr_item_total_issued_qty");
    return db_result_value($result, "total_issued_qty");
}
