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

include_once($path_to_root . "/purchasing/includes/purchasing_db.inc");

include_once($path_to_root . "/includes/session.inc");

include_once($path_to_root . "/includes/banking.inc");
include_once($path_to_root . "/includes/data_checks.inc");

include_once($path_to_root . "/purchasing/includes/ui/purchasing_ui.inc");

include_once($path_to_root . "/transport/includes/db/supplier_transport_invoices_db.inc");

        
$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 = "Enter Supplier Invoice"), false, false, "", $js);

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

check_db_has_suppliers(_("There are no suppliers defined in the system."));

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

if (isset($_GET['AddedID'])) 
{
	$invoice_no = $_GET['AddedID'];
	$trans_type = ST_SUPPINVOICE;


    echo "<center>";
    display_notification_centered(_("Supplier invoice has been processed."));
    display_note(get_trans_view_str($trans_type, $invoice_no, _("View this Invoice")));

	display_note(get_gl_view_str($trans_type, $invoice_no, _("View the GL Journal Entries for this Invoice")), 1);

	hyperlink_params("$path_to_root/purchasing/supplier_payment.php", _("Enter supplier &payment for this invoice"),
		"PInvoice=".$invoice_no);

	hyperlink_params($_SERVER['PHP_SELF'], _("Enter Another Invoice"), "New=1");

	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$invoice_no");
	
	display_footer_exit();
}

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

if (isset($_GET['New']))
{
	if (isset( $_SESSION['supp_trans']))
	{
		unset ($_SESSION['supp_trans']->grn_items);
		unset ($_SESSION['supp_trans']->gl_codes);
        unset ($_SESSION['supp_trans']->transport_invoices);
		unset ($_SESSION['supp_trans']);
	}

	$_SESSION['supp_trans'] = new supp_trans(ST_SUPPINVOICE);
}

//--------------------------------------------------------------------------------------------------
function clear_fields()
{
	global $Ajax;
	
	unset($_POST['gl_code']);
	unset($_POST['dimension_id']);
	unset($_POST['dimension2_id']);
	unset($_POST['amount']);
	unset($_POST['memo_']);
	unset($_POST['AddGLCodeToTrans']);
	$Ajax->activate('gl_items');
	set_focus('gl_code');
}

function reset_tax_input()
{
	global $Ajax;

	unset($_POST['mantax']);
	$Ajax->activate('inv_tot');
}

//------------------------------------------------------------------------------------------------
//	GL postings are often entered in the same form to two accounts
//  so fileds are cleared only on user demand.
//
if (isset($_POST['ClearFields']))
{
	clear_fields();
}

if (isset($_POST['AddGLCodeToTrans'])){

	$Ajax->activate('gl_items');
	$input_error = false;

	$result = get_gl_account_info($_POST['gl_code']);
	if (db_num_rows($result) == 0)
	{
		display_error(_("The account code entered is not a valid code, this line cannot be added to the transaction."));
		set_focus('gl_code');
		$input_error = true;
	}
	else
	{
		$myrow = db_fetch_row($result);
		$gl_act_name = $myrow[1];
		if (!check_num('amount'))
		{
			display_error(_("The amount entered is not numeric. This line cannot be added to the transaction."));
			set_focus('amount');
			$input_error = true;
		}
	}

	if (!is_tax_gl_unique(get_post('gl_code'))) {
   		display_error(_("Cannot post to GL account used by more than one tax type."));
		set_focus('gl_code');
   		$input_error = true;
	}

	if ($input_error == false)
	{
		$_SESSION['supp_trans']->add_gl_codes_to_trans($_POST['gl_code'], $gl_act_name,
			$_POST['dimension_id'], $_POST['dimension2_id'], 
			input_num('amount'), $_POST['memo_']);
		reset_tax_input();
		set_focus('gl_code');
	}
}

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

