<?php 
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Kvcodes CRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
/* Function : Estimate/Invoice for Customers
*****************************************/
$page_security = 'SA_OPEN';
$path_to_root="../..";

include_once($path_to_root . "/modules/KvcodesCRM/includes/cart_class.inc");

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/sales/includes/sales_ui.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/sales_order_ui.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/db/sales_db.inc");
include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
/*
set_page_security( @$_SESSION['Items']->trans_type,
	array(	ST_SALESINVOICE=>'ST_SALESINVOICE'),
	array(	'NewInvoice' => 'ST_SALESINVOICE',
			'ModifyInvoice' => 'ST_SALESINVOICE'	)
);*/

$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['ModifyInvoice']) && is_numeric($_GET['ModifyInvoice'])) {
	
	$_SESSION['page_title'] = sprintf(_("Modifying Project Invoice # %d"), $_GET['ModifyInvoice']);
	create_cart(ST_PROJECTINVOICE, $_GET['ModifyInvoice']);

} elseif (isset($_GET['NewInvoice'])) {
	$_SESSION['page_title'] = _("Project New Invoice");
	create_cart(ST_PROJECTINVOICE, 0);
} 

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

if (isset($_GET['ModifyInvoice']) && crm_is_prepaid_order_open($_GET['ModifyInvoice']))
{
	display_error(_("This order cannot be edited because there are invoices or payments related to it, and prepayment terms were used."));
	end_page(); exit;
}
if (isset($_GET['ModifyInvoice']))
	check_is_editable(ST_PROJECTINVOICE, $_GET['ModifyInvoice']);

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

if (isset($_GET['AddedID'])) {  //Upon creation of Invoice Successfully

	$order_no = $_GET['AddedID'];

	display_notification_centered(sprintf( _("Invoice # %d has been entered."),$order_no));

	crm_submenu_view(_("&View This Project Invoice"), ST_PROJECTINVOICE, $order_no);

	crm_submenu_print(_("&Print This Project Invoice"), ST_PROJECTINVOICE, $order_no, 'prtopt');
	crm_submenu_print(_("&Email This Project Invoice"), ST_PROJECTINVOICE, $order_no, null, 1);
	set_focus('prtopt');

	submenu_option(_("Enter a &New Project Invoice"),	"/modules/KvcodesCRM/invoice.php?NewInvoice=Yes");

	display_footer_exit();

} elseif (isset($_GET['UpdatedID'])) {
	$order_no = $_GET['UpdatedID'];

	display_notification_centered(sprintf( _("Project Invoice # %d has been updated."),$order_no));

	crm_submenu_view(_("&View This Project Invoice"), ST_PROJECTINVOICE, $order_no);

	crm_submenu_print(_("&Print This Project Invoice"), ST_PROJECTINVOICE, $order_no, 'prtopt');
	crm_submenu_print(_("&Email This Project Invoice"), ST_PROJECTINVOICE, $order_no, null, 1);
	set_focus('prtopt');

	submenu_option(_("Enter a &New Project Invoice"),	"/modules/KvcodesCRM/invoice.php?NewInvoice=Yes");

	display_footer_exit();

} else
	check_edit_conflicts(get_post('cart_id'));
//-----------------------------------------------------------------------------

