<?php
/**********************************************************************
***********************************************************************/
//---------------------------------------------------------------------------
//
//	Entry/Modify Credit Note for selected Sales Invoice
//

$page_security = 'SA_SALESCREDITINV';
$path_to_root = "..";

include_once($path_to_root . "/sales/includes/sales_credit_invoice_class.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/includes/inventory.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_order_db.inc");

include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/projects/includes/db/projects_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();
}

if (isset($_GET['ModifyCredit'])) {
	$_SESSION['page_title'] = sprintf(_("Modifying Credit Invoice # %d."), $_GET['ModifyCredit']);
	$help_context = "Modifying Credit Invoice";
	processing_start();
} elseif (isset($_GET['DeliveryNoteNo'])) {
	$_SESSION['page_title'] = _($help_context = "Credit all or part of a Delivery");
	processing_start();
}
page($help_context = "Credit Note", false, false, "", $js);

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

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

	display_notification_centered(_("Credit Note has been processed"));

	display_note(get_customer_trans_view_str($trans_type, $credit_no, _("&View This Credit Note")), 0, 0);

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

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

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

	display_footer_exit();

} elseif (isset($_GET['UpdatedID'])) {
	$credit_no = $_GET['UpdatedID'];
	$trans_type = ST_CUSTCREDIT;

	display_notification_centered(_("Credit Note has been updated"));

	display_note(get_customer_trans_view_str($trans_type, $credit_no, _("&View This Credit Note")), 0, 0);

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

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

	display_footer_exit();
} else
	check_edit_conflicts();


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

