<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_MANUF_REQUIREMENTS';
$path_to_root = "..";
include($path_to_root . "/includes/session.inc");
add_access_extensions();

//page(_($help_context = "Manufacturing Requirements"));

//include_once($path_to_root . "/requisitions/includes/modules_db.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/ui/ui_lists.inc");
include_once($path_to_root . "/manufacturing/includes/db/manufacturing_requirements_db.inc");
include_once($path_to_root . "/inventory/includes/db/alternate_units_db.inc");
include_once($path_to_root . "/sales/includes/db/sales_order_db.inc");

$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 = "Manufacturing Requirements"), false, false, "", $js);


simple_page_mode(true);
//-----------------------------------------------------------------------------------
if(isset($_GET['po'])) {
	if($_GET['po'] == 'yes') {
		if (generate_po())
			display_notification(_("Purchase orders has been generated."));
		else
			display_error(_("Purchase orders generation failed."));
	}
}

$new_record_selection = false;
if(strlen($selected_id) > 10){
    $new_record_selection = true;
}
//UpdatePrPoLine_SOD_5
//UpdatePrPoLine_MNR_5
if(substr($selected_id, 0, 14) == "UpdatePrPoLine"){
    //_SOD_5 or  _MNR_5
    $selected_id = substr($selected_id, 14);
    $_POST["update_type"] = "update_pr_po_line";
}

if(substr($selected_id, 0, 7) == "NewLine"){
    $selected_id = substr($selected_id, 7);
    $_POST["update_type"] =  "new_line";
}

if(substr($selected_id, 0, 6) == "Delete"){
    $selected_id = substr($selected_id, 6);
    $_POST["update_type"] =  "delete_line";
}



function check_data()
{
	if (!get_post('order_line_id') > 0)
	{
		display_error(_("No Order line selected."));
		set_focus('qty');
		return false;
	}
    
    if (!check_num('manufacturing_unit_qty',0))
	{
		display_error(_("Manufacturing quantity entered is negative or invalid."));
		set_focus('qty');
		return false;
	}
    
    if (strlen($_POST['manufacturing_unit_qty']) == 0) 
	{
		display_error(_("Manufacturing quantity can not be zero."));
		set_focus('qty');
        return false;
	}
        
    if (!is_date($_POST['start_on_date'])) 
	{
		display_error(_("Start On date entered is not a valid date."));
		set_focus('start_on_date');
        return false;
	}
    
    if (!is_date($_POST['complete_before_date'])) 
	{
		display_error(_("Complete Before date entered is not a valid date."));
		set_focus('complete_before_date');
        return false;
	}
    
    if(date1_greater_date2($_POST['start_on_date'], $_POST['complete_before_date'])){
        display_error(_("Complete Before date can not be earlier than Start On date."));
		set_focus('start_on_date');
        return false;
    }
    
    if ($_POST['location'] =='') 
	{
		display_error(_("Please select a location."));
		set_focus('location');
                return false;
	}
    
    if (!($_POST['task_id'] > 0)) 
	{
		display_error(_("Please select a task."));
		set_focus('task_id');
                return false;
	}
    return true;

}

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

