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

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


function add_scheduler_work_order($woid, $wo_ref, $project_id, 
                        $task_id, $loc_code, $units_reqd, 
                        $stock_id, $type, $date_, 
                        $required_by, $memo_, $costs, 
                        $cr_acc, $labour, $cr_lab_acc, 
                        $tran_unit, $tran_qty, $convertion_factor)
{
	global $Refs;

	if (!($type == WO_ADVANCED)){
		return add_work_order_quick($woid, $wo_ref, $project_id, $task_id, $loc_code, $units_reqd, $stock_id, $type, $date_, $memo_, $costs, $cr_acc, $labour, $cr_lab_acc);
    }
    
	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('$woid','$wo_ref', '$project_id', '$task_id', '$loc_code','$units_reqd','$stock_id','$type','$date_','
                                        $required_by','$memo_','$costs','$cr_acc','$labour','$cr_lab_acc','
                                        $tran_unit','$tran_qty','$convertion_factor'), $args);
	$args->woid = 0;
	hook_db_prewrite($args, ST_WORKORDER);

    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
    
	$sql = "INSERT INTO ".TB_PREF."workorders (
                        id, wo_ref, 
                        project_id, task_id,
                        loc_code, 
                        units_reqd, stock_id,
                        type, date_, required_by, 
                        requested_unit, requested_unit_qty, 
                        req_unit_conv_factor, comments,
                        created_by, created_on)
    	VALUES (".db_escape($woid).",".db_escape($wo_ref).", "
                    .db_escape($project_id).", ".db_escape($task_id).","
                    .db_escape($loc_code).", "
                    .db_escape($units_reqd).", ".db_escape($stock_id).","
                    .db_escape($type).", '$date_', ".db_escape($required_by).","
                    .db_escape($tran_unit).", ".db_escape($tran_qty).", "
                    .db_escape($convertion_factor).", ".db_escape($memo_).","
                    .db_escape($created_by).", ".db_escape($created_on)." )";
	db_query($sql, "could not add work order");

	$Refs->save(ST_WORKORDER, $woid, $wo_ref);
    
	add_audit_trail(ST_WORKORDER, $woid, sql2date($date_));

	$args->woid = $woid;
	hook_db_postwrite($args, ST_WORKORDER);
	commit_transaction();

	return $woid;
}


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


function add_work_order($wo_ref, $project_id, $task_id, 
                        $loc_code, $units_reqd, 
                        $stock_id, $type, $date_, 
                        $required_by, $memo_, $costs, 
                        $cr_acc, $labour, $cr_lab_acc, 
                        $tran_unit, $tran_qty, $convertion_factor)
{
	global $Refs;

	if (!($type == WO_ADVANCED)){
		return add_work_order_quick($wo_ref, $project_id, $task_id, $loc_code, $units_reqd, $stock_id, $type, $date_, $memo_, $costs, $cr_acc, $labour, $cr_lab_acc);
    }
    
	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('$wo_ref','$project_id', '$task_id', '$loc_code','$units_reqd','$stock_id','$type','$date_','
                                        $required_by','$memo_','$costs','$cr_acc','$labour','$cr_lab_acc','
                                        $tran_unit','$tran_qty','$convertion_factor'), $args);
	$args->woid = 0;
	hook_db_prewrite($args, ST_WORKORDER);

    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
        
	$sql = "INSERT INTO ".TB_PREF."workorders (
                        wo_ref, project_id, 
                        task_id, loc_code, 
                        units_reqd, stock_id,
                        type, date_, required_by, 
                        requested_unit, requested_unit_qty, 
                        req_unit_conv_factor, comments,
                        created_by, created_on)
    	VALUES (".db_escape($wo_ref).", ".db_escape($project_id).", "
                    .db_escape($task_id).", ".db_escape($loc_code).","
                    .db_escape($units_reqd).", ".db_escape($stock_id).","
                    .db_escape($type).", '$date_', ".db_escape($required_by).","
                    .db_escape($tran_unit).", ".db_escape($tran_qty).", "
                    .db_escape($convertion_factor).", ".db_escape($memo_).","
                    .db_escape($created_by).", ".db_escape($created_on)." )";
	db_query($sql, "could not add work order");

	$woid = db_insert_id();

	$Refs->save(ST_WORKORDER, $woid, $wo_ref);
    
	add_audit_trail(ST_WORKORDER, $woid, sql2date($date_));

	$args->woid = $woid;
	hook_db_postwrite($args, ST_WORKORDER);
	commit_transaction();

	return $woid;
}


//--------------------------------------------------------------------------------------
function update_work_order($woid, $project_id, $task_id, 
                            $qty_reqd, $date, 
                            $required_by, $memo_, $tran_unit, 
                            $tran_qty, $conversion_factor, $row_state)
{
	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('woid', 'project_id', 'task_id',
                            'qty_reqd','date_',' 
                            required_by','memo','tran_unit',' 
                            tran_qty','conversion_factor','row_state'), $args);
	hook_db_prewrite($args, ST_WORKORDER);

//	$date = date2sql($date_);
//	$required = date2sql($required_by);

    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
        
	$sql = "UPDATE ".TB_PREF."workorders SET 
                    project_id=".db_escape($project_id).", 
                    task_id=".db_escape($task_id).", 
                    units_reqd=".db_escape($qty_reqd).", 
                    required_by=".db_escape($required_by).",
                    date_=".db_escape($date).",
                    requested_unit=".db_escape($tran_unit).", 
                    requested_unit_qty=".db_escape($tran_qty).",
                    req_unit_conv_factor=".db_escape($conversion_factor).", 
                    comments=".db_escape($memo_).", 
                    row_state=". db_new_row_state($row_state).", 
                    updated_by=".db_escape($updated_by).", 
                    updated_on=". db_escape($updated_on)."    
            WHERE id = ".db_escape($woid)." AND row_state = ". db_escape($row_state);

	db_query($sql, "could not update work order");
    
    $num_recs = db_num_affected_rows();
    if($num_recs != 1){
        cancel_transaction();
        return array("success" => false, "tran_no" => $woid, "message" => "Another user has updated the workorder");
    }

	add_audit_trail(ST_WORKORDER, $woid, sql2date($date), _("Updated."));

	hook_db_postwrite($args, ST_WORKORDER);
	commit_transaction();
    
    return array("success" => true, "message" => "", "tran_no" => $woid);
}


function close_work_order_for_issues($woid)
{
    $sql = "UPDATE ".TB_PREF."workorders SET 
                    closed_for_issues= 1     
            WHERE id = ".db_escape($woid);

	db_query($sql, "Could not close_work_order_for_issues");
}


function close_work_order_for_prs($woid)
{
    if($woid > 0){
        $sql = "UPDATE ".TB_PREF."workorders SET 
                        closed_for_prs= 1     
                WHERE id = ".db_escape($woid);

        db_query($sql, "Could not close_work_order_for_prs");
    }
}


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

function add_wo_material($workorder_id, $process_id, 
                        $stock_id, $workcentre_id, 
                        $units_req, $req_unit, 
                        $req_unit_qty, $req_unit_conversion_factor, 
                        $std_cost, $loc_code, 
                        $comment, $created_by)
{
	global $Refs;

//	if (!($type == WO_ADVANCED)){
//		return add_wo_material_quick('wo_material_component', 'wo_material_loc_code',
//                        'wo_material_tran_unit',
//                         'wo_material_tran_qty',                         
//                        'convertion_factor');
//    }
    
    $created_on = date('Y-m-d H:i:s');
        
	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('workorder_id','process_id',' 
                        stock_id','workcentre_id',' 
                        units_req','req_unit',' 
                        req_unit_qty','req_unit_conversion_factor',' 
                        std_cost','loc_code',' 
                        comment','created_by'), $args);
	$args->woid = 0;
	hook_db_prewrite($args, ST_WORKORDER);

	//$date = date2sql($date_);
	//$required = date2sql($required_by);

	$sql = "INSERT INTO ".TB_PREF."wo_material (
                        `workorder_id`, `process_id`, 
                        `stock_id`, `workcentre`, 
                        `units_req`, `req_unit`, 
                        `req_unit_qty`, `req_unit_conversion_factor`, 
                        `std_cost`, `loc_code`, 
                        `comment`,
                        `created_by`, `created_on`)
    	VALUES (".db_escape($workorder_id).", ".db_escape($process_id).", "
                    .db_escape($stock_id).", ".db_escape($workcentre_id).","
                    .db_escape($units_req).",".db_escape($req_unit).","
                    .db_escape($req_unit_qty).",".db_escape($req_unit_conversion_factor).","
                    .db_escape($std_cost).",".db_escape($loc_code).","
                    .db_escape($comment).","
                    .db_escape($created_by).",".db_escape($created_on).")";
                                                      
        
	db_query($sql, "could not add_wo_material");

	add_audit_trail(ST_WORKORDER, $workorder_id, sql2date($created_on));

	$args->woid = $workorder_id;
	hook_db_postwrite($args, ST_WORKORDER);
	commit_transaction();

	return $workorder_id;
}

//--------------------------------------------------------------------------------------
function update_wo_material($id, $units_req, 
                            $req_unit, $req_unit_qty, 
                            $req_unit_conversion_factor, $std_cost, 
                            $loc_code, $comments,
                            $updated_by, $workorder_id)
{
	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('id','units_req',
                            'req_unit','req_unit_qty', 
                            'req_unit_conversion_factor', 'std_cost',
                            'loc_code','comments',
                            'updated_by', 'workorder_id'),$args);
	hook_db_prewrite($args, ST_WORKORDER);

    $updated_on = date('Y-m-d H:i:s');

	$sql = "UPDATE ".TB_PREF."wo_material SET 
                    units_req=".db_escape($units_req).", 
                    req_unit=".db_escape($req_unit).",
                    req_unit_qty=".db_escape($req_unit_qty).",
                    req_unit_conversion_factor=".db_escape($req_unit_conversion_factor).", 
                    std_cost=".db_escape($std_cost).",
                    loc_code=".db_escape($loc_code).", 
                    comment=".db_escape($comments).", 
                    updated_by=".db_escape($updated_by).",  
                    updated_on=".db_escape($updated_on)."  
            WHERE id = ".db_escape($id);

	db_query($sql, "could not update work order");

	add_audit_trail(ST_WORKORDER, $workorder_id, sql2date($updated_on), _("Updated."));

	hook_db_postwrite($args, ST_WORKORDER);
	commit_transaction();
}



function delete_wo_material($id)
{
	$sql = "DELETE FROM ".TB_PREF."wo_material  
            WHERE id = ".db_escape($id);

	db_query($sql, "could not delete_wo_material");
}

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

function get_wo_process($id)
{
	$sql = "SELECT wop.*, wc.name workcentre_name  
            FROM ".TB_PREF."wo_processes wop, ".TB_PREF."workcentres wc    
            WHERE wop.workcentre_id = wc.id AND 
                    wop.id = ".db_escape($id)." 
            ORDER BY sequence";
	
	$result = db_query($sql, "Workorder process could not be retrieved");
    
    return db_fetch($result);
}

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

function delete_wo_process($id)
{
	$sql = "DELETE FROM ".TB_PREF."wo_processes   
            WHERE id = ".db_escape($id);
	
	db_query($sql, "Could not delete_wo_process");
   
}


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

function get_wo_processes($workorder_id, $backwards = false)
{
	$sql = "SELECT wop.*, 
                    wc.name workcentre_name,
                    ptn.value_name process_type_name 
            FROM ".TB_PREF."wo_processes wop 
                    INNER JOIN ".TB_PREF."workcentres wc ON 
                            wop.workcentre_id = wc.id 
                    LEFT JOIN ".TB_PREF."list_values ptn ON 
                            wop.type_id = ptn.id 
            WHERE wop.workorder_id = ".db_escape($workorder_id)." 
               
            ORDER BY wop.sequence ";
    if($backwards){
        $sql .= " DESC ";
    }
	
	return db_query($sql, "Workorder processes could not be retrieved");
}


//--------------------------------------------------------------------------------------
function get_work_order_header($woid)
{    
    $sql = "SELECT wo.*,st.description As StockItemName,
                    l.location_name,
                    l.delivery_address,
                    l.email, 
                    l.contact,
                    p.project_name, 
                    p.description project_description,
                    t.description task_description 
		FROM ".TB_PREF."workorders wo 
        		INNER JOIN ".TB_PREF."stock_master st ON 
                		st.stock_id=wo.stock_id 
                INNER JOIN ".TB_PREF."locations l ON 
                		l.loc_code=wo.loc_code
                LEFT JOIN ".TB_PREF."projects_master p ON 
                        wo.project_id = p.project_id  
                LEFT JOIN ".TB_PREF."project_tasks t ON 
                        wo.task_id = t.task_id AND p.project_id = t.project_id 
		WHERE  wo.id=".db_escape($woid);

	$result = db_query($sql, "Could not get_work_order_header");
    
	return db_fetch($result);
}

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


function get_wo_items($workorder_id, $process_id = 0)
{
	$sql = "SELECT wom.*, 
                    l.location_name, 
                    wc.name AS WorkCentreDescription,
                    sm.description, 
                    sm.mb_flag AS ResourceType, 
                    (sm.material_cost+ sm.labour_cost+ sm.overhead_cost) AS standard_cost, 
                    wom.req_unit, 
                    wom.req_unit_qty * (sm.material_cost+ sm.labour_cost+ sm.overhead_cost) AS ComponentCost 
    	FROM ".TB_PREF."wo_material wom 
                    INNER JOIN ".TB_PREF."wo_processes wop ON 
                            wom.process_id = wop.id 
                    INNER JOIN ".TB_PREF."workcentres wc ON 
                            wop.workcentre_id = wc.id 
                    INNER JOIN ".TB_PREF."locations l ON 
                            wom.loc_code = l.loc_code 
                    INNER JOIN ".TB_PREF."stock_master sm ON 
                            wom.stock_id = sm.stock_id  
    	WHERE wom.workorder_id = ".db_escape($workorder_id)." 
                    AND wom.process_id = ".db_escape($process_id)." 
        ORDER BY wop.sequence, sm.stock_id ";

            
	return db_query($sql, "Workorder items could not be retrieved");
}

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



function add_wo_process($workorder_id, $sequence, $description, 
                        $workcentre_id, $item_description, $item_quantity,
                        $start_date_time, $setup_time, $processing_time, 
                        $cleaning_time, $curing_time, $end_date_time,
                        $qc, $comment, $type_id)
{
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
        
        
	$sql = "INSERT INTO ".TB_PREF."wo_processes( 
                    workorder_id, sequence, 
                    description, workcentre_id, 
                    item_description, item_quantity,
                    start_date_time, setup_time, 
                    processing_time, cleaning_time, 
                    curing_time, end_date_time,
                    qc, comment,
                    type_id,
                    created_by, created_on) 
            VALUES (".db_escape($workorder_id).", ".db_escape($sequence) . ","
                    .db_escape($description) . ", ".db_escape($workcentre_id) . ", "
                    .db_escape($item_description) . ", ".db_escape($item_quantity) . ", "
                    .db_escape($start_date_time) . ", ".db_escape($setup_time) . ", "
                    .db_escape($processing_time) . ", ".db_escape($cleaning_time) . ", "
                    .db_escape($curing_time) . ", ".db_escape($end_date_time) . ", "
                    .db_escape($qc) . ", ".db_escape($comment) . ", "
                    .db_escape($type_id) . ", "
                    .db_escape($created_by) . ", ".db_escape($created_on).")";

	db_query($sql,"Could not add workorder Process");
}

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



function update_wo_process($id, $sequence, $description,  
                            $item_description, $item_quantity, $start_date_time, 
                            $setup_time, $processing_time, $cleaning_time, 
                            $curing_time, $end_date_time, $qc, $comment,
                            $type_id)
{
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
        
        
	$sql = "UPDATE ".TB_PREF."wo_processes  
            SET sequence=".db_escape($sequence).", 
                description = ".db_escape($description) . ",
                type_id = ".db_escape($type_id) . ",
                item_description = ".db_escape($item_description) . ",
                item_quantity = ".db_escape($item_quantity) . ",
                start_date_time= ".db_escape($start_date_time) . ",
                setup_time=".db_escape($setup_time).", 
                processing_time = ".db_escape($processing_time) . ",
                cleaning_time = ".db_escape($cleaning_time) . ",
                curing_time = ".db_escape($curing_time) . ",
                end_date_time= ".db_escape($end_date_time) . ",
                qc = ".db_escape($qc) . ",
                comment = ".db_escape($comment) . ",
                updated_by=".db_escape($updated_by).", 
                updated_on = ".db_escape($updated_on) . " 
            WHERE id = ".db_escape($id); 
                    

	db_query($sql,"Could not update workorder process");
}


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



function update_wo_process_timings($id, $start_date_time, $end_date_time)
{
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
        
        
	$sql = "UPDATE ".TB_PREF."wo_processes  
            SET start_date_time= ".db_escape($start_date_time) . ",
                end_date_time= ".db_escape($end_date_time) . ",
                updated_by=".db_escape($updated_by).", 
                updated_on = ".db_escape($updated_on) . " 
            WHERE id = ".db_escape($id); 
                    

	db_query($sql,"Could not update_wo_process_timings");
    
    return array("success"=>true, "message"=>"");
}
//--------------------------------------------------------------------------------------


function get_wo_labour($workorder_id, $process_id = 0)
{
	$sql = "SELECT l.*, 
                    j.value_name as job_category_name, 
                    r.description as rate_category_name,
                    r.rate,
                    p.setup_time,p.processing_time,p.cleaning_time  
            FROM ".TB_PREF."wo_labour l 
                    INNER JOIN ".TB_PREF."wo_processes p ON 
                                l.process_id = p.id  
                    LEFT JOIN ".TB_PREF."list_values j ON 
                                l.job_category_id = j.id  
                    LEFT JOIN ".TB_PREF."employee_rates r ON 
                                l.rate_category_id = r.id 
                    
    	WHERE l.workorder_id = ".db_escape($workorder_id);
    
    if($process_id > 0){
        $sql .= " AND l.process_id = ".db_escape($process_id);
    }
    
    $sql .= " ORDER BY p.sequence ";
	
	return db_query($sql, "Workorder Labour details could not be retrieved");
}

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


function get_wo_labour_detail($id)
{
	$sql = "SELECT * 
            FROM ".TB_PREF."wo_labour 
            WHERE id = ".db_escape($id);

	$result = db_query($sql, "Could not get workorder labour detail");
	return db_fetch($result);
}

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

function get_wo_process_material($process_id)
{
    $sql = "SELECT 
                    wm.*, 
                    l.location_name, 
                    wc.name AS WorkCentreDescription,
                    sm.description, 
                    sm.mb_flag AS ResourceType, 
                    (sm.material_cost+ sm.labour_cost+sm.overhead_cost) AS standard_cost, 
                    sm.stock_control_method,
                    units,
                    wm.units_req * (sm.material_cost+ sm.labour_cost+ sm.overhead_cost) AS ComponentCost   
            FROM (".TB_PREF."workcentres wc, 
                    ".TB_PREF."locations l, 
                    ".TB_PREF."wo_material wm) 
                    INNER JOIN ".TB_PREF."stock_master sm ON wm.stock_id = sm.stock_id 
            WHERE wm.process_id = ".db_escape($process_id)."                   
                   AND wc.id=wm.workcentre 
                    AND wm.loc_code = l.loc_code 
            ORDER BY wm.id";
	
	return db_query($sql, "The bill of material could not be retrieved");
}

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

function get_component_from_wo_material($id)
{
$sql = "SELECT *
    
        FROM ".TB_PREF."wo_material
           
        WHERE id=".db_escape($id);
       
        $result = db_query($sql, "Wo_material process could not be retrieved");
        return db_fetch($result);
}

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

function get_wo_labour_process($wo_labour)
{
$sql = "SELECT *
    
       FROM ".TB_PREF."wo_labour
           
       WHERE id=".db_escape($wo_labour);
        
     $result = db_query($sql, "Wo_labour process could not be retrieved");
     return db_fetch($result);
}
//------------------------------------------------------------------------------------------


function add_wo_labour($process_id, $job_category_id, $rate_category_id, 
                        $setup, $processing, $cleaning, 
                        $comment, $created_by, $workorder_id)
{
    $created_on = date('Y-m-d H:i:s');
    
	$sql = "INSERT INTO ".TB_PREF."wo_labour (workorder_id, process_id, 
                            job_category_id, rate_category_id, 
                            setup, processing,
                            cleaning, comment,
                            created_by, created_on)
		VALUES (".db_escape($workorder_id).", ".db_escape($process_id) . ","
                .db_escape($job_category_id) . ", ".db_escape($rate_category_id) . ", "
                .db_escape($setup) . ", ".db_escape($processing) . ", "
                .db_escape($cleaning) . ", ".db_escape($comment) . ", "
                .db_escape($created_by) . ", ".db_escape($created_on).")";

	db_query($sql,"Could not add bom labour detail");
}


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

function update_wo_labour($id, $process_id, $job_category_id, 
                            $rate_category_id, $setup, $processing, 
                            $cleaning, $comment, $updated_by)
{

    $updated_on = date('Y-m-d H:i:s');
        
        
	$sql = "UPDATE ".TB_PREF."wo_labour  
            SET process_id=".db_escape($process_id).", 
                job_category_id = ".db_escape($job_category_id) . ",
                rate_category_id =".db_escape($rate_category_id).", 
                setup = ".db_escape($setup) . ",
                processing = ".db_escape($processing) . ",
                cleaning = ".db_escape($cleaning) . ",
                comment = ".db_escape($comment) . ",
                updated_by=".db_escape($updated_by).", 
                updated_on = ".db_escape($updated_on) . " 
            WHERE id = ".db_escape($id); 
                    

	db_query($sql,"Could not update bom labour detail");
}


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


function delete_wo_labour($id)
{        
	$sql = "DELETE FROM ".TB_PREF."wo_labour  
            WHERE id = ".db_escape($id); 
                    

	db_query($sql,"Could not delete_wo_labour");
}

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



function add_wo_process_completed_qty($process_id, $item_quantity, $closed)
{
    $sql = "UPDATE ".TB_PREF."wo_processes  
            SET qty_completed = qty_completed + $item_quantity,
                closed = ".db_escape($closed)."  
            WHERE id = ".db_escape($process_id); 
                    

	db_query($sql,"Could not add_wo_process_completed_qty");
}


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

function close_work_order($woid, $tasks, $current_user_id)
{
    begin_transaction();
    
    $rta_msg = remove_task_allocations(ST_WORKORDER, $woid, $tasks, $current_user_id);
    if($rta_msg['success'] !== true){
        cancel_transaction();
        return $rta_msg;
    }
            
    $result = get_wo_processes($woid);
    while ($process = db_fetch($result)) {
        close_wo_process($process['id']);
        close_workcentre_process_schedules($process['id']);
    }  

    close_work_order_header($woid);
    
    commit_transaction();
    
    return array("success" => true, "tran_no"=>$woid, "message" => "");
}

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

function close_work_order_header($woid)
{
	$sql = "UPDATE ".TB_PREF."workorders SET closed=1 WHERE id = ".db_escape($woid);
	db_query($sql, "could not close work order");
}

//--------------------------------------------------------------------------------------
function close_wo_process($id)
{   
	$sql = "UPDATE ".TB_PREF."wo_processes  
            SET closed = 1 
            WHERE id = ".db_escape($id); 
                    

	db_query($sql,"Could not close_wo_process");
}


function add_wo_pr_detail($wo_material_id, $order_quantity, 
                    $order_price, $order_unit, 
                    $order_unit_qty, $order_unit_conversion_factor, 
                    $required_date, $pr_line_id)
{
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
        
        
	$sql = "INSERT INTO ".TB_PREF."wo_pr_details( 
                    wo_material_id, order_quantity, 
                    order_price, order_unit, 
                    order_unit_qty, order_unit_conversion_factor, 
                    required_date, pr_line_id, 
                    created_by, created_on) 
            VALUES (".db_escape($wo_material_id).", ".db_escape($order_quantity) . ","
                    .db_escape($order_price) . ", ".db_escape($order_unit) . ", "
                    .db_escape($order_unit_qty) . ", ".db_escape($order_unit_conversion_factor) . ", "
                    .db_escape(date2sql($required_date)) . ", ".db_escape($pr_line_id) . ", "
                    .db_escape($created_by) . ", ".db_escape($created_on).")";

	db_query($sql,"Could not add_wo_pr_detail");
}


function update_wo_material_ordered_qty($wo_material_id, $ordered_qty)
{
    
	$sql = "UPDATE ".TB_PREF."wo_material SET 
                    qty_ordered = qty_ordered + $ordered_qty   
            WHERE id = ".db_escape($wo_material_id);

	db_query($sql, "could not update_wo_material_ordered_qty");

}

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

function view_wo_material_line($wo_material_id)
{
    $sql = "SELECT 
                    wm.*,
                    wp.description process_description,
                    wp.workorder_id, 
                    sm.description item_description,
                    wo.date_ item_required_date 
            FROM ".TB_PREF."wo_material wm 
                    INNER JOIN ".TB_PREF."wo_processes wp  
                            ON wm.process_id = wp.id 
                    INNER JOIN ".TB_PREF."workorders wo   
                            ON wp.workorder_id = wo.id 
                    INNER JOIN ".TB_PREF."stock_master sm 
                            ON wm.stock_id = sm.stock_id 
            WHERE wm.id = ".db_escape($wo_material_id)."           
            ORDER BY wm.id";
	
	$result = db_query($sql, "Could not view_wo_material_line");
    
    return db_fetch($result);
}

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

function view_wo_material_pr_lines($wo_material_id)
{
    $sql = "SELECT 
                    wpr.*, 
                    sm.description, 
                    sm.units,
                    prd.requested_unit pr_unit,
                    prd.requested_unit_qty pr_unit_qty,
                    prd.required_date pr_req_date,
                    pr.pr_no    
            FROM ".TB_PREF."wo_pr_details wpr  
                    INNER JOIN ".TB_PREF."wo_material wm 
                            on wpr.wo_material_id = wm.id 
                    INNER JOIN ".TB_PREF."stock_master sm 
                            ON wm.stock_id = sm.stock_id 
                    INNER JOIN ".TB_PREF."purchase_requisition_details prd 
                            ON wpr.pr_line_id = prd.id 
                    INNER JOIN ".TB_PREF."purchase_requisitions pr 
                            ON prd.requisition_id = pr.pr_no  
            WHERE wpr.wo_material_id = ".db_escape($wo_material_id)."                   
            ORDER BY pr.pr_no";
	
	return db_query($sql, "Could not view_wo_material_line");
}

function get_work_order_estimated_material_cost($wo_id)
{
    $sql = "SELECT SUM(sm.material_cost + sm.labour_cost + sm.overhead_cost) AS wo_material_cost 
            FROM ".TB_PREF."wo_processes wop, ".TB_PREF."wo_material wom, ".TB_PREF."stock_master sm 
            WHERE wop.id = wom.process_id AND 
                    wom.stock_id = sm.stock_id AND 
                    wop.workorder_id = ". db_escape($wo_id);
    
    $result = db_query($sql, "Could not view_wo_material_line");
    
    $cost = db_fetch($result);
    if(isset($cost['wo_material_cost']) && $cost['wo_material_cost'] >= 0){
        return $cost['wo_material_cost'];
    }
    else{
        return 0;
    }
}
        
function get_work_order_remaining_material_cost($wo_id)
{
    $sql = "SELECT SUM((sm.material_cost+sm.labour_cost+sm.overhead_cost) * 
                        IF((wm.units_req - wm.units_issued) > 0, (wm.units_req - wm.units_issued), 0))  total_cost 
            FROM ".TB_PREF."wo_material wm, "
                    .TB_PREF."wo_processes wp, "
                    .TB_PREF."workorders wo, "
                    .TB_PREF."stock_master sm 
            WHERE wm.process_id = wp.id AND 
                    wm.stock_id = sm.stock_id AND 
                    wp.workorder_id = wo.id AND 
                    wo.closed = 0 AND 
                    (wm.units_req - wm.units_issued) > 0 AND 
                    wo.id = ".db_escape($wo_id);
    
    //SELECT SUM(sm.material_cost+sm.labour_cost+sm.overhead_cost) * IF((wm.units_req - wm.units_issued) > 0, (wm.units_req - wm.units_issued), 0) total_cost FROM 0_wo_material wm, 0_wo_processes wp, 0_workorders wo, 0_stock_master sm WHERE wm.process_id = wp.id AND wm.stock_id = sm.stock_id AND wp.workorder_id = wo.id AND wo.closed = 0 AND (wm.units_req - wm.units_issued) > 0 AND wo.id = '113'
            
    $result = db_query($sql, "Could not get_work_order_remaining_material_cost");
    
    return db_fetch($result);   
                        
}

function get_work_order_remaining_labour_cost($wo_id)
{
    return  0;
    
    $sql = "SELECT SUM(sm.material_cost+sm.labour_cost+sm.overhead_cost) total_cost 
            FROM ".TB_PREF."wo_material wm, "
                    .TB_PREF."wo_processes wp, "
                    .TB_PREF."workorders wo, "
                    .TB_PREF."stock_master sm 
            WHERE wm.process_id = wp.id AND 
                    wm.stock_id = sm.stock_id AND 
                    wp.workorder_id = wo.id AND 
                    wo.closed = 0 AND 
                    (wm.units_req - wm.units_issued) > 0 AND 
                    wo.id = ".db_escape($wo_id);
    
    $result = db_query($sql, "Could not get_work_order_remaining_material_cost");
    
    return db_fetch($result);   
                        
}

function get_work_order_remaining_total_cost($woid)
{
    $material_cost = 0;
    $wom_cost = get_work_order_remaining_material_cost($woid);
    if(isset($wom_cost['total_cost'])){
        $material_cost = $wom_cost['total_cost'];
    }
       
    $labour_cost = 0;
    $wol_cost = get_work_order_remaining_labour_cost($woid);
    if(isset($wol_cost['total_cost'])){
        $labour_cost = $wom_cost['total_cost'];
    }
    
    return $material_cost + $labour_cost;
}
//--------------------------------------------------------------------------------------
function get_wo_pr_details($purch_req_id)
{
    $sql = "SELECT wpd.*,wm.workorder_id FROM ".TB_PREF."wo_pr_details wpd
            LEFT JOIN ".TB_PREF."wo_material wm ON
                wpd.wo_material_id=wm.id
            WHERE wpd.pr_line_id=".db_escape($purch_req_id);
    
    $result = db_query($sql, "Could not get work order pr details.");
    
    return db_fetch($result);  
           
}
?>