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


$page_security = 'SA_MANUF_REQUESTS';
$path_to_root = "..";
include($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/manufacturing/includes/db/manufacturing_requirements_db.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 = "Manufacturing Requests"), @$_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 . "/projects/includes/db/projects_db.inc");


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

function clear_data()
{
	//return;
        unset($_POST['no_of_points']);
        
}





//------------------------------------------------------------------------------------
if(isset($_GET['ModifyMRNumber']) && isset($_GET['ModifyMRNumber']) > 0)
{
    $id_mno=$_GET['ModifyMRNumber'];
    
   
}


function can_commit()
{
	if ($_POST['project_id'] == -1)
    {
        display_error( _("Select a project."));
        set_focus('project_id');
        return false;
    }
    
    $project_id = get_post('project_id');    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($project_id, $user_id);
    if($cap['success'] !== true) 
    {
        display_error($cap['message']);
        set_focus('project_id');
        return false;
    }
    
    if ($_POST['task_id'] == -1)
    {
        display_error( _("Select a task."));
        set_focus('task_id');
        return false;

    }
        
    if ($_POST['loc_code'] == "")
    {
        display_error( _("Select a Location."));
        set_focus('loc_code');
        return false;
    }


     if ($_POST['stock_item'] == -1)
    {
        display_error( _("Select a item code."));
        set_focus('stock_item');
        return false;
    }

    if (!check_num('tran_qty', 0.0001))
    {
        display_error( _("The quantity entered must be numeric and can not be negative."));
        set_focus('tran_qty');
        return false;
    }

    $stock_id=get_post('stock_item');
    if (!(strlen($stock_id) > 0))
    {
        display_error( _("Please select an item."));
        set_focus('stock_item');
        return false;
    }
    
    $cf = get_convertion_factor($_POST['tran_unit'], $stock_id);
    $quantity = input_num('tran_qty') * $cf['convertion_factor'];

    if(isset($_POST['UPDATE_ITEM'])){
        $mreq = get_manuf_request_details_for_edit(get_post('mid'));
        if ($quantity < $mreq['quantity_ordered'])
        {
            display_error( _("Quantity can not be smaller than the quantity already ordered."));
            set_focus('tran_qty');
            return false;
        }

        if ($mreq['line_complete'] == 1)
        {
            display_error( _("Selected Manufacturing Request is alreay completed."));
            set_focus('tran_qty');
            return false;
        }
    }
    
    return true;
}

function save_manufacturing_request()
{
    if(!can_commit()){
        return;
    }
    
    $stock_id=get_post('stock_item');
    $cf = get_convertion_factor($_POST['tran_unit'], $stock_id);
    $quantity = input_num('tran_qty') * $cf['convertion_factor'];
    
    if(isset($_POST['UPDATE_ITEM']))
    {
        $mid=get_post('mid');

        update_manuf_request($mid,$_POST['project_id'], $_POST['task_id'], $_POST['loc_code'], $_POST['stock_item'],$quantity,$_POST['tran_unit'],$_POST['tran_qty'],
                           $cf['convertion_factor'],date2sql($_POST['req_date']), $_POST['comment']);   
        $Mode = '';
      
        display_notification("Manufacturing Request $mid has been updated.");
      
    }
    else
    {
        $mid = add_manuf_request($_POST['project_id'], $_POST['task_id'], $_POST['loc_code'], $_POST['stock_item'],$quantity,$_POST['tran_unit'],$_POST['tran_qty'],
                           $cf['convertion_factor'],date2sql($_POST['req_date']), $_POST['comment']);  
      
        $Mode = '';
        display_notification("Manufacturing Request $mid has been added.");

    }
    unset($_POST["stock_item"]);
    unset($_POST["loc_code"]);
    unset($_POST["tran_unit"]);
    unset($_POST["tran_qty"]);
    unset($_POST["task_id"]);
            

//    $Ajax->activate('_page_body');
}