function display_open_manufacturing_requirements()
{
    global $systypes_array;
    
    $result = get_open_manufacturing_requirements();


    start_form();
    start_table(TABLESTYLE, "width=98%");

    $th = array(_("Id"), _("Project"), _("Type"), _("No."), _("Item"),
                _("Units"), _("Req. Qty"),  _("Odr. Qty"), _("Required Date"), 
                _("Order Type"), _("Unit"), _("Qty"), _("Start On"), _("Complete Before"), "", "", "","");

    table_header($th);
    $k = 0;
    $previuos_stock_id = "";
    $previuos_pr_line_id = 0;

    while ($myrow = db_fetch($result)) 
    {
        if($previuos_stock_id == $myrow["stk_code"] && $previuos_pr_line_id == $myrow["id"]){
            $k++;
        }

        $previuos_stock_id = $myrow["stk_code"];
        $previuos_pr_line_id = $myrow["id"];


        alt_table_row_color($k);

        label_cell($myrow["id"]);
        label_cell($myrow["project"]);
        label_cell($systypes_array[$myrow["source_type"]]);
        label_cell($myrow["order_no"]);
        label_cell($myrow["stk_code"]." - ".$myrow["description"]);
        label_cell($myrow["tran_unit_name"]);
        label_cell($myrow["tran_unit_quantity"]);
        if(isset($myrow["quantity_ordered"]) && $myrow["quantity_ordered"] != 0){
            label_cell($myrow["quantity_ordered"]/$myrow["conversion_factor"]);
        }
        else{
            label_cell("");
        }
        
        label_cell(sql2date($myrow["required_date"]));

        if(isset($myrow["order_type"]) && $myrow["order_type"] > 0){
            label_cell($systypes_array[$myrow["order_type"]]);
        }
        else{
            label_cell("");
        }
        label_cell($myrow["manufacturing_unit"]);
        label_cell($myrow["manufacturing_unit_qty"]);
        label_cell(sql2date($myrow["start_on"]));
        label_cell(sql2date($myrow["required_by"]));
        //label_cell($myrow["loc_code"]);

        switch ($myrow['source_type']) {
            case ST_SALESORDER:
                $rec_type = "SOD";
                break;
            case ST_MANUF_REQUEST:
                $rec_type = "MNR";
                break;

            default:
                break;
        }

            if(isset($myrow['id']) && $myrow['id'] > 0){
                //edit_button_cell("EditNewLine".$myrow['pr_line_id'], _("New"));
                button_cell("EditNewLine_".$rec_type."_".$myrow['id'], _("New"), false, 'add.png');
            }
            else{
                label_cell('');
            }

            if(isset($myrow['mr_id']) && $myrow['mr_id'] > 0){
                edit_button_cell("EditUpdatePrPoLine_".$rec_type."_".$myrow['mr_id'], _("Edit"));
                delete_button_cell("Delete".$myrow['mr_id'], _("Delete"));

            }
            else{
                label_cell('');
                label_cell('');
            }
            label_cell(get_trans_view_str(ST_MANUF_REQUIREMENT,$myrow["mr_id"]));
        end_row();
    }
    end_table(1);
}


