<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_ITEM_MOVEMENTS_INQ';
$path_to_root = "../..";
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/banking.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");
include_once($path_to_root . "/includes/ui.inc");

if(!@$_GET['popup']){
    $js = "";
    $js .= get_js_open_window(800, 500);
    $js .= get_js_date_picker();
    page(_($help_context = "Inventory Non Stock Item Movement"), @$_GET['popup'], false, "", $js);
}	
//------------------------------------------------------------------------------------------------

check_db_has_stock_items(_("There are no non stock items defined in the system."));

if(get_post('ShowMoves')){
    $Ajax->activate('doc_tbl');
}

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

global $Ajax;

if(!@$_GET['popup'])
    start_form();

if(!isset($_POST['stock_id']))
    $_POST['stock_id'] = get_global_stock_item();

$Ajax->activate('sm_filter');

div_start('sm_filter');
start_table(TABLESTYLE_NOBORDER);
    start_row();
        if(!@$_GET['popup'])
            non_stock_items_list_cells(_("Item:"), 'stock_id', $_POST['stock_id']);
        yesno_list_cells("Display Order:", 'display_order', null, "Transactions created order", "Transaction document date", true);
    end_row();
end_table();

start_table(TABLESTYLE_NOBORDER);
    start_row();
//        project_list_cells(_("Project:"), 'project_id', null, _('Select a project'), true); 
    
        $_POST['project_id'] = -1;
        hidden('project_id',$_POST['project_id']);

        if($_POST['display_order'] > 0){
            $_POST['AfterDate'] = sql2date(INFINITE_START_DATE);
            $_POST['BeforeDate'] = sql2date(INFINITE_END_DATE);
        }
        
    end_row();
end_table();

start_table(TABLESTYLE_NOBORDER);
    start_row();
        locations_list_cells(_("From Location:"), 'StockLocation', null, true, true);
        
        if($_POST['display_order'] > 0){
            hidden('AfterDate', $_POST['AfterDate']);
            hidden('BeforeDate', $_POST['BeforeDate']);
            label_cell("From:". spaces(2).$_POST['AfterDate'].spaces(5)."To:". spaces(2).$_POST['BeforeDate'].spaces(5));
        }else{
            date_cells(_("From:"), 'AfterDate', '', null, -30, 0, 0, null, true);
            date_cells(_("To:"), 'BeforeDate', '', null, 0, 0, 0, null, true);
        }
        
        submit_cells('ShowMoves',_("Show Movements"),'',_('Refresh Inquiry'), 'default');
    end_row();
end_table(1);

div_end();


if(!@$_GET['popup'])
    end_form();

set_global_stock_item($_POST['stock_id']);

$before_date = date2sql($_POST['BeforeDate']);
$after_date = date2sql($_POST['AfterDate']);
$display_location = !$_POST['StockLocation'];

$unit_name = '';
$item = get_item($_POST['stock_id']);
if (isset($item['units']) && strlen($item['units']) > 0) {
    $item_unit = get_item_unit($item['units']);
    if (isset($item_unit['name']) && strlen($item_unit['name']) > 0) {
        $unit_name = $item_unit['name'];
    }
}

$Ajax->activate('ItemBaseUnit');
div_start('ItemBaseUnit');
start_table(TABLESTYLE2);
echo '<h3>Cost unit (Base Unit) of this item is "'.text_bold($unit_name).'"</h3>';
end_table(1);
div_end();

