<?php
/**********************************************************************
***********************************************************************/
//---------------------------------------------------------------------------
//
//	Entry/Modify free hand Credit Note
//
$page_security = 'SA_SALESCREDIT';
$path_to_root = "..";
include_once($path_to_root . "/sales/includes/cart_class.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");
include_once($path_to_root . "/sales/includes/sales_ui.inc");
include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
include_once($path_to_root . "/sales/includes/ui/sales_credit_ui.inc");
include_once($path_to_root . "/sales/includes/ui/sales_order_ui.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/includes/banking_custom.inc");

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

if(isset($_GET['NewCredit'])) {
	$_SESSION['page_title'] = _($help_context = "Customer Credit Note");
	handle_new_credit(0);
} elseif (isset($_GET['ModifyCredit'])) {
	$_SESSION['page_title'] = sprintf(_("Modifying Customer Credit Note #%d"), $_GET['ModifyCredit']);
	handle_new_credit($_GET['ModifyCredit']);
	$help_context = "Modifying Customer Credit Note";
}

page($_SESSION['page_title'],false, false, "", $js);

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

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

check_db_has_customer_branches(_("There are no customers, or there are no customers with branches. Please define customers and customer branches."));

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

if (list_updated('branch_id')) {
	// when branch is selected via external editor also customer can change
	$br = get_branch(get_post('branch_id'));
	$_POST['customer_id'] = $br['debtor_no'];
	$Ajax->activate('customer_id');
}

if (isset($_GET['AddedID'])) {
	$credit_no = $_GET['AddedID'];
	$trans_type = ST_CUSTCREDIT;

	display_notification_centered(sprintf(_("Credit Note # %d has been processed"),$credit_no));

	display_note(get_customer_trans_view_str($trans_type, $credit_no, _("&View this credit note")), 0, 1);

	display_note(print_document_link($credit_no."-".$trans_type, _("&Print This Credit Invoice"), true, ST_CUSTCREDIT),0, 1);
	display_note(print_document_link($credit_no."-".$trans_type, _("&Email This Credit Invoice"), true, ST_CUSTCREDIT, false, "printlink", "", 1),0, 1);

	display_note(get_gl_view_str($trans_type, $credit_no, _("View the GL &Journal Entries for this Credit Note")));

	hyperlink_params($_SERVER['PHP_SELF'], _("Enter Another &Credit Note"), "NewCredit=yes");

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

	display_footer_exit();
} else
	check_edit_conflicts();

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

function line_start_focus() {
  global $Ajax;
  $Ajax->activate('items_table');
  set_focus('_stock_id_edit');
}

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

function copy_to_cn()
{
	$cart = &$_SESSION['Items'];
	$cart->Comments = $_POST['CreditText'];
	$cart->document_date = $_POST['OrderDate'];
	$cart->freight_cost = input_num('ChargeFreightCost');
	$cart->Location = (isset($_POST["Location"]) ? $_POST["Location"] : "");
	$cart->sales_type = $_POST['sales_type_id'];
	if ($cart->trans_no == 0)
		$cart->reference = $_POST['ref'];
	$cart->ship_via = $_POST['ShipperID'];
	$cart->dimension_id = $_POST['dimension_id'];
	$cart->dimension2_id = $_POST['dimension2_id'];
    
    $cart->order_category_id	= $_POST['order_category_id'];
}

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

function copy_from_cn()
{
	$cart = &$_SESSION['Items'];
	$_POST['CreditText'] = $cart->Comments;
	$_POST['OrderDate'] = $cart->document_date;
	$_POST['ChargeFreightCost'] = price_format($cart->freight_cost);
	$_POST['Location'] = $cart->Location;
	$_POST['sales_type_id'] = $cart->sales_type;
	if ($cart->trans_no == 0)
		$_POST['ref'] = $cart->reference;
	$_POST['ShipperID'] = $cart->ship_via;
	$_POST['dimension_id'] = $cart->dimension_id;
	$_POST['dimension2_id'] = $cart->dimension2_id;
	$_POST['cart_id'] = $cart->cart_id;
}

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

function handle_new_credit($trans_no)
{
	processing_start();
	$_SESSION['Items'] = new Cart(ST_CUSTCREDIT,$trans_no);
	copy_from_cn();
}

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

function can_process()
{
	global $Refs;

	$input_error = 0;

    if (!$_POST['project_id'] > 0) 
	{
		display_error(_("There is no project selected."));
		set_focus('project_id');
		return false;
	}
    
    if (!get_post('customer_id')) 
	{
		display_error(_("There is no customer selected."));
		set_focus('customer_id');
		return false;
	} 
	
	if (!get_post('branch_id')) 
	{
		display_error(_("This customer has no branch defined."));
		set_focus('branch_id');
		return false;
	} 
    
	if ($_SESSION['Items']->count_items() == 0){
		return false;
    }
    
    if($_SESSION['Items']->trans_no == 0) {
        if (!$Refs->is_valid($_POST['ref'])) {
                    display_error( _("You must enter a reference."));
                    set_focus('ref');
                    return false;
            }
    }
    
    if (!is_date($_POST['OrderDate'])) {
            display_error(_("The entered date for the credit note is invalid."));
            set_focus('OrderDate');
            return false;
    }
    
    if (!is_date_in_fiscalyear($_POST['OrderDate'])) {
            display_error(_("The entered date is not in fiscal year."));
            set_focus('OrderDate');
            return false;
    }
        
    $msg = is_accounting_period_open($_POST['OrderDate']);
    if ($msg['success'] !== true)
    {
        display_error($msg['OrderDate']);
        set_focus('DispatchDate');
        return false;
    }
    
	return true;
}

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