function check_data()
{
	global $Refs;
    
//    if (!($_POST['inv_source_type'] > 0))
//	{
//		display_error(_("Please select a Source Type."));
//        set_focus('inv_source_type');
//		return false;
//	}

	if (!$_SESSION['supp_trans']->is_valid_trans_to_post())
	{
		display_error(_("The invoice cannot be processed because the there are no items or values on the invoice.  Invoices are expected to have a charge."));
		return false;
	}

	if (!$Refs->is_valid($_SESSION['supp_trans']->reference)) 
	{
		display_error(_("You must enter an invoice reference."));
		set_focus('reference');
		return false;
	}

//	if (!is_new_reference($_SESSION['supp_trans']->reference, ST_SUPPINVOICE)) 
        $ref_msg = reference_exists($_SESSION['supp_trans']->reference, ST_SUPPINVOICE);
        if($ref_msg != "")
	{
		display_error(_($ref_msg));
		set_focus('reference');
		return false;
	}

	if (!$Refs->is_valid($_SESSION['supp_trans']->supp_reference)) 
	{
		display_error(_("You must enter a supplier's invoice reference."));
		set_focus('supp_reference');
		return false;
	}

	if (!is_date( $_SESSION['supp_trans']->tran_date))
	{
		display_error(_("The invoice as entered cannot be processed because the invoice date is in an incorrect format."));
		set_focus('trans_date');
		return false;
	} 
	
        if (!is_date_in_fiscalyear($_SESSION['supp_trans']->tran_date)) 
	{
		display_error(_("The entered date is not in fiscal year."));
		set_focus('trans_date');
		return false;
	}
        
        $msg = is_accounting_period_open($_POST['InvoiceDate']);
        if ($msg['success'] !== true)
        {
                display_error($msg['message']);
                set_focus('InvoiceDate');
                return false;
        }
    
	if (!is_date( $_SESSION['supp_trans']->due_date))
	{
		display_error(_("The invoice as entered cannot be processed because the due date is in an incorrect format."));
		set_focus('due_date');
		return false;
	}

	if (is_reference_already_there($_SESSION['supp_trans']->supplier_id, $_POST['supp_reference']))
	{ 	/*Transaction reference already entered */
		display_error(_("This invoice number has already been entered. It cannot be entered again.") . " (" . $_POST['supp_reference'] . ")");
		return false;
	}

	return true;
}

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

function handle_commit_invoice()
{
	copy_to_trans($_SESSION['supp_trans']);

	if (!check_data()){
		return;
    }

	$invoice_no = add_supp_invoice($_SESSION['supp_trans']);

    if(!($invoice_no > 0)){
        display_error("Could not save supplier Invoice.");
    }
    else{
        $_SESSION['supp_trans']->clear_items();
        unset($_SESSION['supp_trans']);
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$invoice_no");
    }


}

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

if (isset($_POST['PostInvoice']))
{
	handle_commit_invoice();
}

function check_transport_invoice_data($n)
{
    
    $sti = get_supplier_transport_invoice_record($n);
	if ($sti['payment_source_no'] > 0)
	{
		display_error( _("Supplier Invoice $n has been invoiced or paid already."));
		return false;
	}

	return true;
}


function check_item_data($n, $grn_item)
{
	global $check_price_charged_vs_order_price,
		$check_qty_charged_vs_del_qty, $SysPrefs;
	if (!check_num('this_quantity_inv_po_unit'.$n, 0) || input_num('this_quantity_inv_po_unit'.$n)==0)
	{
		display_error( _("The quantity to invoice must be numeric and greater than zero."));
		set_focus('this_quantity_inv'.$n);
		return false;
	}

	if (!check_num('ChgPrice_po_unit'.$n, 0))
	{
		display_error( _("The price is not numeric."));
		set_focus('ChgPrice'.$n);
		return false;
	}
    
    if (!check_num('ChgPrice_po_discount'.$n, 0, 100))
	{
		display_error( _("Discount has to be between zero and 100."));
		set_focus('ChgPrice'.$n);
		return false;
	}
    
	$margin = $SysPrefs->over_charge_allowance();
	if ($check_price_charged_vs_order_price == True)
	{
        $discounted_po_unit_order_price = $grn_item['po_order_unit_price'] * (1 - $grn_item['po_order_unit_price_discount']/100);
        $discounted_po_unit_charge_price = input_num('ChgPrice_po_unit'.$n) * (1 - input_num('ChgPrice_po_discount'.$n)/100);
		if ($discounted_po_unit_order_price != $discounted_po_unit_charge_price) {
		     if ($discounted_po_unit_order_price==0 ||
				$discounted_po_unit_charge_price/$discounted_po_unit_order_price > (1 + ($margin/ 100)))
		    {
			display_error(_("The price being invoiced is more than the purchase order price by more than the allowed over-charge percentage of ".$margin . "%"));
			set_focus('ChgPrice_po_unit'.$n);
			return false;
		    }
		}
	}

	if ($check_qty_charged_vs_del_qty == true && ($grn_item['qty_recd'] != $grn_item['quantity_inv']))
	{
		if (input_num('this_quantity_inv_po_unit'.$n) / (($grn_item['qty_recd'] - $grn_item['quantity_inv']) / $grn_item['po_order_unit_conv_factor']) >
			(1+ ($margin / 100)))
		{
            display_error(_("The quantity being invoiced is more than the outstanding quantity by more than the allowed over-charge percentage of ".$margin . "%"));
			
			set_focus('this_quantity_inv_po_unit'.$n);
			return false;
		}
	}

	return true;
}