function can_process()
{
    global $Refs;

    if (!is_date($_POST['CreditDate'])) {
            display_error(_("The entered date is invalid."));;
            set_focus('CreditDate');
            return false;
    } 
    
    if (!is_date_in_fiscalyear($_POST['CreditDate']))	{
            display_error(_("The entered date is not in fiscal year."));
            set_focus('CreditDate');
            return false;
    }
    
    $msg = is_accounting_period_open($_POST['CreditDate']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']);
        set_focus('CreditDate');
        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 (!check_num('ChargeFreightCost', 0)) {
		display_error(_("The entered shipping cost is invalid or less than zero."));;
		set_focus('ChargeFreightCost');
		return false;
	}
        
        $cq_msg = check_quantities();
	if ($cq_msg != "") {
		display_error(_($cq_msg));
                return false;
	}
	return true;
}

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

if (isset($_GET['DeliveryNoteNo']) && $_GET['DeliveryNoteNo'] > 0) {

    $_SESSION['Items'] = new Sales_Credit_Invoice_Cart(ST_CUSTDELIVERY, $_GET['DeliveryNoteNo'], true);
	copy_from_cart();

} elseif ( isset($_GET['ModifyCredit']) && $_GET['ModifyCredit']>0) {

//	$_SESSION['Items'] = new Cart(ST_CUSTCREDIT, $_GET['ModifyCredit']);
//	copy_from_cart();

} elseif (!processing_active()) {
	/* This page can only be called with an invoice number for crediting*/
	die (_("This page can only be opened if an invoice has been selected for crediting."));
}
$cq_msg = check_quantities();
if ($cq_msg != "") {
	display_error(_($cq_msg));
}

function check_quantities()
{
	$error = "";
	foreach ($_SESSION['Items']->line_items as $line_no=>$itm) {
                $id = $itm->id;
		if ($itm->quantity == $itm->qty_done) {
			continue; // this line was fully credited/removed
		}
		if (isset($_POST['Line'.$line_no])) {
                        $min = 0;
                        $max = $itm->quantity - $itm->qty_done;
                        $max = (double)$max;
                
                        $max1 = $max + 0.0000000001;
                        $min1 = $min - 0.0000000001;
                        $tran_unit_disp_qty = input_num('Line'.$line_no); 
                        $base_unit_disp_qty = input_num('Line'.$line_no) * $itm->convertion_factor;
                        
			if (check_num2($base_unit_disp_qty, $min1, $max1)) {
        //                      if (check_num('Line'.$line_no, 0, ($itm->quantity / $itm->convertion_factor))) {
                                $_SESSION['Items']->line_items[$line_no]->qty_dispatched = $base_unit_disp_qty;
                                $_SESSION['Items']->line_items[$line_no]->tran_unit = $_SESSION['Items']->line_items[$line_no]->tran_unit; 
                                $_SESSION['Items']->line_items[$line_no]->tran_qty = $tran_unit_disp_qty; 
                                //$_SESSION['Items']->line_items[$line_no]->convertion_factor = $_SESSION['Items']->line_items[$line_no]->convertion_factor; 

                        }
                        else {
                                set_focus('Line'.$line_no);
                                return "Line Id $id: Entered quantity should be positive and not greater than ".$max/$itm->convertion_factor;
                        }
	  	}

		if (isset($_POST['Line'.$line_no.'Desc'])) {
			$line_desc = $_POST['Line'.$line_no.'Desc'];
			if (strlen($line_desc) > 0) {
				$_SESSION['Items']->line_items[$line_no]->item_description = $line_desc;
			}
	  	}
	}
	return $error;
}
//-----------------------------------------------------------------------------

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

function copy_from_cart()
{
	$cart = &$_SESSION['Items'];
	$_POST['ShipperID'] = $cart->ship_via;
	$_POST['ChargeFreightCost'] = price_format($cart->freight_cost);
	$_POST['CreditDate']= $cart->document_date;
	$_POST['Location']= $cart->Location;
	$_POST['CreditText']= $cart->Comments;
	$_POST['cart_id'] = $cart->cart_id;
	$_POST['ref'] = $cart->reference;
}
//-----------------------------------------------------------------------------

if (isset($_POST['ProcessCredit']) && can_process()) {
	$new_credit = ($_SESSION['Items']->trans_no == 0);

	if (!isset($_POST['WriteOffGLCode'])){
		$_POST['WriteOffGLCode'] = 0;
        }

	copy_to_cart();
	if ($new_credit){
		new_doc_date($_SESSION['Items']->document_date);
        }
        
	$ci_msg = $_SESSION['Items']->write_sales_credit_invoice($_POST['WriteOffGLCode']);
        
	if ($ci_msg['success'] !== true){
		display_error(_($ci_msg['message']));
		set_focus('ref');
	} 
        elseif($ci_msg['tran_no'] > 0){
		processing_end();
		if ($new_credit) {
			meta_forward($_SERVER['PHP_SELF'], "AddedID=".$ci_msg['tran_no']);
		} else {
			meta_forward($_SERVER['PHP_SELF'], "UpdatedID=".$ci_msg['tran_no']);
		}
	}
}

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

if (isset($_POST['Location'])) {
	$_SESSION['Items']->Location = $_POST['Location'];
}

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

function display_credit_items()
{
    start_form();
	hidden('cart_id');

    start_outer_table(TABLESTYLE2, "", 5);


    table_section(1, "width=30%");
            if ($_SESSION['Items']->trans_no==0) {
                ref_row(_("Reference"), 'ref', '', null);
            } else {
                ref_row(_("Reference"), $_SESSION['Items']->reference);
            }
            label_row(_("Customer"), $_SESSION['Items']->customer_name);
            label_row(_("Branch"), get_branch_name($_SESSION['Items']->Branch));
            label_row(_("Currency"), $_SESSION['Items']->customer_currency);

    
    table_section(2, "width=30%");
            if(isset($_POST['project_id'])){
                $_SESSION['Items']->project_id  = $_POST["project_id"];
            }
            $project = get_project_record($_SESSION['Items']->project_id);
            label_row(_("Project"),$project['description']);
            hidden('project_id', $_SESSION['Items']->project_id);
            
            label_row(_("Customer Delivery"), get_customer_trans_view_str(ST_CUSTDELIVERY, array_keys($_SESSION['Items']->src_docs)));

            if (!isset($_POST['ShipperID'])) {
                $_POST['ShipperID'] = $_SESSION['Items']->ship_via;
            }

            shippers_list_row("Shipping Company", 'ShipperID', $_POST['ShipperID']);
            
            order_categories_list_row(_("Order Category:"), 'order_category_id', OCT_SALES, $_SESSION['Items']->order_category_id);

     
    table_section(4, "width=30%");

            start_table(TABLESTYLE, "width=100%");

            label_row(_("Delivery Date"), $_SESSION['Items']->src_date);

            date_row(_("Credit Note Date"), 'CreditDate', '', $_SESSION['Items']->trans_no==0, 0, 0, 0, "class='tableheader2'");

            end_table();

    end_outer_table(1); // outer table

    div_start('credit_items');
    start_table(TABLESTYLE, "width=90%");
    $th = array(_("Id"), _("Item Code"), _("Item Description"), _("Invoiced Qty"),_("Returned Qty"), _("Units"),
    	_("Credit Qty"), _("Price"), _("Discount %"), _("Total"));
    table_header($th);

    $k = 0; //row colour counter

    foreach ($_SESSION['Items']->line_items as $line_no=>$ln_itm) {
            if ($ln_itm->quantity == $ln_itm->qty_done) {
                    continue; // this line was fully credited/removed
            }
            alt_table_row_color($k);

            label_cell($ln_itm->id, "align=center");
            //	view_stock_status_cell($ln_itm->stock_id); alternative view
            label_cell($ln_itm->stock_id);

            text_cells(null, 'Line'.$line_no.'Desc', $ln_itm->item_description, 30, 50);
            $dec = get_qty_dec($ln_itm->stock_id);
            //qty_cell($ln_itm->quantity, false, $dec);
            
            $tran_unit_invoiced_qty = $ln_itm->quantity / $ln_itm->convertion_factor;
            qty_cell($tran_unit_invoiced_qty, false, $dec);
            
            $tran_unit_credited_qty = $ln_itm->qty_done / $ln_itm->convertion_factor;
            qty_cell($tran_unit_credited_qty, false, $dec);
            
            //label_cell($ln_itm->units);
            label_cell($ln_itm->disp_unit);

            if(!(isset($_POST['Line'.$line_no]) && input_num('Line'.$line_no) > 0 )){
                $tran_qty = $tran_unit_invoiced_qty - $tran_unit_credited_qty;
            }
            else{
                $tran_qty = $ln_itm->qty_dispatched ;
            }
            amount_cells(null, 'Line'.$line_no, number_format2($tran_qty, $dec), null, null, $dec);
            //$line_total =($ln_itm->qty_dispatched * $ln_itm->price * $ln_itm->convertion_factor * (1 - $ln_itm->discount_percent));
            $line_total =(input_num('Line'.$line_no) * $ln_itm->price * $ln_itm->convertion_factor * (1 - $ln_itm->discount_percent));

            amount_cell($ln_itm->price * $ln_itm->convertion_factor);
            percent_cell($ln_itm->discount_percent*100);
            amount_cell($line_total);
            end_row();
    }

    if (!check_num('ChargeFreightCost')) {
    	$_POST['ChargeFreightCost'] = price_format($_SESSION['Items']->freight_cost);
    }
	$colspan = 7;
	start_row();
	label_cell(_("Credit Shipping Cost"), "colspan=$colspan align=right");
	small_amount_cells(null, "ChargeFreightCost", price_format(get_post('ChargeFreightCost',0)));
	end_row();

    $inv_items_total = $_SESSION['Items']->get_items_total_dispatch();

    $display_sub_total = price_format($inv_items_total + input_num($_POST['ChargeFreightCost']));
    label_row(_("Sub-total"), $display_sub_total, "colspan=$colspan align=right", "align=right");

    $all_taxes = $_SESSION['Items']->get_all_taxes(input_num($_POST['ChargeFreightCost']));
    $staxes_total = $_SESSION['Items']->get_staxes_total($all_taxes);

    $tax_total = display_edit_tax_items($all_taxes, $colspan, $_SESSION['Items']->tax_included);

    $display_total = price_format(($inv_items_total + input_num('ChargeFreightCost') + $tax_total - $staxes_total));

    label_row(_("Credit Note Total"), $display_total, "colspan=$colspan align=right", "align=right");

    end_table();
	div_end();
}

//-----------------------------------------------------------------------------
function display_credit_options()
{
	global $Ajax;
	br();

	if (isset($_POST['_CreditType_update']))
		$Ajax->activate('options');

 	div_start('options');
	start_table(TABLESTYLE2);

	credit_type_list_row(_("Credit Note Type"), 'CreditType', null, true);

	if ($_POST['CreditType'] == "Return")
	{

		/*if the credit note is a return of goods then need to know which location to receive them into */
		if (!isset($_POST['Location']))
			$_POST['Location'] = $_SESSION['Items']->Location;
	   	locations_list_row(_("Items Returned to Location"), 'Location', $_POST['Location']);
	}
	else
	{
		/* the goods are to be written off to somewhere */
		gl_all_accounts_list_row(_("Write off the cost of the items to"), 'WriteOffGLCode', null);
	}

	textarea_row(_("Memo"), "CreditText", null, 51, 3);
	echo "</table>";
 div_end();
}

//-----------------------------------------------------------------------------
if (get_post('Update'))
{
	$Ajax->activate('credit_items');
}
//-----------------------------------------------------------------------------

display_credit_items();
display_credit_options();

echo "<br><center>";
submit('Update', _("Calculate"), true, _('Update credit value for quantities entered'), true);
echo "&nbsp";
submit('ProcessCredit', _("Process Credit Note"), true, '', 'default');
echo "</center>";

end_form();


end_page();

?>
