
<%= javascript_include_tag 'wklogmaterial', :plugin => "redmine_wktime" %>
<%= javascript_include_tag 'index', :plugin => "redmine_wktime" %>
<%
	Issue.class_eval do
		has_one :wk_issue, :dependent => :destroy, :class_name => 'WkIssue'
		has_many :assignees, :dependent => :destroy, :class_name => 'WkIssueAssignee'
		accepts_nested_attributes_for :assignees
		accepts_nested_attributes_for :wk_issue
		def erpmineissues
			self.wk_issue ||= WkIssue.new(:issue => self, :project => self.project)
		end
	end

	Project.class_eval do
		has_many :account_projects, :dependent => :destroy, :class_name => 'WkAccountProject'
		#has_many :parents, through: :account_projects
	end

	TimeEntry.class_eval do
	  has_one :spent_for, as: :spent, class_name: 'WkSpentFor', :dependent => :destroy
	  has_one :invoice_item, through: :spent_for

	  accepts_nested_attributes_for :spent_for
	end
%>
<% catagoriesList = { 's'  => l(:label_salaried), 'h' =>  l(:label_hourly) }  %>
<% logmaterial_helper = Object.new.extend(WklogmaterialHelper)	%>
<% wktime_helper = Object.new.extend(WktimeHelper) %>
<% wkasset_helper = Object.new.extend(WkassetHelper) %>
<% rateperHash = wkasset_helper.getRatePerHash(false) %>
<% logtype = logmaterial_helper.getLogHash %>
<% spentForsValue = wktime_helper.getSpentFors(User.current.id, @time_entry.project_id) %>
<% if (Setting.plugin_redmine_wktime['wktime_enable_inventory_module'].blank? &&
			Setting.plugin_redmine_wktime['wktime_enable_inventory_module'].to_i == 0 ) %>
			<% logtype.delete("M") %>
			<% logtype.delete("A") %>
<% end %>
<% if (Setting.plugin_redmine_wktime['wktime_enable_expense_module'].blank? &&
			Setting.plugin_redmine_wktime['wktime_enable_expense_module'].to_i == 0 ) %>
			<% logtype.delete("E") %>
<% end %>
<% 	productArr = ""
	locationArr = ""
	brandArr = ""
	itemArr = ""
	locationId = ""
	locId = nil
	itemObj = nil
	productSNs = []
	serialNumbers = []
	hidden_sns = []
%>
<% productArr = logmaterial_helper.getProductArray(WkProduct, '', '', false)  %>
<% locationArr = WkLocation.order(:name).pluck(:name, :id) %>
<% uomArr = logmaterial_helper.getUOMArray(nil, false)  %>
<% productId = @materialEntry.blank? ? ( productArr.blank? ? 0 : productArr[0][1]) : @materialEntry.inventory_item.product_item.product.id    %>
<!-- Below Array contains the inventory item id and combination of brand, model, partnumber, attribute, selling price as display field  -->
<% ltype = @spentType == 'M' ? 'I' : @spentType  %>
<% locId = locationArr[0][1] unless locationArr.blank? %>
<% locationId = @materialEntry.blank? ? locId : @materialEntry.inventory_item.location_id %>
<% itemArr = logmaterial_helper.getPdtItemArr(productId, false, ltype, locationId)  %>
<% itemId = @materialEntry.blank? ? '' : @materialEntry.inventory_item_id  %>
<% uomId = @materialEntry.blank? ? '' : @materialEntry.uom_id  %>
<% inventoryItemId = @materialEntry.blank? ? (itemArr.blank? ? '' : itemArr[0][1]) : @materialEntry.inventory_item.id %>
<% itemObj = WkInventoryItem.find(inventoryItemId) unless inventoryItemId.blank?  %>
<%= hidden_field_tag 'inventory_item_id', (itemObj.blank? ? "" : itemObj.id) %>
<% matterialId = @materialEntry.blank? ? '' : @materialEntry.id  %>
<%= hidden_field_tag 'matterial_entry_id', matterialId %>
<%= hidden_field_tag 'expense_entry_id', (@expenseEntry.blank? ? '' : @expenseEntry.id) %>
<% expenseAmount = @expenseEntry.blank? ? "" : @expenseEntry.amount  %>
<%  assetObj = @materialEntry.blank? ? nil : @materialEntry.inventory_item.asset_property %>
<% disable = @materialEntry.blank? || @materialEntry.spent_for.blank? || @materialEntry.spent_for.invoice_item_id.blank? ? false : true  %>
<%= hidden_field_tag 'old_log_type', @spentType == 'E' ? 'wk_expense_entry' : (@spentType == 'M' || @spentType == 'A' ? 'wk_material_entry' : 'time_entry') %>
<%#=h hidden_field_tag('getclients_url', "#{url_for(:controller => 'wktime', :action => 'getclients', :user_id => User.current.id, :separator => ',')}") %>
<%= hidden_field_tag 'userId', User.current.id %>
<%
	if @spentType == 'E' && !@expenseEntry.blank?
		objEntry = @expenseEntry
	elsif (@spentType == 'T' || @spentType.blank?) && (!@time_entry.blank? && !@time_entry.spent_for.blank?)
		objEntry = @time_entry
	elsif !@materialEntry.blank?
		objEntry = @materialEntry
	end
	selectedSpentFor = objEntry.present? ? objEntry.project_id.to_s + '|' + objEntry.spent_for.spent_for_type.to_s + '_' + objEntry.spent_for.spent_for_id.to_s : ""
	spentForIdVal = objEntry.present? ? objEntry.spent_for.id : ""
	issueSub = objEntry && objEntry.issue.present? ? objEntry.issue.subject : ""
	endLocations =  objEntry.blank? || (@spentType.present? && @spentType != 'T') ? ["",""] : [
		objEntry.spent_for.e_longitude || "", objEntry.spent_for.e_latitude || "", objEntry.project.name+ "\n"+ issueSub+"\n"+objEntry.hours.to_s, "E"
	]
	if objEntry.blank? || (objEntry.spent_for.s_longitude == objEntry.spent_for.e_longitude && objEntry.spent_for.s_latitude == objEntry.spent_for.e_latitude) || (@spentType.present? && @spentType != 'T')
		startLocations = ["",""]
	else
		startLocations = [
			objEntry.spent_for.s_longitude || "", objEntry.spent_for.s_latitude || "", objEntry.project.name+ "\n"+ objEntry.issue.subject+"\n"+objEntry.hours.to_s, "S"
		]
	end