function commit_item_data($n)
{
    $grn_item = get_grn_item_detail($n);
    
	if (check_item_data($n, $grn_item))
	{
        
        $this_quantity_inv_base_unit = input_num('this_quantity_inv_po_unit'.$n) * $grn_item["po_order_unit_conv_factor"];
        $ChgPrice_base_unit = (input_num('ChgPrice_po_unit'.$n) * (1 - input_num('ChgPrice_po_discount'.$n)/100))/ $grn_item["po_order_unit_conv_factor"];
        
		$_SESSION['supp_trans']->add_grn_to_trans($n, $grn_item['po_detail_item'],
			$grn_item['item_code'], $grn_item['description'], $grn_item['qty_recd'],
			$grn_item['quantity_inv'], $this_quantity_inv_base_unit,
			$grn_item['unit_price'], $ChgPrice_base_unit,
			$grn_item['std_cost_unit'], "");
		reset_tax_input();
        
        $inv_item = &$_SESSION['supp_trans']->grn_items[$n];
        
        $inv_item->po_unit = $grn_item['po_order_unit'];
        $inv_item->po_unit_name = $grn_item['po_order_unit'];
        $inv_item->po_unit_conv_factor = $grn_item['po_order_unit_conv_factor'];
        $inv_item->this_quantity_inv_po_unit = input_num('this_quantity_inv_po_unit'.$n);
        
        $qty_recd_po_unit = $grn_item['qty_recd'] / $grn_item["po_order_unit_conv_factor"];
        $inv_item->qty_recd_po_unit = $qty_recd_po_unit;
        $inv_item->prev_quantity_inv_po_unit = $grn_item['quantity_inv'] * $grn_item["convertion_factor"];
        $inv_item->chg_price_po_unit = input_num('ChgPrice_po_unit'.$n);
        $inv_item->chg_price_discount = input_num('ChgPrice_po_discount'.$n);
	}
}


function commit_transport_invoice_data($n)
{
	if (check_transport_invoice_data($n))
	{
		$_SESSION['supp_trans']->add_transport_invoices_to_trans($n, $_POST['supp_inv_ref'.$n],
			$_POST['tran_date'.$n], input_num('invoice_total'.$n));
		reset_tax_input();
        
//        $transport_invoice_id, $supp_inv_ref, $invoice_date, $invoice_total
	}
}

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

$id = find_submit('grn_item_id');
if ($id != -1)
{
	commit_item_data($id);
}


$id = find_submit('transport_invoice_id');
if ($id > 0)
{
	commit_transport_invoice_data($id);
}

if (isset($_POST['InvGRNAll']))
{
   	foreach($_POST as $postkey=>$postval )
    {
		if (strpos($postkey, "qty_recd") === 0)
		{
			$id = substr($postkey, strlen("qty_recd"));
			$id = (int)$id;
			commit_item_data($id);
		}
    }
}	

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

global $Ajax;

$id3 = find_submit('Delete');
if ($id3 != -1)
{
	$_SESSION['supp_trans']->remove_grn_from_trans($id3);
	$Ajax->activate('grn_items');
	reset_tax_input();
}

$id4 = find_submit('Delete2');
if ($id4 != -1)
{
	$_SESSION['supp_trans']->remove_gl_codes_from_trans($id4);
	clear_fields();
	reset_tax_input();
	$Ajax->activate('gl_items');
}

