<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_BOM';
$path_to_root = "../..";
include_once($path_to_root . "/includes/session.inc");

page(_($help_context = "Bill Of Materials"));

include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");

include_once($path_to_root . "/includes/inventory.inc");

check_db_has_bom_stock_items(_("There are no manufactured or kit items defined in the system."));

check_db_has_workcentres(_("There are no work centres defined in the system. BOMs require at least one work centre be defined."));

simple_page_mode(true);
$selected_component = $selected_id;
//--------------------------------------------------------------------------------------------------

//if (isset($_GET["NewItem"]))
//{
//	$_POST['stock_id'] = $_GET["NewItem"];
//}
if (isset($_GET['stock_id']))
{
	$_POST['stock_id'] = $_GET['stock_id'];
	$selected_parent =  $_GET['stock_id'];
}

/* selected_parent could come from a post or a get */
/*if (isset($_GET["selected_parent"]))
{
	$selected_parent = $_GET["selected_parent"];
}
else if (isset($_POST["selected_parent"]))
{
	$selected_parent = $_POST["selected_parent"];
}
*/
/* selected_component could also come from a post or a get */
/*if (isset($_GET["selected_component"]))
{
	$selected_component = $_GET["selected_component"];
}
else
{
	$selected_component = get_post("selected_component", -1);
}
*/


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

function display_bom_header($selected_parent, $bom_header)
{
	//$bom_header = get_bom_header($selected_parent);
	div_start('bom');
	start_table(TABLESTYLE2);


    if ($bom_header) {
        $_POST['header_tran_unit'] = $bom_header["tran_unit"]; // by Tom Moulton
        $_POST['header_comments']  = $bom_header["comment"];
        $_POST['header_tran_qty'] = number_format2($bom_header["tran_qty"], get_qty_dec($bom_header["parent"]));
    }


    units_list_row("Unit:", "header_tran_unit", $selected_parent);

	$dec = get_qty_dec($selected_parent);
	$_POST['header_tran_qty'] = number_format2(input_num('header_tran_qty',1), $dec);
	qty_row(_("Quantity:"), 'header_tran_qty', null, null, null, $dec);
    textarea_row(_("Comments:"), "header_comments", null, 31, 2);
    
    	end_table(1);
	div_end();
    
    if ($bom_header) {
        submit_center_first('Update_BOM_Header', _("Update"), '', 'default');
        submit_center_last('Delete_BOM_Header', _("Delete"), _("Cancel Edition"), 'cancel');
    }
    else
    {
        submit_center_first('Add_BOM_Header', _("Save"), '', 'default');
    }

}

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


function display_bom_process($bom_process)
{

	div_start('bom');
	start_table(TABLESTYLE, "width=40%");
	$th = array(_("Sequence"), _("Description"), _("Workcentre"), _("Setup Time"), _("Processing Time"), _("Cleaning Time"), _("Comment"), "", "");
	table_header($th);

	$k = 0;

		alt_table_row_color($k);

		label_cell($bom_process["sequence"]);
        label_cell($bom_process["description"]);
        label_cell($bom_process["workcentre_name"]);
        label_cell($bom_process["setup_time"]);
        label_cell($bom_process["processing_time"]);
        label_cell($bom_process["cleaning_time"]);
        label_cell($bom_process["comment"]);

        edit_button_cell("Edit"."Process_".$bom_process['id'], _("Edit"));
 		delete_button_cell("Delete"."Process_".$bom_process['id'], _("Delete"));
        
        end_row();

	
	end_table();
	div_end();
}

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