%>
<%= hidden_field_tag 'spentForId', spentForIdVal %>
<script type="text/javascript">
	productModifyUrl="<%= "#{url_for(:controller => "wklogmaterial", :action => 'modifyProductDD')}" %>";
   getClientsUrl = 	"<%= "#{url_for(:controller => "wktime", :action => 'getclients', :user_id => User.current.id, :separator => ',')}" %>";
</script>
<% productSNs = logmaterial_helper.getProductSNs(itemId) if itemId.present? %>
<% serialNumbers = WkConsumedItems.get_serial_nos(@materialEntry.id, 'WkMaterialEntry').map{|e| e.serial_number} if @materialEntry.present? %>
<% hidden_sns = WkConsumedItems.get_serial_nos(@materialEntry.id, 'WkMaterialEntry').map{|e| {id: e.id, serial_number: e.serial_number}} if @materialEntry.present? %>
<%= hidden_field_tag 'product_serial_numbers', productSNs.to_json || [] %>
<%= hidden_field_tag 'hidden_sns', hidden_sns.to_json || [] %>

<table style="padding-left:100px;">
	<tr>
		<th align="right" ><%= l(:label_log_type) %><span style="color:red;">*</span></th>
		<td align="left">
			<%=h select_tag('log_type', options_for_select(logtype.invert, :selected => (@spentType.blank? ? "T" : @spentType)), :style => "width:155px;", :onchange => "hideLogDetails(#{User.current.id});") %>
		</td>
	</tr>
</table>

<% if wktime_helper.showBilling %>
	<table id='spent_for_tbl' style="padding-left:100px;">
		<tr>
			<th align="right" ><%= l(:label_spent_for) %></th>
			<td align="left">
				<%=h select_tag('spent_for', options_for_select(spentForsValue, :selected => selectedSpentFor.blank? ? spentForsValue : selectedSpentFor), :style => "width:155px;") %>
			</td>
		</tr>
	</table>
<% end %>