function copy_to_cart(){
	$cart = &$_SESSION['Items'];
	$cart->reference = $_POST['ref'];
	$cart->Comments =  $_POST['Comments'];
	$cart->document_date = $_POST['OrderDate'];
	$newpayment = false;

	if (isset($_POST['payment']) && ($cart->payment != $_POST['payment'])) {
		$cart->payment = $_POST['payment'];
		$cart->payment_terms = get_payment_terms($_POST['payment']);
		$newpayment = true;
	}
	if ($cart->payment_terms['cash_sale']) {
		if ($newpayment) {
			$cart->due_date = $cart->document_date;
			$cart->phone = $cart->cust_ref = $cart->delivery_address = '';
			$cart->ship_via = 0;
			$cart->deliver_to = '';
			$cart->prep_amount = 0;
		}
	} else {
		$cart->due_date = $_POST['delivery_date'];
		$cart->cust_ref = $_POST['cust_ref'];
		$cart->deliver_to = $_POST['deliver_to'];
		$cart->delivery_address = $_POST['delivery_address'];
		$cart->phone = $_POST['phone'];
		$cart->ship_via = $_POST['ship_via'];
		if (!$cart->trans_no || ($cart->trans_type == ST_PROJECTINVOICE && !$cart->is_started()))
			$cart->prep_amount = input_num('prep_amount', 0);
	}
	$cart->Location = $_POST['Location'];
	$cart->freight_cost = input_num('freight_cost');
	if (isset($_POST['email']))
		$cart->email =$_POST['email'];
	else
		$cart->email = '';
	$cart->customer_id	= $_POST['customer_id'];
	$cart->Branch = $_POST['branch_id'];
	$cart->sales_type = $_POST['sales_type'];
	$cart->formType = (isset($_POST['formType']) ? $_POST['formType'] : 2 );
	$cart->project_id = (isset($_POST['project_id']) ? $_POST['project_id'] : 0 ); 
	$cart->billing_type = (isset($_POST['billing_type']) ? $_POST['billing_type'] : 0 ); 
	

	/*if ($cart->trans_type!=ST_PROJECTINVOICE && $cart->trans_type!=ST_SALESESTIMATE) { // 2008-11-12 Joe Hunt
		$cart->dimension_id = $_POST['dimension_id'];
		$cart->dimension2_id = $_POST['dimension2_id'];
	}*/
	$cart->ex_rate = input_num('_ex_rate', null);
}

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

function copy_from_cart()
{
	$cart = &$_SESSION['Items'];
	$_POST['ref'] = $cart->reference;
	$_POST['Comments'] = $cart->Comments;

	$_POST['OrderDate'] = $cart->document_date;
	$_POST['delivery_date'] = $cart->due_date;
	$_POST['cust_ref'] = $cart->cust_ref;
	$_POST['freight_cost'] = price_format($cart->freight_cost);

	$_POST['deliver_to'] = $cart->deliver_to;
	$_POST['delivery_address'] = $cart->delivery_address;
	$_POST['phone'] = $cart->phone;
	$_POST['Location'] = $cart->Location;
	$_POST['ship_via'] = $cart->ship_via;

	$_POST['customer_id'] = $cart->customer_id;
	if(!isset($_POST['project_id']))
		$_POST['project_id'] = $cart->project_id;
	$_POST['billing_type'] = $cart->billing_type;

	$_POST['branch_id'] = $cart->Branch;
	$_POST['sales_type'] = $cart->sales_type;
	$_POST['prep_amount'] = price_format($cart->prep_amount);
	// POS 
	$_POST['payment'] = $cart->payment;
	if ($cart->trans_type!=ST_PROJECTINVOICE && $cart->trans_type!=ST_SALESESTIMATE) { // 2008-11-12 Joe Hunt
		$_POST['dimension_id'] = $cart->dimension_id;
		$_POST['dimension2_id'] = $cart->dimension2_id;
	}
	$_POST['cart_id'] = $cart->cart_id;
	$_POST['_ex_rate'] = $cart->ex_rate;
}
//--------------------------------------------------------------------------------

function line_start_focus() {
  	global 	$Ajax;

  	$Ajax->activate('items_table');
  	set_focus('_stock_id_edit');
}

//--------------------------------------------------------------------------------
function can_process() {

	global $Refs, $SysPrefs;

	copy_to_cart();

	if (!get_post('customer_id')) {
		display_error(_("There is no customer selected."));
		set_focus('customer_id');
		return false;
	} 		
	
	if (!is_date($_POST['OrderDate'])) {
		display_error(_("The entered date is invalid."));
		set_focus('OrderDate');
		return false;
	}
	if ($_SESSION['Items']->trans_type!=ST_PROJECTINVOICE && $_SESSION['Items']->trans_type!=ST_SALESESTIMATE && !is_date_in_fiscalyear($_POST['OrderDate'])) {
		display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
		set_focus('OrderDate');
		return false;
	}
	if (count($_SESSION['Items']->line_items) == 0)	{
		display_error(_("You must enter at least one non empty item line."));
		set_focus('AddItem');
		return false;
	}
	if (!$SysPrefs->allow_negative_stock() && ($low_stock = $_SESSION['Items']->check_qoh()))
	{
		display_error(_("This document cannot be processed because there is insufficient quantity for items marked."));
		return false;
	}
		
	if (!db_has_currency_rates($_SESSION['Items']->customer_currency, $_POST['OrderDate']))
		return false;
	
   	if ($_SESSION['Items']->get_items_total() < 0) {
		display_error("Invoice total amount cannot be less than zero.");
		return false;
	}
	
	return true;
}