function display_bom_items($parent, $process_id)
{
	$result = get_bom_items($parent, $process_id);
	div_start('bom');
	start_table(TABLESTYLE, "width=60%");
	$th = array(_("Code"), _("Description"), _("Location"),
		_("Work Centre"), _("Quantity"), _("Units"),'','');
	table_header($th);

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

		alt_table_row_color($k);

		label_cell($myrow["component"]);
		label_cell($myrow["description"]);
        label_cell($myrow["location_name"]);
        label_cell($myrow["WorkCentreDescription"]);
        qty_cell($myrow["quantity"], false, get_qty_dec($myrow["component"]));
        label_cell($myrow["units"]);
 		edit_button_cell("Edit"."Items_".$myrow['id'], _("Edit"));
 		delete_button_cell("Delete"."Items_".$myrow['id'], _("Delete"));
        end_row();

	} //END WHILE LIST LOOP
	end_table();
	div_end();
}

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



function display_bom_details($selected_parent)
{
    $result = get_bom_processes($selected_parent);
	while ($myrow = db_fetch($result))
	{
        display_bom_process($myrow);
    
        br();
    
        display_bom_items($selected_parent, $myrow['id']);
        
        br(2);

	} //END WHILE LIST LOOP
}

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



function on_submit($selected_parent, $selected_component=-1)
{
	if (!check_num('quantity', 0))
	{
		display_error(_("The quantity entered must be numeric and greater than zero."));
		set_focus('quantity');
		return;
	}

	if ($selected_component != -1)
	{
		update_bom($selected_parent, $selected_component, $_POST['workcentre_added'], $_POST['loc_code'],
			input_num('quantity'));
		display_notification(_('Selected component has been updated'));
		$Mode = 'RESET';
	}
	else
	{

		/*Selected component is null cos no item selected on first time round
		so must be adding a record must be Submitting new entries in the new
		component form */

		//need to check not recursive bom component of itself!
		if (!check_for_recursive_bom($selected_parent, $_POST['component']))
		{

			/*Now check to see that the component is not already on the bom */
			if (!is_component_already_on_bom($_POST['component'], $_POST['workcentre_added'],
				$_POST['loc_code'], $selected_parent))
			{
				add_bom($selected_parent, $_POST['component'], $_POST['workcentre_added'],
					$_POST['loc_code'], input_num('quantity'));
				display_notification(_("A new component part has been added to the bill of material for this item."));
				$Mode = 'RESET';
			}
			else
			{
				/*The component must already be on the bom */
				display_error(_("The selected component is already on this bom. You can modify it's quantity but it cannot appear more than once on the same bom."));
			}

		} //end of if its not a recursive bom
		else
		{
			display_error(_("The selected component is a parent of the current item. Recursive BOMs are not allowed."));
		}
	}
}

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

function display_bom_process_edit_controls($parent, &$Mode, $selected_id)
{
    
    start_table(TABLESTYLE2);
    
    $_POST['bom_process_id'] = 0;
    
    if ($selected_id != -1)
	{
 		if ($Mode == 'Edit') {
			//editing a selected component from the link to the line item
            
            $id = substr($selected_id,8);
			$myrow = get_bom_process($id);

			$_POST['bom_process_id'] = $myrow["id"];
            $_POST['bom_process_sequence'] = $myrow["sequence"];
            $_POST['bom_process_description'] = $myrow["description"];
			$_POST['bom_process_workcentre_id'] = $myrow["workcentre_id"]; // by Tom Moulton
			$_POST['bom_process_setup_time']  = $myrow["setup_time"];
            $_POST['bom_process_processing_time']  = $myrow["processing_time"];
            $_POST['bom_process_cleaning_time']  = $myrow["cleaning_time"];
            $_POST['bom_process_comment']  = $myrow["comment"];
		}
		hidden('selected_id', $selected_id);
	}
	else
	{

	}
	hidden('stock_id', $parent);
    hidden('bom_process_id', $_POST['bom_process_id']);
    
    qty_row("Sequence", 'bom_process_sequence', null, null, null, 0);
    text_row("Description:", 'bom_process_description', null, 50, 200);
    workcenter_list_row("Workcentre", 'bom_process_workcentre_id');
	qty_row(_("Setup Time:"), 'bom_process_setup_time', null, null, null, 0);
    qty_row(_("Processing Time:"), 'bom_process_processing_time', null, null, null, 0);
    qty_row(_("Cleaning Time:"), 'bom_process_cleaning_time', null, null, null, 0);
    qty_row(_("Quantity:"), 'bom_process_quantity', null, null, null, 0);
    textarea_row(_("Comment:"), "bom_process_comment", null, 31, 2);
    
    
	end_table(1);
	//submit_add_or_update_center($selected_id == -1, '', 'both');
    
    if (strlen($selected_id) > 5) {
        submit_center_first('Update_BOM_Process', _("Update"), '', 'default');
        submit_center_last('Delete_BOM_Process', _("Delete"), _("Cancel Edition"), 'cancel');
    }
    else
    {
        submit_center_first('Add_BOM_Process', _("Save"), '', 'default');
    }
    
}
//--------------------------------------------------------------------------------------------------