<table id="materialtable" style="padding-left:65px; display:none;">
	<tr>
		<th align="right" ><%= l(:field_location) %><span style="color:red;">*</span></th>
		<td align="left">
			<%=h select_tag('location_id', options_for_select(locationArr, :selected => (locationId.blank? ? locationArr : locationId) ), :style => "width:155px;", :onchange => "productChanged('product', 'product_item', #{User.current.id}, true, false, 'log_type', 'location_id'); ", :disabled => disable) %>
		</td>
		<th align="right"><%= l(:label_available_quantity) %></th>
		<% availableQuantity = itemObj.blank? ? " " : itemObj.available_quantity  %>
		<td align="left" ><label id="available_quantity" style="padding-left: 125px; text-align:right;"><%=h html_hours("%.2f" % availableQuantity ) unless availableQuantity.blank? %></label></td>
	</tr>
	<tr>
		<th align="right" ><%= l(:label_product) %><span style="color:red;">*</span></th>
		<td align="left">
			<%=h select_tag('product', options_for_select(productArr, :selected => (productId.blank? ? productArr : productId) ), :style => "width:155px;", :onchange => "productChanged(this.id, 'product_item', #{User.current.id}, true, false, 'log_type', 'location_id'); ", :disabled => disable) %>
		</td>
		<% totQuantity = @materialEntry.blank? ? 1 : @materialEntry.quantity  %>
		<th align="right"><%= l(:field_quantity) %><span style="color:red;">*</span></th>
		<td align="left" style="padding-left: 40px;">
			<%=h text_field_tag("product_quantity", ("%.2f" % totQuantity  ),:size => 10, :style => "width:80px;text-align:right;", :onchange => "updateTotal(this.id, 'product_sell_price', 'total', 'spcurrency');", :disabled => disable) %>
			<%=h select_tag("uom_id", options_for_select(uomArr, :selected => uomId.blank? ? uomArr  : uomId), :disabled => disable) %>
		</td>
	</tr>
	<tr>
		<th align="right" ><%= l(:label_product_items) %><span style="color:red;">*</span></th>
		<td align="left" >
			<%= select_tag('product_item', options_for_select(itemArr, :selected => itemId.blank? ? itemArr  : itemId), :style => "width:155px;", :onchange => "productItemChanged(this.id, 'product_quantity', 'product_cost_price', 'product_sell_price', #{User.current.id}, 'log_type' ); productUOMChanged(this.id, 'uom_id', #{User.current.id})", :disabled => disable) %>
			<span><%= link_to l(:label_details), logmaterial_helper.get_item_details_url(itemId, @spentType), class: 'icon icon-report' if itemId.present? %></span>
		</td>
		<th align="right"><%= l(:label_sell_price) %><span style="color:red;">*</span></th>
		<td align="left" colspan="3" >
			<label id="spcurrency" style="padding-left:45px;"><%=h (itemObj.blank? ? "" : itemObj.currency) %></label>
			<% sellPrice = @materialEntry.blank? ? "" : @materialEntry.selling_price  %>
			<%=h text_field_tag("product_sell_price", sellPrice.blank? ? "" : ("%.2f" % sellPrice),:size => 20, :style => "width:80px; text-align:right;", :onchange => "updateTotal(this.id, 'product_quantity', 'total', 'spcurrency');", :disabled => disable) %>
			<label id="unittext" style="float:right;padding-left: 120px; " >
			<% assetlabel = (assetObj.rate_per.blank? ? "" : "/ " + rateperHash[assetObj.rate_per]) unless assetObj.blank? %>
			<%=h assetObj.blank? ? "" : assetlabel %></label>
		</td>
	</tr>
		<tr id="material_serial_no">
				<th align="right"><%= l(:label_serial_number) %></th>
				<td> <%= text_area_tag("material_sn", serialNumbers.join(','), rows:4) %>
				<div><%= l(:label_serial_number_note) %></div>
				<span class="icon icon-warning warning" id="warn_serial_number" style="background-color: unset; border: 0;display:none;"><%= l(:warn_sn_range) %></span></td>
		</tr>
	<tr>
		<% if wktime_helper.isModuleAdmin('wktime_inventory_admin') && @spentType == 'M'  %>
			<th align="right"><%= l(:label_cost_price) %><span style="color:red;">*</span></th>
			<td align="left" style="padding-left: 40px;">

				<label id="cpcurrency" ><%=h (itemObj.blank? ? "" : itemObj.currency) %></label>
				<% costPrice = itemObj.blank? ? "" : itemObj.cost_price %>
				<%=h text_field_tag("product_cost_price", costPrice.blank? ? "" : ("%.2f" % costPrice) ,:size => 20, :disabled => true, :style => "width:100px; text-align:right; float:right") %>
			</td>
		<% elsif @spentType != 'T' && @spentType != 'E' && @spentType != 'I'  %>
			<th align="right"><%= l(:label_done) %></th>
			<% isDone = assetObj.blank? || assetObj.matterial_entry_id.blank? ? true :  false  %>
			<td align="left" style="padding-left: 10px;"><%= check_box_tag("is_done", 1, isDone, :disabled => disable) %></td>
		<% else %>
			<th></th>
			<td></td>
		<% end %>
		<th align="right"><%= l(:label_total) %></th>
		<td>
			<!-- <label id="totalcurrency" style="padding-left: 40px;"><%#=h (itemObj.blank? ? "" : itemObj.currency) %></label> -->
			<% netTotal = @materialEntry.blank? ? 0 : (@materialEntry.selling_price * @materialEntry.quantity)  %>
			<label id="total" style="padding-left: 127px; text-align:right;"><%=h (itemObj.blank? ? "" : itemObj.currency) %><%=h html_hours("%.2f" % netTotal ) unless netTotal.blank? %></label>
		</td>
	</tr>