$id5 = find_submit('Delete'.ST_SUPPLIER_TRANSPORT_INVOICES);
if ($id5 != -1)
{
	$_SESSION['supp_trans']->remove_transport_invoice_from_trans($id5);
	clear_fields();
	reset_tax_input();
	$Ajax->activate('transport_items');
}

$void_transport_invoice_id = -1;
if ($_SESSION["wa_current_user"]->can_access('SA_GRNDELETE'))
{
	$void_transport_invoice_id = find_submit('void_transport_invoice_id');
	if ($void_transport_invoice_id != -1) 
	{
		remove_not_invoice_item($void_transport_invoice_id);
		display_notification(sprintf(_('All yet non-invoiced items on delivery line # %d has been removed.'), $id2));

	}
}

$id2 = -1;
if ($_SESSION["wa_current_user"]->can_access('SA_GRNDELETE'))
{
	$id2 = find_submit('void_item_id');
	if ($id2 != -1) 
	{
//		remove_not_invoice_item($id2);
//		display_notification(sprintf(_('All yet non-invoiced items on delivery line # %d has been removed.'), $id2));

	}
}

if (isset($_POST['go']))
{
	$Ajax->activate('gl_items');
	display_quick_entries($_SESSION['supp_trans'], $_POST['qid'], input_num('totamount'), QE_SUPPINV);
	$_POST['totamount'] = price_format(0); $Ajax->activate('totamount');
	reset_tax_input();
}

start_form();

if(list_updated('supplier_id')){
    $_SESSION['supp_trans']->clear_items();
    $_POST['inv_source_type'] = -1;
    
}

$Ajax->activate('invoice_header');
div_start('invoice_header');
invoice_header($_SESSION['supp_trans']);
div_end();

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



if(!($_SESSION['supp_trans']->supplier_id > 0)){
		display_error(_("There is no supplier selected."));
}
else {
//    switch ($_POST['inv_source_type']){
//        case ST_SUPPRECEIVE:
////            $Ajax->activate('grn_items');            
//            unset($_SESSION['supp_trans']->gl_codes);
//            unset($_SESSION['supp_trans']->transport_invoices);
//            $_SESSION['supp_trans']->gl_codes = array();
//            $_SESSION['supp_trans']->transport_invoices = array();
//            display_grn_items($_SESSION['supp_trans'], 1);
//            break;
//        case SIST_MISCELLANEOUS:
////            $Ajax->activate('gl_items');        
//            unset($_SESSION['supp_trans']->grn_items);
//            unset($_SESSION['supp_trans']->transport_invoices);
//            $_SESSION['supp_trans']->grn_items = array();
//            $_SESSION['supp_trans']->transport_invoices = array();
//            display_gl_items($_SESSION['supp_trans'], 1);
//            break;
//        case ST_SUPPLIER_TRANSPORT_INVOICES:
////            $Ajax->activate('gl_items');
//            unset($_SESSION['supp_trans']->grn_items);
//            unset($_SESSION['supp_trans']->gl_codes);
//            $_SESSION['supp_trans']->grn_items = array();
//            $_SESSION['supp_trans']->gl_codes = array();
//            display_trasport_invoices($_SESSION['supp_trans'], 1);
//            break;
//
//        default:
//            break;
//    }
    
    $Ajax->activate('grn_items');  
    $Ajax->activate('gl_items');
//    $_SESSION['supp_trans']->grn_items = array();
//    $_SESSION['supp_trans']->gl_codes = array();
    display_grn_items($_SESSION['supp_trans'], SIDM_DISPLAY_ON_INVOICE_CREDIT_NOTE);
    display_gl_items($_SESSION['supp_trans'], SIDM_DISPLAY_ON_INVOICE_CREDIT_NOTE);
	
div_end();

//	display_gl_items($_SESSION['supp_trans'], 1);

	div_start('inv_tot');
	invoice_totals($_SESSION['supp_trans']);
	div_end();

}

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

if ($id != -1 || $id2 != -1)
{
	$Ajax->activate('grn_items');
	$Ajax->activate('inv_tot');
}

if (get_post('AddGLCodeToTrans'))
	$Ajax->activate('inv_tot');

br();
submit_center('PostInvoice', _("Enter Invoice"), true, '', 'default');
br();

end_form();

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

end_page();
?>