function display_bom_item_edit_controls($parent, &$Mode, $selected_id)
{
    start_table(TABLESTYLE2);
    
    if ($selected_id != -1)
	{
 		if ($Mode == 'Edit') {
			//editing a selected component from the link to the line item
            $id = substr($selected_id,6);
			$myrow = get_component_from_bom($id);

			$_POST['process_id'] = $myrow["process_id"];
            $_POST['loc_code'] = $myrow["loc_code"];
			$_POST['component'] = $myrow["component"]; // by Tom Moulton
			$_POST['workcentre_added']  = $myrow["workcentre_added"];
			$_POST['quantity'] = number_format2($myrow["quantity"], get_qty_dec($myrow["component"]));
            
            label_row(_("Process:"), $myrow["sequence"] . " - " . $myrow["process_description"]);
			label_row(_("Component:"), $myrow["component"] . " - " . $myrow["description"]);
		}
		hidden('selected_id', $selected_id);
	}
	else
	{
        bom_processes_list_row('Process', 'process_id', $parent);
        
		start_row();
		label_cell(_("Component:"), "class='label'");

		echo "<td>";
		echo stock_component_items_list('component', $parent, null, false, true);
		if (get_post('_component_update')) 
		{
			$Ajax->activate('quantity');
		}
		echo "</td>";
		end_row();
	}
	hidden('stock_id', $parent);

	locations_list_row(_("Location to Draw From:"), 'loc_code', null);
    if(isset($_POST['component'])){
        units_list_row("Unit", 'tran_unit', $_POST['component']);
    }
    else{
        units_list_row("Unit", 'tran_unit', '');
    }
	//workcenter_list_row(_("Work Centre Added:"), 'workcentre_added', null);
	$dec = get_qty_dec(get_post('component'));
	$_POST['quantity'] = number_format2(input_num('quantity',1), $dec);
	qty_row(_("Quantity:"), 'quantity', null, null, null, $dec);
    
    
	end_table(1);
	//submit_add_or_update_center($selected_id == -1, '', 'both');
    
    if (strlen($selected_id) > 5) {
        submit_center_first('Update_BOM_Item', _("Update"), '', 'default');
        submit_center_last('Delete_BOM_Item', _("Delete"), _("Cancel Edition"), 'cancel');
    }
    else
    {
        submit_center_first('Add_BOM_Item', _("Save"), '', 'default');
    }
}

function can_commit_bom_header($alt_unit_info)
{
    if($_POST['header_tran_unit'] == ''){
        display_error("Please select units");
        set_focus('header_tran_unit');
        return false;
    }
    
    if($_POST['header_tran_qty'] <= 0){
        display_error("Quantity entered can not be zero or negative.");
        set_focus('header_tran_qty');
        return false;
    }
    
    if(!$alt_unit_info){
        display_error("Alternative unit conversion factor is not defined for the selected unit.");
        set_focus('header_tran_unit');
        return false;
    }
    return true;
}

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



function can_commit_bom_process()
{
    if(!check_num('bom_process_sequence',0)){
        display_error("The sequence number entered is not valid.");
        set_focus('bom_procees_sequence');
        return false;
    }
    
    return true;
}

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