if (isset($_POST['ADD_ITEM']) || isset($_POST['UPDATE_ITEM'])) 
{ 
    save_manufacturing_request();

}

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


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


function item_settings($manuf_req_id) 
{
	global $SysPrefs, $path_to_root, $new_item, $pic_height, $Refs, $Ajax;
        
        if($manuf_req_id > 0){
            $manufacturing_req=get_manuf_request_details_for_edit($manuf_req_id);
            
            $project_id = $manufacturing_req['project_id'];    
            $user_id = $_SESSION['wa_current_user']->user;
            $cap = can_access_project($project_id, $user_id);
            if($cap['success'] !== true) 
            {
                display_error($cap["message"]);
                set_focus('project_id');
                exit;
            }

            $_POST['mid']=$manufacturing_req['id'];
            
            if(!isset($_POST['project_id'])){
                $_POST['project_id']=$manufacturing_req['project_id'];
            }
            
            if(!isset($_POST['task_id']) || list_updated('project_id')){
                $_POST['task_id']=$manufacturing_req['task_id'];
            }
            
            if(!isset($_POST['stock_item'])){
                $_POST['stock_item']=$manufacturing_req['stock_id'];
            }
            
            if(!isset($_POST['tran_unit'])){
                $_POST['tran_unit']=$manufacturing_req['tran_unit'];
            }
            
            $_POST['tran_qty']=$manufacturing_req['tran_qty'];
            $_POST['req_date']=sql2date($manufacturing_req['req_date']);
            
            if(!isset($_POST['task_id']) || list_updated('stock_item')){
                $_POST['tran_unit']=$manufacturing_req['tran_unit'];
            }
            
            if(!isset($_POST['loc_code'])){
                $_POST['loc_code']=$manufacturing_req['loc_code'];
            }
            
            $_POST['comment']=$manufacturing_req['comment'];
            
            hidden('mid',$_POST['mid']);
          
        }
    
        $Ajax->activate('task_id');
        
        start_outer_table(TABLESTYLE2);
        table_section_title(_("Enter Manufacturing Request"));
        
        project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true);
        tasks_list_row(_("Task:"), 'task_id', $_POST['project_id'], null, _('Select a task'), true);
        
        //stock_items_list_cells(_("Item:"), 'stock_item', null, true, true);
        $Ajax->activate('wo_material_stock_id');
        start_row();
        label_cell(_("Component:"), "class='label'");

        echo "<td>";
//        if(isset($_POST['wo_material_stock_id'])){
//            echo stock_component_items_list('wo_material_stock_id', '', $_POST['wo_material_stock_id'], false, true);
//
//        }
//        else{
            echo stock_manufactured_items_list('stock_item', null, "",  true);
//        }
        echo "</td>";
        end_row();
        
        $stock_id=get_post('stock_item');
        $Ajax->activate('tran_unit');
        units_list_row(_("Unit:"),'tran_unit',$stock_id);
        amount_row(_('Quantity:'), 'tran_qty');
        locations_list_row("Location:", "loc_code", null, "Select a location", false);
        date_row('Required Date :', 'req_date');
        
       // hidden('mid','mid');

        textarea_row('Comment', 'comment', '', 25, 2);
        
	end_outer_table();
        
        br();

	div_start('controls');
        
        if((isset($_GET['ModifyMRNumber']) && isset($_GET['ModifyMRNumber'])>0) || get_post('mid') > 0)
        {
            $button_staus=false;
        }
        else
        {
            $button_staus=true;
        }
       
        //('addupdate', _("Process"), '',@$_REQUEST['popup'] ? true : 'default');
        submit_add_or_update_center( $button_staus, '', 'both');

	div_end();
}

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

start_form(true);

div_start('details');

$manuf_req_id = 0;
if(isset($_POST['id']) && $_POST['id'] > 0){
    $manuf_req_id = $_POST['id'];
}
elseif(get_post('mid') > 0){
    $manuf_req_id = get_post('mid');
}
item_settings($manuf_req_id);
tabbed_content_end();

div_end();

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

end_form();

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

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