//-----------------------------------------------------------------------------
if (isset($_POST['update'])) {
	copy_to_cart();
	$Ajax->activate('items_table');
}

if (isset($_POST['ProcessOrder']) && can_process()) {

	$modified = ($_SESSION['Items']->trans_no != 0);
	$so_type = $_SESSION['Items']->so_type;
	
	$ret = $_SESSION['Items']->write(1);
	if ($ret == -1)	{
		display_error(_("The entered reference is already in use."));
		$ref = $Refs->get_next($_SESSION['Items']->trans_type, null, array('date' => Today()));
		if ($ref != $_SESSION['Items']->reference){
			unset($_POST['ref']); // force refresh reference
			display_error(_("The reference number field has been increased. Please save the document again."));
		}
		set_focus('ref');
	} else {
		if (count($messages)) { // abort on failure or error messages are lost
			$Ajax->activate('_page_body');
			display_footer_exit();
		}
		$trans_no = key($_SESSION['Items']->trans_no);
		$trans_type = $_SESSION['Items']->trans_type;
		new_doc_date($_SESSION['Items']->document_date);
		processing_end();
		
		if ($modified) {
			meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$trans_no");
		} else {
			meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
		} 
	}	
}

//--------------------------------------------------------------------------------
function check_item_data(){
	global $SysPrefs;

	if($_SESSION['Items']->trans_type != ST_PROJECTINVOICE ) {
		$is_inventory_item = is_inventory_item(get_post('stock_id'));
		
		if (!check_num('qty', 0) || !check_num('Disc', 0, 100)) {
			display_error( _("The item could not be updated because you are attempting to set the quantity ordered to less than 0, or the discount percent to more than 100."));
			set_focus('qty');
			return false;
		} elseif (!check_num('price', 0) && (!$SysPrefs->allow_negative_prices() || $is_inventory_item)) {
			display_error( _("Price for inventory item must be entered and can not be less than 0"));
			set_focus('price');
			return false;
		} elseif (isset($_POST['LineNo']) && isset($_SESSION['Items']->line_items[$_POST['LineNo']])
		    && !check_num('qty', $_SESSION['Items']->line_items[$_POST['LineNo']]->qty_done)) {

			set_focus('qty');
			display_error(_("You attempting to make the quantity ordered a quantity less than has already been delivered. The quantity delivered cannot be modified retrospectively."));
			return false;
		}

		$cost_home = get_unit_cost(get_post('stock_id')); // Added 2011-03-27 Joe Hunt
		$cost = $cost_home / get_exchange_rate_from_home_currency($_SESSION['Items']->customer_currency, $_SESSION['Items']->document_date);
		if (input_num('price') < $cost){
			$dec = user_price_dec();
			$curr = $_SESSION['Items']->customer_currency;
			$price = number_format2(input_num('price'), $dec);
			if ($cost_home == $cost)
				$std_cost = number_format2($cost_home, $dec);
			else
			{
				$price = $curr . " " . $price;
				$std_cost = $curr . " " . number_format2($cost, $dec);
			}
			display_warning(sprintf(_("Price %s is below Standard Cost %s"), $price, $std_cost));
		}	
		$total_amt_entered =  input_num('qty')*input_num('price') +input_num('display_total');
		if(($_SESSION['Items']->trans_type == ST_SALESINVOICE || $_SESSION['Items']->trans_type == ST_CUSTDELIVERY  ) &&$total_amt_entered > $_SESSION['Items']->credit){
			display_error(_("The invoice Total is greater than the customer credit"));
			return false;
		}
	} else {
		if(get_post('project_id') == '' ) {
			display_error( _("Select a Project to Add Items to cart."));
			set_focus('project_id');
			return false;
		}
	}

	if(!get_post('stock_id_text', true)) {
		display_error( _("Item description cannot be empty."));
		set_focus('stock_id_edit');
		return false;
	}

	return true;
}

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