$result = get_non_stock_movements($_POST['stock_id'], $_POST['StockLocation'], $_POST['BeforeDate'], $_POST['AfterDate'], $_POST['project_id'], $_POST['display_order']);
$Ajax->activate('doc_tbl');
div_start('doc_tbl');
    start_table(TABLESTYLE, "width=98%");
        $th = array(_("ID"), _("Type"), _("#"), _("Reference"));
        if($display_location) array_push($th, _("Location"));
        array_push($th, _("Date"), _("Detail"),_("Project"), _("Tran Unit"), _("Tran Qty"),  _("Conv."), 
                        _("Base Unit<br>Qty In"), _("Base Unit<br>Qty Out"), "Base Unit<br>Cost", _("Base Unit<br>Qty On Hand"));
        
        table_header($th);

        $before_qty = get_non_stock_movements_before($_POST['stock_id'], $_POST['StockLocation'], $_POST['AfterDate'], $_POST['display_order']);

        $after_qty = $before_qty;
        start_row("class='inquirybg'");
            $header_span = $display_location ? 8 : 7;
            label_cell("<b>"._("Quantity on hand before") . " " . $_POST['AfterDate']."</b>", "align=center colspan=$header_span");
            label_cell("&nbsp;", "colspan=6");
            $dec = get_qty_dec($_POST['stock_id']);
            qty_cell($before_qty, false, $dec);
        end_row();

        $j = 1;
        $k = 0; //row colour counter

        $total_in = 0;
        $total_out = 0;

        while($myrow = db_fetch($result)){
            alt_table_row_color($k);
                $trandate = sql2date($myrow["tran_date"]);
                $type_name = $systypes_array[$myrow["type"]];
                if($myrow["qty"] > 0){
                    $quantity_formatted = number_format2($myrow["qty"], $dec);
                    $total_in += $myrow["qty"];
                }else{
                    $quantity_formatted = number_format2(-$myrow["qty"], $dec);
                    $total_out += -$myrow["qty"];
                }
                $after_qty += $myrow["qty"];

                label_cell($myrow["trans_id"], "align=center");
                label_cell($type_name);
                label_cell(get_trans_view_str($myrow["type"], $myrow["trans_no"]));
                label_cell(get_trans_view_str($myrow["type"], $myrow["trans_no"], $myrow["reference"]));
                if($display_location) {
                    label_cell($myrow['loc_code']);
                }
                label_cell($trandate);
                
                $person = $myrow["person_id"];
                $gl_posting = "";

                if(($myrow["type"] == ST_CUSTDELIVERY) || ($myrow["type"] == ST_CUSTCREDIT)){
                    $cust_row = get_customer_details_from_trans($myrow["type"], $myrow["trans_no"]);

                    if(strlen($cust_row['name']) > 0)
                        $person = $cust_row['name'] . " (" . $cust_row['br_name'] . ")";
                }elseif($myrow["type"] == ST_SUPPRECEIVE || $myrow['type'] == ST_SUPPCREDIT){
                    // get the supplier name
                    $supp_name = get_supplier_name($myrow["person_id"]);

                    if(strlen($supp_name) > 0)
                        $person = $supp_name;
                }elseif($myrow["type"] == ST_LOCTRANSFER || $myrow["type"] == ST_INVADJUST){
                    // get the adjustment type
                    $movement_type = get_movement_type($myrow["person_id"]);
                    if (isset($movement_type["name"])) {
                        $person = $movement_type["name"];
                    }
                }elseif($myrow["type"]==ST_WORKORDER || $myrow["type"] == ST_MANUISSUE  || $myrow["type"] == ST_MANURECEIVE){
                    $person = "";
                }

                if(is_numeric($person)){
                    $new_person = $person * 1;
                    if(!($new_person > 0 || $new_person < 0)){
                        $person = "";
                    }
                }
                label_cell($person);
                label_cell($myrow["project_name"]);
                label_cell($myrow["tran_unit_name"], 'align=center');
                label_cell(number_format($myrow["tran_qty"],2), 'align=right');
                label_cell(number_format($myrow["convertion_factor"],4), 'align=right');
                label_cell((($myrow["qty"] >= 0) ? $quantity_formatted : ""), "nowrap align=right");
                label_cell((($myrow["qty"] < 0) ? $quantity_formatted : ""), "nowrap align=right");
                label_cell(price_format($myrow['standard_cost']), 'align=right');
                qty_cell($after_qty, false, $dec);
            end_row();

                $j++;
                If($j == 12){
                    $j = 1;
                    table_header($th);
                }
        //end of page full new headings if
        }
        //end of while loop

        start_row("class='inquirybg'");
            label_cell("<b>"._("Quantity on hand after") . " " . $_POST['BeforeDate']."</b>", "align=center colspan=$header_span");
            label_cell("&nbsp;", "colspan=3");
            qty_cell($total_in, false, $dec);
            qty_cell($total_out, false, $dec);
            label_cell("&nbsp;", "colspan=1");
            qty_cell($after_qty, false, $dec);
        end_row();

    end_table(1);
div_end();

if(!@$_GET['popup'])
    end_page(@$_GET['popup'], false, false);

?>