<?php
/**********************************************************************
    Copyright (C) FrontAccounting, LLC.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/
$page_security = 'SA_TRANSDER_INQUIRY';
$path_to_root="../..";

include($path_to_root . "/includes/db_pager.inc");
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");
$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['outstanding_only']) && $_GET['outstanding_only'])
{
	$outstanding_only = 1;
	page(_($help_context = "Search Outstanding   Inventry Transfer"), false, false, "", $js);
}
else
{
	$outstanding_only = 0;
	page(_($help_context = "Search  Inventry Transfer "), false, false, "", $js);
}
//-----------------------------------------------------------------------------------
// Ajax updates
//
if (get_post('SearchOrders'))
{
	$Ajax->activate('dim_table');
} elseif (get_post('_OrderNumber_changed'))
{
	$disable = get_post('OrderNumber') !== '';

	$Ajax->addDisable(true, 'FromDate', $disable);
	$Ajax->addDisable(true, 'ToDate', $disable);
	$Ajax->addDisable(true, 'StkLocation', $disable);
	$Ajax->addDisable(true, 'receive_loc', $disable);
	$Ajax->addDisable(true, 'type_', $disable);
	$Ajax->addDisable(true, 'OverdueOnly', $disable);
	$Ajax->addDisable(true, 'OpenOnly', $disable);

	if ($disable) {
		set_focus('OrderNumber');
	} else
		set_focus('type_');

	$Ajax->activate('dim_table');
}

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

if (isset($_GET["stock_id"]))
	$_POST['SelectedStockItem'] = $_GET["stock_id"];

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

start_form(false, false, $_SERVER['PHP_SELF'] ."?outstanding_only=$outstanding_only");

start_table(TABLESTYLE_NOBORDER);
start_row();

ref_cells(_("Reference:"), 'OrderNumber', '',null, '', false);

locations_list_cells(_("From Loc:"), 'StkLocation', null, true, true, $order->fixed_asset,2);

locations_list_cells(_("To Loc:"), 'receive_loc', null, true, true, $order->fixed_asset,1);
end_row();

// $array_list=array();
// $array_list[1]=$SysPrefs->prefs['dim1_name'];
// $array_list[2]=$SysPrefs->prefs['dim2_name'];
// number_list_array_cells(_("Type"), 'type_', null, 1, 2, _("All"),$array_list,true);

start_row();
stock_items_list_cells(_("Item:"), 'SelectStockFromList', null, true, true);
date_cells(_("From:"), 'FromDate', '', null, -user_transaction_days());
date_cells(_("To:"), 'ToDate');
// check_cells( _("Only Overdue:"), 'OverdueOnly', null);

// if (!$outstanding_only)
// {
//    	check_cells( _("Only Open:"), 'OpenOnly', null);
// }
// else
// 	$_POST['OpenOnly'] = 1;

submit_cells('SearchOrders', _("Search"), '', '', 'default');

end_row();
end_table();

$dim = get_company_pref('use_dimension');

function view_link($row) 
{
	return get_trans_view_str(ST_LOCTRANSFER, $row["trans_no"]); // get_dimensions_trans_view_str(ST_DIMENSION, $row["id"]);
}

function sum_dimension($row) 
{
	return get_dimension_balance($row['id'], $_POST['FromDate'], $_POST['ToDate']); 
}

function is_closed($row)
{
	return $row['closed'] ? _('Yes') : _('No');
}

function is_overdue($row)
{
	return date_diff2(Today(), sql2date($row["due_date"]), "d") > 0;
}



function status($row)
{
	if(exists_approval_trans(ST_LOCTRANSFER, $row["trans_no"]))
	{
			$app_res = get_approved_trans(ST_LOCTRANSFER,$row['trans_no']);
			 $ap_row = db_fetch($app_res);
			 return '<span class="label label-primary"> Received </span> <span class="label" > '.get_user($ap_row["user_id"])['real_name'].' </span>';

	}
	else{

      	 return '<span class="label label-danger"> Not Received <span> ';
	}
}


function tmpl_checkbox($row)
{
	global $trans_type, $page_nested;

  if( exists_approval_trans(ST_LOCTRANSFER, $row["trans_no"])){
  	$app_res = get_approved_trans(ST_LOCTRANSFER,$row['trans_no']);
     $ap_row = db_fetch($app_res);
    return  sql2date($ap_row['date']);
   	// return '-';
  }
	
	$name = "chgtpl" .$row['trans_no'];
	$value = exists_approval_trans(ST_LOCTRANSFER, $row["trans_no"]) ? 1:0;

// function delete($row)
// {
// 	$delete = "delete" .$row['trans_no'];
// 	return checkbox($delete);
// }

// save also in hidden field for testing during 'Update'

 return checkbox(null, $name, $value, true,
 	_('Set this order as a template for direct deliveries/invoices'))
	. hidden('last['.$row['order_no'].']', $value, false);
}
function from_loc($row){

	return  get_item_location($row['from_loc'])['location_name'];
}
function to_loc($row){

	return  get_item_location($row['to_loc'])['location_name'];
}
function remarks_box($row){

  if( exists_approval_trans(ST_LOCTRANSFER, $row["trans_no"])){
  	$app_res = get_approved_trans(ST_LOCTRANSFER,$row['trans_no']);
     $ap_row = db_fetch($app_res);
   	return   $ap_row['remarks'] ;
  }
	
	return textarea_cells(null, 'remarks'.$row['trans_no'], $_POST['postal_address'], 25, 2);
}


// function delete_link($row){
// 	// display_error($row['trans_no']);
// if($_SESSION["wa_current_user"]->can_access('DELETE_TRANSFER_INQUERY')==1){

// 	$void_entry = get_voided_entry(ST_LOCTRANSFER, $row['trans_no']);
// 	print_r($void_entry);
// 	// display_error($void_entry);
// 	if (!$void_entry) {
// 	return delete_button_cell("Delete".$row['trans_no'], _("Delete"),	_('Remove line from document'));
// 	}
// }


// }

// $delete_id = find_submit('Delete');
// if ($delete_id != -1) {

// 		delete_transfer_inquery(ST_LOCTRANSFER, $delete_id);
// 		display_notification(_('Inventory transfer successfully deleted'), 1);
// }

$id = find_submit('_chgtpl');

if ($id != -1)
{  global $Ajax;
	  if($_POST['remarks'.$id]==''){
	  	display_error("remarks must be Ennter");
	  	 unset($_POST["chgtp".$id]);
	  	$Ajax->activate('dim_tbl');
	  	set_focus('remarks'.$id);
	  	// return;
	  }else{
			    
                 if(!exists_approval_trans(ST_LOCTRANSFER, $id))
                {
				      $trans = get_stock_transfer($id);

				      $transfer_items = get_stock_moves(ST_LOCTRANSFER, $id);
				       $data_trans = get_tranfer_data(ST_LOCTRANSFER, $id);
				     while ($item = db_fetch($transfer_items))
				    {
				    add_stock_move(ST_LOCTRANSFER, $item['stock_id'], $id, $data_trans['to_loc'],  	sql2date($trans['tran_date']),  $trans['reference'],abs($item['qty']), 0, 0, $item['batch_no'], $item['exp_date']);
				    }  
					$sql = "INSERT INTO ".TB_PREF."approval_trans (type,trans_no,date,user_id,remarks) VALUES (".db_escape(ST_LOCTRANSFER) . ",".db_escape($id).",".db_escape(date('Y-m-d')).",".db_escape($_SESSION["wa_current_user"]->user).",".db_escape($_POST['remarks'.$id]).")";
					db_query($sql,"The sales group could not be added");

                } 
                else	
                display_error("already Received");	
			   $Ajax->activate('dim_tbl');
	  }
	
}

// print_r($_SESSION['wa_current_user']->location);

$sql = get_sql_for_transfer_inquiry($dim, $_POST['FromDate'], $_POST['ToDate'],fasle, $_POST['StkLocation'], $_POST['receive_loc'], $_POST['OrderNumber'],$_POST['SelectStockFromList']);

$cols = array(
	_("#") => array('fun'=>'view_link'), 
	_("Reference") => array('name'=>'reference') ,
	_("Date")=> array('name'=>'tran_date','type'=>'date') ,
	_("From Loc") => array('fun'=>'from_loc'), 
	_("To Loc") => array('fun'=>'to_loc'),
	// _("Due Date") => array('name'=>'due_date', 'type'=>'date', 'ord'=>'asc'),

	_("Remarks") => array('insert'=>false, 'fun'=>'remarks_box'), 
	_("Received") => array('insert'=>false, 'fun'=>'tmpl_checkbox' ,'align'=>'left' ),
	_("Status") => array('fun'=>'status'),
	// _("Delete") => array('fun'=>'delete_link'),
	_(""), 
	// _("Balance") => array('type'=>'amount', 'insert'=>true, 'fun'=>'sum_dimension'),
	// array('insert'=>true, 'fun'=>'edit_link'),
	// array('insert'=>true, 'fun'=>'prt_link')
);

if ($outstanding_only) {
	$cols[_("Closed")] = 'skip';
}

$table =& new_db_pager('dim_tbl', $sql, $cols);
$table->set_marker('is_overdue', _("Marked dimensions are overdue."));

$table->width = "80%";

display_db_pager($table);

end_form();
end_page();

