<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_COMPLETE_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/complete_stock_count_ui.inc");
include_once($path_to_root . "/inventory/includes/stock_count_ui.inc");
include_once($path_to_root . "/inventory/includes/db/complete_stock_count_db.inc");
include_once($path_to_root . "/inventory/includes/db/stock_count_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/includes/errors.inc");
include_once($path_to_root . "/includes/types.inc");
include_once($path_to_root . "/inventory/includes/process_stock_count.inc");
include_once($path_to_root . "/jobq/includes/jobq_requests.inc");


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



if (isset($_GET['StockCountNo']) && is_numeric($_GET['StockCountNo'])) {
    $_POST['stock_count_id'] = $_GET['StockCountNo'];
}

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

page("Complete Stock Count", false, false, "", $js);


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

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

//	display_note(get_gl_view_str($trans_type, $trans_no, _("View the GL &Postings for this Stock count")), 0, 1);

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

	hyperlink_no_params("$path_to_root/inventory/stock_count.php?NewStockCount=Yes", _("Enter &Another Stock Count"));
        
	display_footer_exit();
}

function check_data($stock_count_id)
{
    $sch = get_stock_count_header_record($stock_count_id);
    if(!($sch['status_id'] == SC_COMPLETED || $sch['status_id'] == SC_PROCESSING)){
		display_error(_("Status of this stock count does not allow further processing."));
		set_focus('');
		return false;
	}
        
        
     if(!is_date($sch['tran_date'])) 
    {
        display_error( _("Date entered for the stock count is invalid.")); 
        return false;
    }
        
    if (!is_date_in_fiscalyear($sch['tran_date'])) 
    {
        display_error(_("The entered date is not in fiscal year.")); 
        return false;
    } 
    
    $msg = is_accounting_period_open($sch['tran_date']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']); 
        return false;
    }
    
    return true;
}

function display_stock_count_counted_details($stock_count_id)
{
    $sheet_no = $_POST['sheet_no'];
    
    start_table(TABLESTYLE, "width=98%");

    $th = array(_("Stock_ID"),_("Description"), "Unit", 
                    _("Good Qty"), _("Damaged Qty"), "Counted Qty",
                    "System Qty", "Unit Cost", "Adj. Qty", "Adj Value");
    
    $th = array(_("Stock_ID"),_("Description"), 
        
                nl2br("Tran \r\n Unit"), 
                nl2br("Tran \r\n Unit \r\n Good \r\n Qty"), 
                nl2br("Tran \r\n Unit \r\n Damaged \r\n Qty"),
        
                nl2br("Base \r\n Unit"), 
                nl2br("Conv. \r\n Factor"), 
        
                nl2br("Base \r\n Unit \r\n Good \r\n Qty"), 
                nl2br("Base \r\n Unit \r\n Damaged \r\n Qty"), 
                nl2br("Base \r\n Unit \r\n System \r\n Qty"),
        
                nl2br("Base \r\n Unit \r\n Cost"),
                nl2br("Base \r\n Unit \r\n Adj \r\n Qty"),
                nl2br("Base \r\n Unit \r\n Adj \r\n Value"),
                nl2br("Tran \r\n Unit \r\n Adj \r\n Qty")
        );
    
    table_header($th);

    $j = 1;
    $k=0; //row colour counter
    $adj_value_total = 0;
    
    $result = get_stock_count_details($stock_count_id, $sheet_no);


    while ($myrow = db_fetch($result))
    {

        $dec = '2';
        alt_table_row_color($k);

        label_cell($myrow["stock_id"]);
        label_cell($myrow["description"]);
        
        $convertion_factor = $myrow['conversion_factor'];
        label_cell($myrow["tran_unit_name"]);
        label_cell(number_format($myrow["tran_unit_good_qty"], $dec), "align=right");
        label_cell(number_format($myrow["tran_unit_damaged_qty"], $dec), "align=right");
        
        label_cell($myrow["base_unit_name"]);
        label_cell($convertion_factor, "align=right");
        label_cell(number_format($myrow["good_qty"], $dec), "align=right");
        label_cell(number_format($myrow["damaged_qty"], $dec), "align=right");
        label_cell(number_format($myrow["system_qty"], $dec), "align=right");
        
        label_cell(number_format($myrow["standard_cost"], 2), "align=right");
        $base_unit_adj_qty = $myrow["good_qty"] + $myrow["damaged_qty"] - $myrow["system_qty"];
        label_cell(number_format($base_unit_adj_qty, $dec), "align=right");
        $base_unit_adj_value = $base_unit_adj_qty * $myrow["standard_cost"];
        label_cell(number_format($base_unit_adj_value, 2), "align=right");
        
        label_cell(number_format($base_unit_adj_qty/$convertion_factor, $dec), "align=right");
        
        
        
        
        
        
        $adj_value_total += $base_unit_adj_value;
        
        end_row();
        $j++;
        If ($j == 25)
        {
            $j = 1;
            table_header($th);
        }

    }

    start_row();
    label_cell("Total", "colspan=12 align=right");
    label_cell(number_format($adj_value_total, 2), "align=right");
    end_row();
    
    end_table(1);

}


function process_stock_count($stock_count_no)
{
//    process_stock_count_job($stock_count_no);    
//    return;
    
//    $parameters[] = array('stock_count_no' => $stock_count_no, 'stock_count_processing_type' => 'PROCESS');
//    $parameters_json = json_encode($parameters);
//
//    $submitted_by = $_SESSION['wa_current_user']->user;
//
//    $msg_cjr = create_jobq_request(ST_STOCK_COUNT, $submitted_by, $parameters_json);
//    if($msg_cjr['success'] == true){
//            update_stock_count_joq_request_id($stock_count_no, (int)$msg_cjr['message']);
//            $trans_no = $stock_count_no;
//            unset($_SESSION['stock_counts']);
//            meta_forward($_SERVER['PHP_SELF'], "ProcessedID=$trans_no");
//    }
//    else{
//        display_error($msg_cjr['message']);
//    }
    
    
    $msg_psc = process_stock_count_job($stock_count_no);
    if($msg_psc['success'] === true){
            $trans_no = $stock_count_no;
            unset($_SESSION['stock_counts']);
            meta_forward($_SERVER['PHP_SELF'], "ProcessedID=$trans_no");
    }
    else{
        display_error($msg_psc['message']);
    }
    
 
}

if (isset($_POST['ProcessStockCount']) && check_data($stock_count_id)){
    process_stock_count($stock_count_id);
}

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

display_stock_count_header($stock_count_id);


$Ajax->activate('sc_details');
div_start('sc_details');

start_table(TABLESTYLE_NOBORDER); 
stock_count_sheets_list_row("Sheet No :", 'sheet_no', $stock_count_id, null, false, true);
end_table(1);
    
display_stock_count_counted_details($stock_count_id);
div_end();

submit_center_last('ProcessStockCount', _("Process Stock Count"), '', 'default');
    

end_form();
end_page();

?>