if (isset($_POST['ProcessCredit']) && can_process()) {
	copy_to_cn();
	if ($_POST['CreditType'] == "WriteOff" && (!isset($_POST['WriteOffGLCode']) ||
		$_POST['WriteOffGLCode'] == '')) {
		display_note(_("For credit notes created to write off the stock, a general ledger account is required to be selected."), 1, 0);
		display_note(_("Please select an account to write the cost of the stock off to, then click on Process again."), 1, 0);
		exit;
	}
	if (!isset($_POST['WriteOffGLCode'])) {
		$_POST['WriteOffGLCode'] = 0;
	}
	copy_to_cn();
	$cn_msg = $_SESSION['Items']->write($_POST['WriteOffGLCode']);
    if($cn_msg['success'] !== true){    
        //if ($credit_no == -1)
		//display_error(_("The entered reference is already in use."));
        
        display_error($cn_msg['message']);
		set_focus('ref');
	}
	else
	{
        $credit_no = $cn_msg['tran_no'];
		new_doc_date($_SESSION['Items']->document_date);
		processing_end();
		meta_forward($_SERVER['PHP_SELF'], "AddedID=$credit_no");
	}
} /*end of process credit note */

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

function check_item_data($alternate_unit)
{
    if (!$alternate_unit) {
		display_error("Unit conversion not defined for the select unit ".get_post('tran_unit'));
		set_focus('tran_unit');
		return false;
    }
    
	if (!check_num('tran_qty',0)) {
		display_error(_("The quantity must be greater than zero."));
		set_focus('qty');
		return false;
	}
	if (!check_num('tran_unit_price',0)) {
		display_error(_("The entered price is negative or invalid."));
		set_focus('price');
		return false;
	}
	if (!check_num('Disc', 0, 100)) {
		display_error(_("The entered discount percent is negative, greater than 100 or invalid."));
		set_focus('Disc');
		return false;
	}
	return true;
}

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

function handle_update_item()
{
    $id = $_POST['line_no'];
    
    //$item = get_stock_item_edit_info($_SESSION['Items']->line_items[$id]->stock_id);
    $alternate_unit = get_convertion_factor(get_post('tran_unit_'.$id), $_SESSION['Items']->line_items[$id]->stock_id);
    $convertion_factor = $alternate_unit['convertion_factor'];
    
    if ($_POST['UpdateItem'] != ''){
        if(!check_item_data($alternate_unit)){
            $_POST['Edit'.get_post('line_no')] = 1;
            return;
        }
		//$_SESSION['Items']->update_cart_item($_POST['line_no'], input_num('qty'), input_num('price'), input_num('Disc') / 100);
	
        $_SESSION['Items']->update_cart_item($id, input_num('tran_qty')* $convertion_factor, input_num('tran_unit_price') / $convertion_factor, input_num('Disc') / 100, 
                                            null, input_num('tran_qty'), get_post('tran_unit_'.$id), $convertion_factor, 
                                            input_num('tran_unit_price'));
	}   
    
    line_start_focus();
}

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

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

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

function handle_new_item()
{
    $alternate_unit = get_convertion_factor($_POST['tran_unit_-1'], $_POST['stock_id']);
    if($alternate_unit){
        $convertion_factor = $alternate_unit['convertion_factor'];
    }
    else{
        $kit = get_kit_props($_POST['stock_id']);
        if($kit){
            $convertion_factor = 1;
            $alternate_unit = true;
        }
    }

	if (!check_item_data($alternate_unit)){
		return;
    }

//	add_to_order($_SESSION['Items'], $_POST['stock_id'], input_num('qty'),
//		input_num('price'), input_num('Disc') / 100);
    
    add_to_order($_SESSION['Items'], get_post('stock_id'), input_num('tran_qty') * $convertion_factor,
            input_num('tran_unit_price') / $convertion_factor, input_num('Disc') / 100, null, 
            $_POST['tran_unit_-1'], input_num('tran_qty'), $convertion_factor,
            input_num('tran_unit_price'));
    
    $l = $_SESSION['Items']->count_items() - 1;
    $_SESSION['Items']->line_items[$l]->list_price = input_num('tran_unit_list_price') / $convertion_factor;
    
    
    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();

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

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

if (!processing_active()) {
	handle_new_credit(0);
}

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

start_form();
hidden('cart_id');

$customer_error = display_credit_header($_SESSION['Items']);

if ($customer_error == "") {
	start_table(TABLESTYLE, "width=80%", 10);
	echo "<tr><td>";
	display_credit_items(_("Credit Note Items"), $_SESSION['Items']);
	credit_options_controls($_SESSION['Items']);
	echo "</td></tr>";
	end_table();
} else {
	display_error($customer_error);
}

echo "<br><center><table><tr>";
submit_cells('Update', _("Update"));
submit_cells('ProcessCredit', _("Process Credit Note"), '', false, 'default');
echo "</tr></table></center>";

end_form(2);
end_page();

?>