function display_manufacturing_requirement_edit_controls($selected_id, $new_record_selection)
{
    start_outer_table(TABLESTYLE2, "width=60%"); // outer table

    if ($selected_id != -1) 
    {
        if(substr($selected_id,0,5) == "_SOD_"){

            $myrow = get_manufacturing_requirements(get_post('update_type'), $selected_id);
        }
        elseif(substr($selected_id,0,5) == "_MNR_"){
            $myrow = get_manufacturing_requirements_from_manufacturing_request(get_post('update_type'), $selected_id);
        }


        $_POST['order_line_id']  = $myrow["id"];
        $_POST['project']  = $myrow["project"];
        $_POST['type']  = $myrow["source_type"];
        $_POST['doc_no']  = $myrow["order_no"];
        $_POST['item_code']  = $myrow["stk_code"];
        $_POST['item_description'] = $myrow["description"];
        $_POST['description']  = $myrow["description"];
        $_POST['order_unit']  = $myrow["tran_unit_name"];
        $_POST['order_unit_qty']  = $myrow["tran_unit_quantity"];
        $_POST['delivery_date']  = $myrow["required_date"];
        if(get_post('update_type') == "update_pr_po_line"){
            $_POST['manufacturing_unit']  = $myrow["manufacturing_unit"];
            $_POST['manufacturing_unit_qty']  = $myrow["manufacturing_unit_qty"];
            $_POST['wo_start_date']  = sql2date($myrow["start_on"]); 
            $_POST['wo_end_date']  = sql2date($myrow["required_by"]);        
            $_POST['location']  = $myrow["loc_code"];
            $_POST['task_id']  = $myrow["task_id"];
        }
        else{
            $_POST['manufacturing_unit']  = $myrow["tran_unit_name"];
            $_POST['wo_start_date']  = sql2date($myrow["required_date"]);
            $_POST['wo_end_date']  = sql2date($myrow["required_date"]);
            $_POST['manufacturing_unit_qty'] = $myrow["tran_unit_quantity"];
            $_POST['location']  = $myrow["loc_code"];
            $_POST['task_id']  = $myrow["source_task_id"];
        }
        
        $_POST['mreq_row_state']  = $myrow["mreq_row_state"];
        $_POST['source_row_state']  = $myrow["source_row_state"];
        $_POST['project_id'] = $myrow["project_id"];

        if(!isset($_POST['manufacturing_unit'])){
            $_POST['manufacturing_unit']  = $myrow["manufacturing_unit"];
        }

       if(!isset($_POST['location'])){
            $_POST['location']  = $myrow["loc_code"];
        }
       // $_POST['row_state']  = db_new_row_state($row_state);
        hidden('type', $_POST['type']);
        hidden('doc_no', $_POST['doc_no']);
        hidden('order_line_id', $_POST['order_line_id']);
        hidden('mreq_row_state', $_POST['mreq_row_state']);
        hidden('source_row_state', $_POST['source_row_state']);
        hidden('project_id', $_POST['project_id']);
        hidden('selected_id', $selected_id);
    } 

    $res = get_item_edit_info(get_post('item_code'));
    $dec =  $res["decimals"] == '' ? 0 : $res["decimals"];
    $units = $res["units"] == '' ? _('kits') : $res["units"];

    table_section(1);

    if(isset($_POST['project'])){
        label_row("Project Description:", $_POST['project']);
    }
    else {
        label_row("Project Description:", '');
    }

    if(isset($_POST['type'])){
        label_row("Type:", $_POST['type']);
    }
    else {
        label_row("Type:", '');
    }

    if(isset($_POST['doc_no'])){
        label_row("Doc. No:", $_POST['doc_no']);
    }
    else {
        label_row("Doc. No:", '');
    }
    hidden('item_code',get_post('item_code'));


    if(isset($_POST['item_code'])){
        label_row("Item Code:", $_POST['item_code']);
    }
    else {
        label_row("Item Code:", '');
    }

    if(isset($_POST['item_description'])){
        label_row("Item Description:", $_POST['item_description']);
    }
    else {
        label_row("Item Description:", '');
    }

    if(isset($_POST['order_unit_qty'])){
        label_row("Quantity:", number_format2($_POST['order_unit_qty'],$dec));
    }
    else {
        label_row("Quantity:", 0);
    }


    if(isset($_POST['order_unit'])){
        label_row("Unit:",$_POST['order_unit']);
    }
    else {
        label_row("Unit:", 0);
    }

    if(isset($_POST['delivery_date'])){
        label_row("Delivery Date:", sql2date($_POST['delivery_date']));
    }
    else {
        label_row("Delivery Date:", '');
    }


    if(isset($_POST['pr_complete'])){
        $pr_line_complete = $_POST['pr_complete'];
    }
    else {
        $pr_line_complete = 0;
    }
    yesno_list_row("Close:", "pr_complete",$pr_line_complete);



    table_section(2, "50%");



    $manuf_unit = "";
    if(get_post('manufacturing_unit') != "")
    {
        $manuf_unit = get_post('manuf_unit');
    }

    units_list_row(_("Manufacturing Unit:"), 'manufacturing_unit', get_post('item_code'), $manuf_unit, false, true);

    $manuf_unit_conversion = get_convertion_factor($_POST['manufacturing_unit'], get_post('item_code'));
    hidden('manuf_unit_conversion_factor', $manuf_unit_conversion['convertion_factor']);

    $manufacturing_unit_qty = 0;

    if(get_post("update_type") == "update_pr_po_line"){
        $manufacturing_unit_qty = 0;
        if(list_updated('manufacturing_unit')){
            $manufacturing_unit_qty = input_num('order_unit_qty') * get_post('manuf_unit_conversion_factor');
        }
        else{
            $manufacturing_unit_qty = input_num('manufacturing_unit_qty');
        }
    }

    if(get_post("update_type") == "new_line"){
       $_POST['manufacturing_unit_qty'] = number_format2($manufacturing_unit_qty, $dec);
    }
    $_POST['manufacturing_unit_qty'] = $manufacturing_unit_qty;
    qty_row(_("Manufacturing Qty:"), 'manufacturing_unit_qty', null, '', null, $dec);

    if($new_record_selection){
        if(get_post('update_type') == "update_pr_po_line"){
            $_POST['start_on_date'] = $_POST['wo_start_date'];
        }
        elseif(get_post('update_type') == "new_line"){
            $_POST['start_on_date'] = $_POST['wo_start_date'];
        }
    }
    date_row("Start On:", 'start_on_date');

    if($new_record_selection){
        if(get_post('update_type') == "update_pr_po_line"){
            $_POST['complete_before_date'] = $_POST['wo_end_date'];
        }
        elseif(get_post('update_type') == "new_line"){
            $_POST['complete_before_date'] = $_POST['wo_end_date'];
        }
    }
    date_row("Complete Before:", 'complete_before_date');
    
    locations_list_row("Location:", 'location', null,'Select a Location', false);

    if(isset($_POST['project_id'])){
        $project_id = $_POST['project_id'];
    }
    else {
        $project_id = 0;
    }
    tasks_list_row("Task:", "task_id", $project_id, null, "Select a task");
    

    //hidden('source_row_state', $_POST['source_row_state']);






    //end_table(1);
    end_outer_table(1); // outer table

}