</table>

<% wkexpense_helper = Object.new.extend(WkexpenseHelper) %>
<table id="expensetable" style="padding-left:110px; display:none;">
	<tr>
		<th align="right"><%= l(:field_currency) %></th>
		<td align="left" ><%=h select_tag('wktime_currency',options_for_select(wkexpense_helper.options_for_currency), :style => "width:55px;") %>
		<%=h text_field_tag("expense_amount", expenseAmount.blank? ? nil : ("%.2f" % expenseAmount),:size => 20, :style => "width:90px; text-align:right;") %>
		</td>
	</tr>
</table>

<!-- Issue Time Tracker-->
<% if (@project.present? && wktime_helper.showIssueLogger(@project) || @project.blank? && wktime_helper.isChecked("label_enable_issue_logger")) && (@spentType.blank? || @spentType == "T" || @spentType == "A") %>
	<%= hidden_field_tag("allowedProjects", wktime_helper.getEditLogPermission ) %>
	<%
		obj = @spentType.blank? || @spentType == "T" ? @time_entry : @materialEntry
		startOn = nil
		start_on = nil
		if obj.present? && obj.spent_for && obj.spent_for.spent_on_time
			seconds = Time.now - obj.spent_for.spent_on_time
			start_on = (obj.spent_for.spent_on_time.localtime.to_s.split("T")).last
			start_on = (start_on.split("+")).first
		end
		end_on = nil
		if obj.present? && obj.spent_for && obj.spent_for.end_on
			end_on = obj.spent_for.end_on.localtime
			end_on = (end_on.to_s.split("T")).last
			end_on = (end_on.split("+")).first
		end
		logger = WkSpentFor.getIssueLog(params[:id].blank? ? 0 : params[:id], @spentType).first
		issuelogTimer = logger.present? ? wktime_helper.time_diff(Time.now, logger.spent_on_time) : "00:00"
		issueStarted = logger.present? && logger.clock_action == "S"
		imgName = issueStarted ? ["finish", "red"] : ["start", "green"]
		button = issueStarted || logger.blank? ? content_tag("div", (logger.present? ? "Stop" : "Start"), class: "drdn-trigger issueLog clock", id: "issueLogger",
			style: "color: white; font-weight: bold; border-radius: 20px; background: #{imgName[1]}; padding-left: 15px; padding-top: 5px; padding-bottom: 5px; padding-right: 15px;") : nil
	%>
	<%= javascript_tag do %>
		var label_warn_hours = "<%= l(:label_warn_hours) %>";
		<% if issueStarted %>
			$(function(){
				$("#logTimer").timer({
					action: 'start',
					seconds: <%= seconds.to_i %>
				});
			});
		<% end %>
	<% end %>
	<%= hidden_field_tag("clock_action", logger.present? ? logger.clock_action : nil ) %>
	<%= hidden_field_tag("end_on", end_on, class: "end_on" ) %>
	<%= hidden_field_tag("start_on", startOn, class: "start_on" ) %>
	<%= hidden_field_tag("offSet", nil ) %>
	<%= hidden_field_tag("current_user", User.current.id ) %>
	<%= hidden_field_tag((issueStarted ? "time_entry[spent_on]" : "h_time_entry[spent_on]"), startOn ? startOn.to_date : nil, id: "h_time_entry_spent_on") %>
	<%= hidden_field_tag((issueStarted ? "time_entry[hours]" : "h_time_entry[hours]"), "0.1", id: "h_time_entry_hours") %>
	<table id="issuelogtable" style="padding-left:95px;">
		<tr>
			<th align="right" ><%= l(:label_start_time) %></th>
			<td align="left" id="td_start_on"><%= start_on %></td>
			<td id="s_issueLogger">
				<%= button %>
			</td>
		</tr>
		<tr>
			<th align="right" ><%= l(:label_end_time) %></th>
			<td align="left" id="td_end_on"><%= end_on %></td>
			<td id="e_issueLogger"></td>
		</tr>
	</table>
	<% if issueStarted %>
		<span id="logTimer" ><%= issuelogTimer %></span>
	<% end %>
<% end %>

<% if wktime_helper.isChecked('te_save_geo_location') && ["T", "E", "M", "A"].include?(@spentType) %>
	<!-- Geolocation -->
	<table id="geolocation" style="padding-left:100px;">
		<tr><td>
			<div id='mapContainer' style="width:30%;height:300px;"></div>
			<%= render partial: "wkgeolocation/location_map", locals: { locations: [startLocations, endLocations] } %>
		</td></tr>
	</table>
<% end %>