function handle_update_item(){
	if ($_POST['UpdateItem'] != '' && check_item_data()) {
		$_SESSION['Items']->update_cart_item($_POST['LineNo'], input_num('qty'), input_num('price'),
		 input_num('Disc') / 100, $_POST['item_description'], get_post('units') );
	}
	page_modified();
  line_start_focus();
}

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

function handle_delete_item($line_no){
    if ($_SESSION['Items']->some_already_delivered($line_no) == 0) {
	    $_SESSION['Items']->remove_from_cart($line_no);
    } else {
		display_error(_("This item cannot be deleted because some of it has already been delivered."));
    }
    line_start_focus();
}

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

function handle_new_item(){
	if (!check_item_data()) {
			return;
	}	
	add_to_order($_SESSION['Items'], get_post('stock_id'), input_num('qty'), input_num('price'), input_num('Disc') / 100, get_post('stock_id_text'), get_post('units'), get_post('itemType'), get_post('project_id'), get_post('billing_type'),get_post('tax_type_id'));

	unset($_POST['_stock_id_edit'], $_POST['stock_id']);
	page_modified();
	line_start_focus();
}

//--------------------------------------------------------------------------------
function  handle_cancel_order(){
	global $path_to_root, $Ajax;

	if ($_SESSION['Items']->trans_type == ST_CUSTDELIVERY) {
		display_notification(_("Direct delivery entry has been cancelled as requested."), 1);
		submenu_option(_("Enter a New Sales Delivery"),	"/sales/sales_order_entry.php?NewDelivery=1");
	} elseif ($_SESSION['Items']->trans_type == ST_SALESINVOICE) {
		display_notification(_("Direct invoice entry has been cancelled as requested."), 1);
		submenu_option(_("Enter a New Sales Invoice"),	"/sales/sales_order_entry.php?NewInvoice=1");
	} elseif ($_SESSION['Items']->trans_type == ST_SALESESTIMATE)
	{
		if ($_SESSION['Items']->trans_no != 0) 
			crm_delete_sales_order(key($_SESSION['Items']->trans_no), $_SESSION['Items']->trans_type);
		display_notification(_("This sales quotation has been cancelled as requested."), 1);
		submenu_option(_("Enter a New Sales Quotation"), "/sales/sales_order_entry.php?NewEstimate=Yes");
	} else { // sales order
		if ($_SESSION['Items']->trans_no != 0) {
			$order_no = key($_SESSION['Items']->trans_no);
			if (crm_sales_order_has_deliveries($order_no))	{
				crm_close_sales_order($order_no);
				display_notification(_("Undelivered part of order has been cancelled as requested."), 1);
				submenu_option(_("Select Another Sales Order for Edition"), "/sales/inquiry/proposal_estimate_inquiry.php?type=".ST_PROJECTINVOICE);
			} else {
				crm_delete_sales_order(key($_SESSION['Items']->trans_no), $_SESSION['Items']->trans_type);

				display_notification(_("This sales order has been cancelled as requested."), 1);
				submenu_option(_("Enter a New Sales Order"), "/sales/sales_order_entry.php?NewInvoice=Yes");
			}
		} else {
			processing_end();
			meta_forward($path_to_root.'/index.php','application=orders');
		}
	}
	processing_end();
	display_footer_exit();
}

