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


$page_security = 'SA_COPY_MANUF_BOM';
$path_to_root = "../..";
include($path_to_root . "/includes/session.inc");
include_once ($path_to_root . "/trace.php");
$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();
	
page(_($help_context = "Copy BOM"), @$_REQUEST['popup'], false, "", $js);

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 . "/payroll/includes/db/payroll_settings_db.inc");
include_once($path_to_root . "/includes/ui/ui_lists_custom.inc");

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


$user_comp = user_company();


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

if (isset($_GET['payroll_id']))
{
	$_POST['payroll_id'] = $_GET['payroll_id'];
}

$payroll_id = get_post('bom_parent');

if (list_updated('payroll_id')) {
	$_POST['NewEmployeeCode'] = $payroll_id = get_post('payroll_id');
    //clear_data();
	$Ajax->activate('details');
	$Ajax->activate('controls');
}

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


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

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


    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"]));
    }
    else{
        $_POST['header_tran_unit'] = '';
        $_POST['header_comments']  = '';
        $_POST['header_tran_qty'] = number_format2(0, get_qty_dec($bom_header["parent"]));
    }

    label_row("Unit:", $_POST['header_tran_unit']);

	$dec = get_qty_dec($selected_parent);
	$_POST['header_tran_qty'] = number_format2(input_num('header_tran_qty',1), $dec);
	label_row("Quantity:", $_POST['header_tran_qty']);
        label_row("Comments:",$_POST['header_comments'] , 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 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 save_bom_header($new = true){
//    $alt_unit_info = get_alternate_unit_info($_POST['bom_parent'], $_POST['header_tran_unit']);
//    if(can_commit_bom_header($alt_unit_info)){
//        if($new){
//            add_bom_header($_POST['bom_parent'], $_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['bom_parent'], $_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 can_copy_bom($parent, $new_bom_parent,$delete_copy=false)
{
//    if(!isset($_POST['parent'] )){
//        display_error("Please select a BOM item to copy new BOM item.");
//        set_focus('new_header_tran_qty');
//        return false;
//    }
    if($new_bom_parent == $parent){
        display_error("Can not copy a BOM to itself. Please select different item.");
        return false;
    }
    
    $mb_flag = get_mb_flag($new_bom_parent);
    if($mb_flag != "M"){
        display_error("Please select a manufacturing item to copy the BOM");
        return false;
    }
    
    if($delete_copy!=true)
    {
        $bom_header = get_bom_header($new_bom_parent);
        if($bom_header)
        {
            display_error("Selected item has a BOM already");
            return false;
        }
    }
    
    if($_POST['new_header_tran_unit'] == ''){
        display_error("Please select units");
        set_focus('new_header_tran_unit');
        return false;
    }
    
    if($_POST['new_header_tran_qty'] <= 0){
        display_error("Quantity entered can not be zero or negative.");
        set_focus('new_header_tran_qty');
        return false;
    }
    
    if($_POST['factor'] <= 0){
        display_error("Factor entered can not be zero or negative.");
        set_focus('factor');
        return false;
    }
    
    
    
//    if(!$alt_unit_info){
//        display_error("Alternative unit conversion factor is not defined for the selected unit.");
//        set_focus('new_header_tran_unit');
//        return false;
//    }
    
    return true;
}

function display_bom_copy_form()
{
    global $Ajax;
    
    $Ajax->activate('new_bom');
    div_start('new_bom');
	start_form(true);
        start_table(TABLESTYLE_NOBORDER);
        start_row();
        stock_manufactured_items_list_cells(_("Select Item to create the BOM:"), 'new_bom_parent', null, false, true);
        end_row();
        end_table();
        
	start_table(TABLESTYLE2);
    $new_bom_header = get_bom_header(get_post('new_bom_parent'));
    if ($new_bom_header) {
        $_POST['new_header_tran_unit'] = $new_bom_header["tran_unit"]; // by Tom Moulton
        $_POST['new_header_comments']  = $new_bom_header["comment"];
        $_POST['new_header_tran_qty'] = number_format2($new_bom_header["tran_qty"], get_qty_dec($new_bom_header["parent"]));
    }
    else{
        $_POST['new_header_tran_unit'] = '';
        $_POST['new_header_comments']  = '';
        $_POST['new_header_tran_qty'] = number_format2(0, get_qty_dec($new_bom_header["parent"]));
    }
       
    units_list_row("Unit:", "new_header_tran_unit", $_POST['new_bom_parent']);

	$dec = get_qty_dec($_POST['new_bom_parent']);
	$_POST['new_header_tran_qty'] = number_format2(input_num('header_tran_qty',1), $dec);
	qty_row(_("Quantity:"), 'new_header_tran_qty', null, null, null, $dec);
    qty_row(_("Factor for BOM Details:"), 'factor', null, null, null, 5);
    textarea_row(_("Comments:"), "new_header_comments", null, 31, 2);

    end_table(1);
	div_end();
    
    submit_center_first('Copy_BOM', _("Copy BOM"), '', 'default');

    submit_center_last('Delete_and_Copy_BOM', _("Delete & Copy"),'', 'default');
    
    end_form();
}
//------------------------------------------------------------------------------------

function general_settings($selected_parent)
{
    $bom_header = get_bom_header($selected_parent);
    
    display_bom_header($selected_parent, $bom_header);
    
    br();
    br();
    
    display_bom_copy_form();
}

//------------------------------------------------------------------------------------
function copy_bom($new_bom_parent,$parent)
{
    if(!can_copy_bom($parent, $new_bom_parent)){
        return;
    }
    
    begin_transaction();
    $bom_header = get_bom_header($parent);
    $new_alt_unit_info = get_alternate_unit_info($new_bom_parent, $_POST['new_header_tran_unit']);
    
    $factor=$_POST['factor'];
    add_bom_header($_POST['new_bom_parent'], $_POST['new_header_tran_qty'] * $new_alt_unit_info['convertion_factor'], 
                    $_POST['new_header_tran_unit'], $_POST['new_header_tran_qty'], 
                    $new_alt_unit_info['convertion_factor'], $_POST['new_header_comments']);

    $new_bom_processes=get_bom_processes($parent);
    while($new_bom_process_rw=db_fetch($new_bom_processes))
    {
        add_bom_process($_POST['new_bom_parent'], $new_bom_process_rw['sequence'], 
                $new_bom_process_rw['description'], $new_bom_process_rw['workcentre_id'], 
                $new_bom_process_rw['item_description'],
                $new_bom_process_rw['item_quantity']*$factor,$new_bom_process_rw['setup_time']*$factor, $new_bom_process_rw['processing_time']*$factor, 
                $new_bom_process_rw['cleaning_time']*$factor, $new_bom_process_rw['qc'], 
                $new_bom_process_rw['comment'], $new_bom_process_rw['type_id']);

        $new_bom_new_process_id = db_insert_id();
        $new_bom_items=get_bom_items($parent, $new_bom_process_rw['id']);

        while($new_bom_item=db_fetch($new_bom_items))
        {
            add_bom_material($_POST['new_bom_parent'], $new_bom_new_process_id, $new_bom_item['component'], $new_bom_item['workcentre_added'], $new_bom_item['loc_code'], $new_bom_item['quantity']*$factor, $new_bom_item['tran_unit'], 
                    $new_bom_item['tran_qty']*$factor, $new_bom_item['conversion_factor'], $new_bom_item['comment']);
        }

        $new_bom_labour_data=get_bom_labour($parent, $new_bom_process_rw['id']);

        while($new_bom_labour=db_fetch($new_bom_labour_data))
        {
            add_bom_labour($_POST['new_bom_parent'], $new_bom_new_process_id, $new_bom_labour['job_category_id'], $new_bom_labour['rate_category_id'], $new_bom_labour['setup'], $new_bom_labour['processing'], $new_bom_labour['cleaning']);
        }

    }
    
    commit_transaction();

        
    display_notification("New BOM copied to item ".$_POST['new_bom_parent']);

    
}
//-------------------------------------------------------------------------------------------- 
function delete_and_copy_bom($new_bom_parent,$parent)
{
    if(!can_copy_bom($parent, $new_bom_parent,true)){
        return;
    }
    
    $deleting_bom_header = get_bom_header($new_bom_parent);

    begin_transaction();
    
    $bom_processes_for_delete=get_bom_processes($deleting_bom_header['parent'],true);
    while($del_bom_process_rw=db_fetch($bom_processes_for_delete))
    {

        $bom_labour_for_delete=get_bom_labour($deleting_bom_header['parent'], $del_bom_process_rw['id']);

        while($bom_labour_for_delete_rw=db_fetch($bom_labour_for_delete))
        {
            delete_bom_labour($bom_labour_for_delete_rw['id']);
        }

        $bom_material_for_delete=get_bom_items($deleting_bom_header['parent'], $del_bom_process_rw['id']);

        while($bom_material_for_delete_rw=db_fetch($bom_material_for_delete))
        {
            delete_bom_material($bom_material_for_delete_rw['id']);
        }

        delete_bom_process($del_bom_process_rw['id']);

    }

    delete_bom_header($deleting_bom_header['parent']);
    
    commit_transaction();
    //return;
    
    $old_bom =get_bom_header($deleting_bom_header['parent']);
    if($old_bom)
    {
        display_error("Could not delete BOM master item");
        return;
    }
 
    copy_bom($new_bom_parent, $parent);
//
//
//    $factor=$_POST['factor'];
//
//    add_bom_header($_POST['new_bom_parent'], $_POST['new_header_tran_qty'] * $new_alt_unit_info['convertion_factor'], 
//                    $_POST['new_header_tran_unit'], $_POST['new_header_tran_qty'], 
//                    $new_alt_unit_info['convertion_factor'], $_POST['new_header_comments']);
//
//    $new_bom_processes=get_bom_processes($parent);
//    while($new_bom_process_rw=db_fetch($new_bom_processes))
//    {
//        add_bom_process($_POST['new_bom_parent'], $new_bom_process_rw['sequence'], $new_bom_process_rw['description'], $new_bom_process_rw['workcentre_id'], $new_bom_process_rw['item_description'],
//                $new_bom_process_rw['item_quantity']*$factor,$new_bom_process_rw['setup_time']*$factor, $new_bom_process_rw['processing_time']*$factor, $new_bom_process_rw['cleaning_time']*$factor, $new_bom_process_rw['qc'], $new_bom_process_rw['comment']);
//
//        $new_bom_new_process_id = db_insert_id();
//        $new_process_items=get_bom_items($parent, $new_bom_process_rw['id']);
//
//        while($new_process_item=db_fetch($new_process_items))
//        {
//            add_bom_material($_POST['new_bom_parent'], $new_bom_new_process_id, $new_process_item['component'], $new_process_item['workcentre_added'], $new_process_item['loc_code'], $new_process_item['quantity']*$factor, $new_process_item['tran_unit'], 
//                    $new_process_item['tran_qty']*$factor, $new_process_item['conversion_factor']);
//        }
//
//        $new_process_labour_data=get_bom_labour($parent, $new_bom_process_rw['id']);
//
//        while($new_process_labour=db_fetch($new_process_labour_data))
//        {
//            add_bom_labour($_POST['new_bom_parent'], $new_bom_new_process_id, $new_process_labour['job_category_id'], $new_process_labour['rate_category_id'], $new_process_labour['setup'], $new_process_labour['processing'], $new_process_labour['cleaning']);
//        }
//
//    }
        
        
    
}



if(isset($_POST['Copy_BOM'])){
     copy_bom(get_post('new_bom_parent'),get_post('bom_parent'));    
}

if(isset($_POST['Delete_and_Copy_BOM'])){
    delete_and_copy_bom(get_post('new_bom_parent'),get_post('bom_parent'));    
}


start_form(true);

if (!isset($_POST['payroll_id']))
        $_POST['payroll_id'] = get_global_payroll_id ();


start_table(TABLESTYLE_NOBORDER);
start_row();
stock_manufactured_items_list_cells(_("Select BOM Item to copy from:"), 'bom_parent', null, false, true);
//hidden('bom_parent', $_POST['bom_parent']);
end_row();

    
end_table();



if (list_updated('bom_parent')){
	$Ajax->activate('_page_body');
    $Ajax->activate('bom');
}
//$result = get_all_table_values($_POST['table_id']);

set_global_payroll_id($_POST['payroll_id']);



div_start('details');

$bom_parent = get_post('bom_parent');

$bom_header = get_bom_header($bom_parent);
if (!$bom_header){
	unset($_POST['_tabs_sel']); // force settings tab for new customer
}
  
general_settings($_POST['bom_parent']); 

br();


div_end();


hidden('popup', @$_REQUEST['popup']);

end_form();

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

end_page(@$_REQUEST['popup']);
?>