function save_bom_header($new = true){
    $alt_unit_info = get_alternate_unit_info($_POST['stock_id'], $_POST['header_tran_unit']);
    if(can_commit_bom_header($alt_unit_info)){
        if($new){
            add_bom_header($_POST['stock_id'], $_POST['header_tran_qty'] * $alt_unit_info['convertion_factor'], 
                            $_POST['header_tran_unit'], $_POST['header_tran_qty'], 
                            $alt_unit_info['convertion_factor'], $_POST['header_comments']);
        }
        else{
            update_bom_header($_POST['stock_id'], $_POST['header_tran_qty'] * $alt_unit_info['convertion_factor'], 
                            $_POST['header_tran_unit'], $_POST['header_tran_qty'], 
                            $alt_unit_info['convertion_factor'], $_POST['header_comments']);
        }
    }
}

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

function save_bom_process($new = true){
    
    if(can_commit_bom_process()){
        if($new){
            add_bom_process($_POST['stock_id'], input_num('bom_process_sequence'), 
                            $_POST['bom_process_description'], $_POST['bom_process_workcentre_id'], 
                            input_num('bom_process_setup_time'), input_num('bom_process_processing_time'), 
                            input_num('bom_process_cleaning_time'), $_POST['bom_process_comment']);
        }
        else{
            $bom_process_id = get_post('bom_process_id') ;
            if($bom_process_id > 0){
                update_bom_process(get_post('bom_process_id'), input_num('bom_process_sequence'), 
                                $_POST['bom_process_description'], 
                                input_num('bom_process_setup_time'), input_num('bom_process_processing_time'), 
                                input_num('bom_process_cleaning_time'), $_POST['bom_process_comment']);
            }
        }
        
        return array("success" => true); 
    }
    
    return array("success" => false); 
}

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

if(isset($_POST['Add_BOM_Header'])){
    save_bom_header();    
}

if(isset($_POST['Update_BOM_Header'])){
    save_bom_header(false);    
}

if(isset($_POST['Add_BOM_Process'])){
    $sbp_msg = save_bom_process();   
    if($sbp_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
    }
    
}

if(isset($_POST['Update_BOM_Process'])){
    $sbp_msg = save_bom_process(false);  
    if($sbp_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
    }
}

if ($Mode == 'Delete')
{
	delete_bom($selected_id);

	display_notification(_("The component item has been deleted from this bom"));
	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
	unset($_POST['quantity']);
}

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

start_form();

start_form(false, true);
start_table(TABLESTYLE_NOBORDER);
start_row();
stock_manufactured_items_list_cells(_("Select a manufacturable item:"), 'stock_id', null, false, true);
hidden('stock_id', $_POST['stock_id']);
end_row();
if (list_updated('stock_id'))
	$Ajax->activate('_page_body');
end_table();
br();

//end_form();
//--------------------------------------------------------------------------------------------------

if (get_post('stock_id') != '')
{ //Parent Item selected so display bom or edit component
	$selected_parent = $_POST['stock_id'];
	if ($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM'){
		on_submit($selected_parent, $selected_id);
    }
	//--------------------------------------------------------------------------------------

//start_form();

$bom_header = get_bom_header($selected_parent);

display_bom_header($selected_parent, $bom_header);
if($bom_header){
    br(2);
    
    display_bom_details($selected_parent);

	//--------------------------------------------------------------------------------------
	echo '<br>';

	
    if(substr($selected_id,0,7) == "Process"){
        display_bom_process_edit_controls($selected_parent, $Mode, $selected_id);
    }
    elseif(substr($selected_id,0,5) == "Items"){
        display_bom_item_edit_controls($selected_parent, $Mode, $selected_id);
    }
    elseif($selected_id == -1){
        display_bom_process_edit_controls($selected_parent, $Mode, $selected_id);
        display_bom_item_edit_controls($selected_parent, $Mode, $selected_id);
    }
}
end_form();
}
// ----------------------------------------------------------------------------------

end_page();

?>
