<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_STOCK_COUNT';
$path_to_root = "..";

include_once($path_to_root . "/includes/ui/items_cart.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/ui/ui_controls.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/inventory/includes/stock_count_ui.inc");
include_once($path_to_root . "/inventory/includes/db/stock_count_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");


$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(800, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();


//------------
// check weather the record is a new one or a modify 

 //unset ($_SESSION['page_title']);
//if (isset($_GET['CompleteStockCountNo']) && is_numeric($_GET['CompleteStockCountNo'])) {
//
//	$help_context = 'Modifying Stock Count';
//	//$_SESSION['stock_counts'] = sprintf( _("Modifying Stock Count # %d"), $_GET['ModifyStockCountNo']);
//        $_SESSION['complete'] = $_GET['CompleteStockCountNo'];
//	create_cart(ST_INVADJUST, $_GET['CompleteStockCountNo']);
//    }
if (isset($_GET['ModifyStockCountNo']) && is_numeric($_GET['ModifyStockCountNo'])) {
        //unset($_SESSION['complete']);
	$help_context = 'Modifying Stock Count';
	$_SESSION['page_title'] = sprintf( _("Update Stock Count # %d"), $_GET['ModifyStockCountNo']);
	create_cart(ST_STOCK_COUNT, $_GET['ModifyStockCountNo']);
    }
 else {
        
	if(isset($_GET['NewStockCount'])){
           $NewStockCount = true;
            $_SESSION['page_title'] = _($help_context = "New Stock Count Entry");
             create_cart(ST_STOCK_COUNT, 0);               
        }
        else {  
	}
 }
 
page($_SESSION['page_title'], false, false, "", $js);
 
//-----------

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

check_db_has_costable_items(_("There are no inventory items defined in the system which can be adjusted (Purchased or Manufactured)."));

check_db_has_movement_types(_("There are no inventory movement types defined in the system. Please define at least one inventory adjustment type."));

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

if (isset($_GET['AddedID'])) 
{
	$trans_no = $_GET['AddedID'];
	$trans_type = ST_STOCK_COUNT;

	display_notification_centered(_("Stock count ".$trans_no." has been created"));
        
	display_note(get_trans_view_str($trans_type, $trans_no, _("&View this Stock Count")), 0, 1);

	display_note(print_document_link($trans_no, _("&Print this Stock Count"), true, $trans_type), 0, 1);

	//hyperlink_no_params($_SERVER['PHP_SELF'], _("Enter &Another Stock Count"));
        submenu_option(_("Enter &Another Stock Count"),	"/inventory/stock_count.php?NewStockCount=Yes");

        
	display_footer_exit();
}
//--------------------------------------------------------------------------------------------------

function line_start_focus() {
  global 	$Ajax;

  $Ajax->activate('items_table');
  set_focus('_stock_id_edit');
}


function can_process()
{
	$adj = &$_SESSION['stock_counts'];//passing values by reference

	if (count($adj->line_items) == 0){
		display_error(_("You must enter at least one non empty item line."));
		set_focus('stock_id');
		return false;
	}
          if (($_POST['reference'] == "")){
		display_error(_("Reference can not be empty"));
		set_focus('des');
		return false;
	}
        if ($adj->order_no == 0 && !is_new_reference($_POST['reference'], ST_STOCK_COUNT)) 
	{
		display_error( _("The entered reference is already in use."));
		set_focus('ref');
		return false;
	}
        
        if ($adj->order_no > 0) 
	{
		$ref = check_stock_count_reference($adj->order_no, $_POST['reference']);
                if($ref){
                    display_error( _("The entered reference is already in use."));
                    set_focus('ref');
                    return false;
                }
	}
	
	return true;
}


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

if (isset($_POST['Process']) && can_process()){
    
    if(isset($_SESSION['stock_counts']->updated_on)){
        $trans_no = update_stock_count($_SESSION['stock_counts'], $_POST['Location'], $_POST['reference'], 
                                        SC_UPDATED, $_POST['tran_date'], $_POST['comments'],
                                        $_POST['project_id'],$_POST['task_id']);
        unset($_SESSION['stock_counts']);
   	meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
    else{
       $trans_no = add_stock_count($_SESSION['stock_counts'], $_POST['Location'], $_POST['reference'], 
                                        SC_NEW , $_POST['tran_date'],$_POST['comments']
                                        ,$_POST['project_id'],$_POST['task_id']);
	unset($_SESSION['stock_counts']);
   	meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
    
} 
//-----------------------------------------------------------------------------------------------

function check_item_data()
{
    
//    $dec = get_qty_dec($_POST['stock_id']);
//	$min = 1 / pow(10, $dec);
    
    if (!check_num('qty',0))
    {
    	$min = number_format2($min, $dec);
	   	display_error(_("The quantity of the count item must be numeric and not less than ").$min);
		set_focus('qty');
	   	return false;
    }

   	return true;
}

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

function create_cart($trans_type, $stock_count_id)
{ 
	global $Refs;

	if (!$_SESSION['SysPrefs']->db_ok) // create_cart is called before page() where the check is done
		return;

        unset ($_SESSION['stock_counts']);
		$_SESSION['stock_counts'] = new items_cart(ST_STOCK_COUNT);
//	$_POST['tran_date'] = new_doc_date();
//	if (!is_date_in_fiscalyear($_POST['tran_date']))
//		$_POST['tran_date'] = end_fiscalyear();	
               
        if ($stock_count_id) {
            read_stock_count($stock_count_id, $_SESSION['stock_counts'], $trans_type);
		$_SESSION['stock_counts']->order_no = $stock_count_id;
	} else{
                $_SESSION['stock_counts']->order_no = $stock_count_id;
                $_SESSION['stock_counts']->trans_type = $trans_type;
        } 
	copy_from_cart();
}
function read_stock_count($stock_count_id, &$order, $trans_type)
{   
      $sc_header = get_stock_count_header($stock_count_id);
      
      copy_to_cart($sc_header, $stock_count_id);

        $order->loc_code = $sc_header["loc_code"];    
        $order->location = $sc_header["location_name"];
        $order->status_id = $sc_header["status_id"];      
        $order->tran_date = $sc_header["tran_date"];
        $order->reference = $sc_header["reference"];
        $order->comment = $sc_header["comments"];
        $order->project_id = $sc_header["project_id"];
        $order->task_id = $sc_header["task_id"];
      
      $result = get_stock_count_details($stock_count_id);
      if (db_num_rows($result) > 0){
        $line_no=0;
            while ($sc_lines = db_fetch($result)){
                add_stock_order($order, $sc_lines["stock_id"],
                                $sc_lines["counted_qty"],$sc_header["location_name"],
                                $sc_lines["description"], $sc_lines["status_id"], 
                                $sc_header["created_on"], $sc_lines["id"], 
                                $sc_lines["standard_cost"]);
                $order->line_items[$line_no]->row_id = $sc_lines["id"] ;
                $order->line_items[$line_no]->created_by = $sc_lines["created_by"] ;
                $order->line_items[$line_no]->created_on = $sc_lines["created_on"] ;
             $line_no++;       
            } 
      } 
  
}
//-------

function handle_update_item()
{
    if($_POST['UpdateItem'] != "" && check_item_data())
    {
		$id = $_POST['LineNo'];
    	$_SESSION['stock_counts']->update_cart_item($id, input_num('qty'), '', '');
    }
	line_start_focus();
}

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

function handle_delete_item($id)
{
	$_SESSION['stock_counts']->remove_from_cart($id);
	line_start_focus();
}

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

function handle_new_item()
{
        if(!isset($_SESSION['stock_counts']->status_id)){
                if (!check_item_data())
                    return;

                add_stock_order($_SESSION['stock_counts'], $_POST['stock_id'], 
                                input_num('qty'), $_POST['Location'], '5', $_POST['tran_date'], 0, 0);
                //copy_to_cart();
                line_start_focus();
        }
        else {
                if (!check_item_data())
                    return;
                add_stock_order($_SESSION['stock_counts'], $_POST['stock_id'], input_num('qty'), 
                        $_POST['Location'],$_SESSION['stock_counts']->status_id, 
                        $_SESSION['stock_counts']->tran_date, 0, 0);
                //copy_to_cart();
                line_start_focus();
        }
}

//-----------------------------------------------------------------------------------------------
$id = find_submit('Delete');
if ($id != -1)
	handle_delete_item($id);

if (isset($_POST['AddItem']))
	handle_new_item();

if (isset($_POST['UpdateItem']))
	handle_update_item();


function copy_to_cart($sc_header, $stock_count_id)
{
        $cart = &$_SESSION['stock_counts'];
        //$cart->location = $sc_header["location_name"];
        $cart->status_id = $sc_header["status_id"];
        $cart->created_on = $sc_header["created_on"];
        $cart->updated_on = $sc_header["updated_on"];
        $cart->tran_date = $sc_header["tran_date"];
        $cart->system_qty = $sc_header["system_qty"];
        $cart->trans_type = ST_STOCK_COUNT;
        $cart->trans_no = $stock_count_id;	
}

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

function copy_from_cart()
{
//
//
      $cart = &$_SESSION['stock_counts'];
        //$_POST['comment'] = $cart->comment;
        //$_POST['AdjDate'] = $cart->AdjDate ;
	//$_POST['plant_code'] = $cart->plant_code;
        //$_POST['job_code'] = $cart->job_code;
        //$price = $cart->price;
        //$_POST['qty'] = $cart->quantity;
        //$_POST['description'] = $cart->description;
       // $_POST['sales_type'] = $cart->sales_type;
//	$cart = &$_SESSION['Items'];
//	$_POST['ref'] = $cart->reference;
//	$_POST['Comments'] = $cart->Comments;
//         $_POST['comment'] = $cart->comment ;
//
//	
}

function read_job_id($trans_type){
    $trans_type = $_GET['ModifyOrderNumber'];
    return $trans_type;
}



if (isset($_POST['CancelItemChanges'])) {
	line_start_focus();
}

//-----------------------------------------------------------------------------------------------
start_form();

display_order_header($_SESSION['stock_counts']);

start_outer_table(TABLESTYLE, "width=70%", 10);

display_order_summary(_("Stock Items"), $_SESSION['stock_counts'], true);

display_stock_count_comments($_SESSION['stock_counts']->comment ? $_SESSION['stock_counts']->comment : "");

end_outer_table(1, false);

if(!isset($_SESSION['stock_counts']->status_id)){
submit_center_first('Process', _("Add Stock Count List"), '', 'default');
}
else{
    submit_center_first('Process', _("Update Stock Count List"), '', 'default');
}
end_form();
end_page();

?>