function update_manu_requirement($selected_id)
{
    $order_unit = $_POST['manufacturing_unit'];

    get_convertion_factor2($_POST['item_code'], $order_unit, $conversion_factor);
    
    $base_unit_order_qty = $_POST['manufacturing_unit_qty'] * $conversion_factor;
   
    $selected_id = substr($selected_id,5);
    
    $item = get_stock_item_edit_info($_POST['item_code']);
    if($item['mb_flag'] == "M"){
        $order_type = ST_WORKORDER;
    }
    elseif($item['mb_flag'] == "B"){
        $order_type = ST_PURCH_REQ;
    }
    
    $start_on_date = date2sql($_POST['start_on_date']);
    $start_on_date .= " 08:00:00"; 
    $complete_before_date = date2sql($_POST['complete_before_date']);
    $complete_before_date .= " 17:00:00"; 
    
    $umr = update_manufacturing_requirement($selected_id,  $_POST['type'],$_POST['doc_no'],
                                    $_POST['order_line_id'],$base_unit_order_qty, $_POST['manufacturing_unit'],
                                    $base_unit_order_qty,$conversion_factor , $complete_before_date, 
                                    $_POST['location'], $_POST['task_id'], $order_type,
                                    0,get_post('source_row_state'), get_post('mreq_row_state'), $start_on_date);
    
    return $umr;
}

function add_manu_requirement($selected_id)
{
    $order_unit = $_POST['manufacturing_unit'];
    
    get_convertion_factor2($_POST['item_code'], $order_unit, $conversion_factor);
    
    $manuf_base_unit_qty = $_POST['manufacturing_unit_qty'] * $conversion_factor;
    
    $selected_id=substr($selected_id,5);    
    
    $item = get_stock_item_edit_info($_POST['item_code']);
    if($item['mb_flag'] == "M"){
        $order_type = ST_WORKORDER;
    }
    elseif($item['mb_flag'] == "B"){
        $order_type = ST_PURCH_REQ;
    }
    
    $start_on_date = date2sql($_POST['start_on_date']);
    $start_on_date .= " 08:00:00"; 
    $complete_before_date = date2sql($_POST['complete_before_date']);
    $complete_before_date .= " 17:00:00"; 
    
    add_manufacturing_requirement($selected_id, $_POST['type'],$_POST['doc_no'],
                                    $_POST['order_line_id'], $_POST['item_code'], $manuf_base_unit_qty, 
                                    $_POST['manufacturing_unit'],$_POST['manufacturing_unit_qty'],$conversion_factor,
                                    $complete_before_date, $_POST['location'], get_post('project_id'),
                                    $_POST['task_id'], $order_type, 0, 
                                    get_post('source_row_state'), $start_on_date);

}

if(isset($_POST['update_pr_po_line']) && check_data()){

    $umr = update_manu_requirement($selected_id);

    if($umr["success"] !== true){
        display_error($umr["message"]);
    }
    else{
        $Mode = 'RESET';
        display_notification(_('Selected requisition details has been updated.'));
    }
}
                

if(isset($_POST['new_line'])&& check_data()){
     
    add_manu_requirement($selected_id);
    
    $Mode = 'RESET';
  
    display_notification(_('Selected requisition details has been updated.'));
	
} 

if(isset($_POST['Delete'.$selected_id])){
    
     delete_manufacturing_requirement($selected_id);
     $selected_id = -1;
}
//-----------------------------------------------------------------------------------

if ($Mode == 'RESET')
{
	$selected_id = -1;
	$sav = get_post('show_inactive');
	unset($_POST);
}


display_open_manufacturing_requirements();

hidden('update_type',get_post("update_type"));


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

//start_table(TABLESTYLE2);

display_manufacturing_requirement_edit_controls($selected_id, $new_record_selection);


//submit_add_or_update_center($selected_id == -1, '', 'both');
//submit_add_or_update(false);

if(get_post('update_type') == "update_pr_po_line"){
    submit("update_pr_po_line", "Update" );
}
elseif(get_post('update_type') == "new_line"){
    submit("new_line", "Add" );
}


end_form();

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

end_page();

?>