//--------------------------------------------------------------------------------
function create_cart($type, $trans_no){ 
	global $Refs, $SysPrefs;

	if (!$SysPrefs->db_ok) // create_cart is called before page() where the check is done
		return;

	processing_start();

	if (isset($_GET['NewEstimateToSalesOrder'])){
		$trans_no = $_GET['NewEstimateToSalesOrder'];
		$doc = new CRMCart(ST_SALESESTIMATE, $trans_no, true);
		$doc->Comments = _("Sales Estimate") . " # " . $trans_no;
		$_SESSION['Items'] = $doc;
	} elseif (isset($_GET['NewInvoiceToSalesOrder'])){
		$trans_no = $_GET['NewInvoiceToSalesOrder'];
		$doc = new CRMCart(ST_PROJECTINVOICE, $trans_no, true);
		$doc->Comments = _("Sales Invoice") . " # " . $trans_no;
		$_SESSION['Items'] = $doc;
	} elseif($type != ST_PROJECTINVOICE && $type != ST_SALESESTIMATE && $trans_no != 0) { // this is template

		$doc = new CRMCart(ST_PROJECTINVOICE, array($trans_no));
		$doc->trans_type = $type;
		$doc->trans_no = 0;
		$doc->document_date = new_doc_date();
		$doc->due_date = $doc->document_date;
		$doc->reference = $Refs->get_next($doc->trans_type, null, array('date' => Today()));
		//$doc->Comments='';
		foreach($doc->line_items as $line_no => $line) {
			$doc->line_items[$line_no]->qty_done = 0;
		}
		$_SESSION['Items'] = $doc;
	} else
		$_SESSION['Items'] = new CRMCart($type, array($trans_no));
	copy_from_cart();
}

//--------------------------------------------------------------------------------
if (isset($_POST['CancelOrder']))
	handle_cancel_order();

$id = find_submit('Delete');
if ($id!=-1)
	handle_delete_item($id);

if (isset($_POST['UpdateItem']))
	handle_update_item();

if (isset($_POST['AddItem']))
	handle_new_item();

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

if(list_updated('project_id') ){	
	$_SESSION['Items']->line_items = array();
	$project_details = GetRow('kv_crm_projects', array('id' => $_POST['project_id']));
	$hours = 1;
	if($project_details['billing_type'] == 1){ //Fixed Budget 
		$price = $project_details['project_cost'];
		$add_item=true;
	} elseif($project_details['billing_type'] == 2){  //Project Hours
		$price = $project_details['project_rate_per_hour']; //*$project_details['estimated_hours'];
		$add_item=true;
		$hours = $project_details['estimated_hours'];
	} else {
		$add_item=false;
	}
	if($add_item)
		add_to_order($_SESSION['Items'], get_post('project_id'), $hours, $price, 0, $project_details['name'], $project_details['units'], 1);
}
//--------------------------------------------------------------------------------
if ($_SESSION['Items']->fixed_asset)
	check_db_has_disposable_fixed_assets(_("There are no fixed assets defined in the system."));
else
	check_db_has_stock_items(_("There are no inventory 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 ($_SESSION['Items']->trans_type == ST_PROJECTINVOICE) {

	$idate = _("Invoice Date:");
	$orderitems = _("Project Invoice Items");
	$cancelorder = _("Cancel Invoice");
	$porder = _("Place Invoice");
	$corder = _("Commit Invoice Changes");
	
}
start_form();

hidden('cart_id');
$customer_error = display_order_header($_SESSION['Items'], !$_SESSION['Items']->is_started(), $idate);

//display_error(json_encode($_SESSION['Items']->line_items));
if ($customer_error == "") {
	start_table(TABLESTYLE, "width='80%'", 10);
	echo "<tr><td>";
	display_order_summary($orderitems, $_SESSION['Items'], true);
	echo "</td></tr>";
	echo "<tr><td>";
	display_delivery_details($_SESSION['Items']);
	echo "</td></tr>";
	end_table(1);

	//display_error(input_num('display_total'));
	if ($_SESSION['Items']->trans_no == 0) {

		submit_center_first('ProcessOrder', $porder,    _('Check entered data and save document'), 'default');
		submit_center_last('CancelOrder', $cancelorder,	_('Cancels document entry or removes sales order when editing an old document'));
		submit_js_confirm('CancelOrder', _('You are about to void this Document.\nDo you want to continue?'));
	} else {
		submit_center_first('ProcessOrder', $corder,    _('Validate changes and update document'), 'default');
		submit_center_last('CancelOrder', $cancelorder,	_('Cancels document entry or removes sales order when editing an old document'));
		if ($_SESSION['Items']->trans_type==ST_PROJECTINVOICE)
			submit_js_confirm('CancelOrder', _('You are about to cancel undelivered part of this order.\nDo you want to continue?'));
		else
			submit_js_confirm('CancelOrder', _('You are about to void this Document.\nDo you want to continue?'));
	}

} else {
	display_error($customer_error);
}

end_form();
end_page(); ?>