<style>
	.accordion {
		background-color: #eee;
		color: #444;
		cursor: pointer;
		width: 100%;
		border: none;
		outline: none;
		transition: 0.4s;
	}

	.active1, .accordion:hover {
		background-color: #ccc;
	}

	.accordion:after {
		content: '\002B';
		color: #007bff;
		font-weight: bold;
		float: right;
		font-size: 150%;
		margin-left: 5px;
	}

	.active1:after {
		content: "\2212";
	}

	.panel {
		padding: 0 18px;
		background-color: white;
		max-height: 0;
		overflow: hidden;
		transition: max-height 0.2s ease-out;
	}
</style>

<section class="container" style="padding-bottom: 2rem;">
	<div class="row">
		<div class="col-sm-12">
			<div class="tab-content" id="tabContent">
				<div class="tab-pane fade show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
					<div class="card bg-light-transparent">
						<div class="card-header bg-light">
							<h4 class="card-title float-left"><?php echo (empty($ID))?'New ':'Edit '; ?> Invoice Request Form</h4>
						</div>
						<div class="card-body">
							<div class="card no-shadow">
								<div class="card-body">
									<?php if(!empty($ID)){ ?>
										<form id="invoiceForm" class="form" action="<?php echo ($invoice_list['approval_status'] > 0)?base_url('hr/Serviceform/invoice_edit/'.$mode):(($invoice_list['total'] > 0)?base_url('hr/Serviceform/invoice_edit'):base_url('hr/Serviceform/invoice_edit/first')); ?>" method="POST" onsubmit="return confirm('Confirm to update this form?')">
										<?php }else{ ?>	
											<form id="invoiceForm" class="form" action="<?php echo base_url('hr/Serviceform/invoice_save') ?>" method="POST" onsubmit="return confirm('Confirm to submit this form?')">
											<?php }?>

											<input type="text" class="form-control" name="invoiceID" id="invoiceID" value="<?php echo $ID; ?>" hidden>
											<input type="text" class="form-control" name="entityID" id="entityID" value="<?php echo $entity_id; ?>" hidden>

											<div class="form-row">
												<div class="col-12 col-sm-6">
													<div class="form-group">
														<label>MGS Job ID</label>
														<select class="form-control select" name="job_id" id="job_id" required onchange="change_client_input()">
															<option></option>
															<?php if($mgs_job) foreach($mgs_job as $row){ ?>
																<option value="<?php echo $row['job_id'] ?>">
																	<?php echo '[JOB ID: '.str_pad($row['job_id'],5,0,STR_PAD_LEFT).'] '.$row['customerName'].' - '.$row['job_description']; ?>
																</option>
															<?php } ?>
														</select>
													</div>
												</div>

												<div class="col-12 col-sm-6">
													<div class="form-group">
														<label>Company Name</label>
														<select class="form-control select" name="client_id" id="client_id" required onchange="change_job_input()" <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':'disabled'; ?>>
															<option></option>
															<?php if($client) foreach($client as $row){ ?>
																<option value="<?php echo $row->id; ?>">
																	<?php echo $row->name; ?>
																</option>
															<?php } ?>
														</select>
													</div>
												</div>

												<div class="col-12 col-sm-6">
													<div class="form-group">
														<label>Group</label>
														<input type="text" class="form-control" name="client_group_id" id="client_group_id" <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':'readonly'; ?>>
													</div>
												</div>

												<div class="col-12 col-sm-6">
													<div class="form-group">
														<label>Tel No</label>
														<?php if($mode != 'view'){ ?>
															<button type="button" id="addClientPhone" class="btn btn-sm btn-warning float-right" onclick="open_modal('client_phone')" data-trigger="hover" data-tooltip="tooltip" title="Add Client Telephone Number"><i class="fas fa-plus" <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>></i></button>
														<?php } ?>
														<select class="form-control" name="client_tel_no" id="client_tel_no" required onchange="change_email_input()" <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>>
															<option value="-1" selected disabled>-- Please Select --</option>
														</select>
													</div>
												</div>

												<div class="col-12 col-sm-6">
													<div class="form-group">
														<label>Fax No</label>
														<!-- <button type="button" id="addClientFax" class="btn btn-sm btn-warning float-right" onclick="open_modal('client_fax')" data-trigger="hover" data-tooltip="tooltip" title="Add Client Fax"><i class="fas fa-plus" <?php //echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>></i></button> -->
														<input type="text" class="form-control" name="client_fax_no" id="client_fax_no" <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':'readonly'; ?>>
													</div>
												</div>

												<div class="col-12 col-sm-6">
													<div class="form-group">
														<label>Email</label>
														<!-- <button type="button" id="addClientEmail" class="btn btn-sm btn-warning float-right" onclick="open_modal('client_email')" data-trigger="hover" data-tooltip="tooltip" title="Add Client Email Address"><i class="fas fa-plus" <?php //echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>></i></button> -->
														<input type="text" class="form-control" name="client_email" id="client_email" required <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':'readonly'; ?>>
													</div>
												</div>

												<div class="col-12">
													<div class="form-group">
														<label>Address</label>
														<?php if($mode != 'view'){ ?>
															<button type="button" id="addClientAddress" class="btn btn-sm btn-warning float-right" onclick="open_modal('client_address')" data-trigger="hover" data-tooltip="tooltip" title="Add Client Address"><i class="fas fa-plus" <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>></i></button>
														<?php } ?>
														<!-- <textarea class="form-control" rows="3" name="client_address" id="client_address" required <?php //echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>></textarea> -->
														<select class="form-control" name="client_address" id="client_address" required></select>
													</div>
												</div>

												<div class="col-12 col-sm-6">
													<div class="form-group">
														<label>Attention To</label>
														<input type="text" class="form-control" name="client_attention_to" id="client_attention_to" value="<?php echo ($ID)?$invoice_list['attention_to']:''; ?>" required <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>>
													</div>
												</div>

												<div class="col-12 col-sm-6">
													<div class="form-group">
														<label>PO No</label>
														<input type="text" class="form-control" name="client_po_no" id="client_po_no" value="<?php echo ($ID)?$invoice_list['po_no']:''; ?>" <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>>
													</div>
												</div>
												
												<?php if($entity_id == 3){ ?>
													<div class="col-12 col-sm-6">
														<div class="form-group">
															<label>Branch</label>
															<select class="form-control" name="branch_id" id="branch_id" required <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>>
																<option value="-1" selected disabled>-- Please Select --</option>
																<?php if($branch) foreach($branch as $row){ ?>
																	<option value="<?php echo $row['id']; ?>" <?php echo ($ID)?(($invoice_list['branch_id'] == $row['id'])?'selected':''):''; ?>><?php echo $row['name']; ?></option>
																<?php } ?>
															</select>
														</div>
													</div>

													<div class="col-12 col-sm-6">
														<div class="form-group">
															<label>Signing Parner</label>
															<select class="form-control" name="signing_partner" id="signing_partner" <?php echo ($ID && $invoice_list['approval_status'] > 0)?'disabled':''; ?>>
																<option value="-1" selected disabled>-- Please Select --</option>
																<?php if($partner) foreach($partner as $row){ ?>
																	<option value="<?php echo $row['id'] ?>" <?php echo ($ID)?(($invoice_list['sign_partner_id'] == $row['id'])?'selected':''):''; ?>><?php echo $row['name']; ?></option>
																<?php } ?>
															</select>
														</div>
													</div>
												<?php } ?>
											</div>

											<div class="form-row py-3">
												<div class="col-12">
													<label for="description_list"><h5><strong>Service List</strong></h5></label>
													<br>
													<?php if($description) foreach($description as $row) { if($row['type'] == 0){ ?>
														<br>
														<a class="accordion p-2 bg-light float-right">
															<?php echo $row['description']; ?>
															<span class="badge badge-pill" id="description_<?php echo $row['ID']; ?>"></span>

															<?php //if($ID && $invoice_list['total_description'] >= 1) { ?>
																<!-- <span class="badge badge-pill badge-danger"><?php //echo $invoice_list['total_description']; ?></span> -->
															<?php //} ?>
														</a>

														<div class="col-12 panel">
															<br>
															<?php if($mode != 'view'){ ?>
																<div class="card-header-action d-print-none d-none d-sm-block">
																	<div class="form-row float-right">
																		<button type="button" class="btn btn-sm btn-primary"
																			data-descid="<?php echo $row['ID']; ?>"
																			data-description="<?php echo $row['description']; ?>"
																			onclick="open_modal('new_invoice_detail', this)">
																			Add New <?php echo $row['description']; ?>
																		</button>
																	</div>
																	<br>
																</div>
															<?php } ?>
															<br>
															<div class="table-responsive">
																<table id="table_invoice_detail_<?php echo $row['ID']; ?>" class="table table-hover table-striped ">
																	<thead align="center"> 
																		<tr>
																			<!-- <td>#</td> -->
																			<td>Service Description</td>
																			<td>Year End</td>
																			<td>Amount (RM)</td>
																			<?php if($mode != 'view'){ ?>
																				<td>Action</td>
																			<?php } ?>
																		</tr>
																	</thead>
																	<tbody>
																		<?php if($invoice_list['total_description'] > 0){ 
																			$description_id		= explode('->',$invoice_list['description_id']);
																			$detail_id			= explode('->',$invoice_list['detail_id']);
																			$desc 				= explode('->',$invoice_list['description']);
																			$description_remark = explode('->',$invoice_list['description_remark']);
																			$description_ye 	= explode('->',$invoice_list['description_year_end']);
																			$description_amount = explode('->',$invoice_list['description_amount']);

																			foreach($description_id as $desc_key => $desc_id)
																			{
																				if($desc_id == $row['ID'])
																				{
																					$btn_edit = '<button type="button" class="btn btn-sm btn-warning" title="Edit" data-descid="'.$desc_id.'" data-detailid="'.$detail_id[$desc_key].'" data-description="'.$desc[$desc_key].'" data-remark="'.$description_remark[$desc_key].'" data-amount="'.$description_amount[$desc_key].'" data-yearend="'.$description_ye[$desc_key].'" onclick="open_modal('."'update_invoice_detail'".', this)"><i class="fas fa-edit"></i></button>';
																					$btn_delete = '<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ID="'.$detail_id[$desc_key].'" data-updatedBY="'.$_SESSION['user']['id'].'" data-updatedTS="'.date('Y-m-d H:i:s').'" data-rowid="detail_row_'.$detail_id[$desc_key].'" data-tableid="table_invoice_detail_'.$row['ID'].'" onclick="delete_row('."'delete_invoice_detail'".','."'sv__invoice_description'".',['."'ID'".','."'updatedBY'".','."'updatedTS'".'], this)" ><i class="fas fa-trash"></i></button>';
																					$btn = $btn_edit.' '.$btn_delete;
																						echo '<tr id="detail_row_'.$detail_id[$desc_key].'">';
																							echo '<td>'.$description_remark[$desc_key].'</td>';
																							echo '<td>'.$description_ye[$desc_key].'</td>';
																							echo '<td>'.number_format($description_amount[$desc_key],2).'</td>';
																					if($mode != 'view'){
																							echo '<td class="text-center"><div class="btn-group btn-group-sm" role="group">'.$btn.'</div></td>';
																					}
																						echo '</tr>';
																				}
																			}
																		} ?>
																	</tbody>
																</table>
															</div>
														</div>
													<?php } } ?>
												</div>

												<div class="col-12" style="margin-top: 2rem;">
													<label for="disbursement"><h5><strong>Out of Pocket</strong></h5></label>
													<br>
													<?php if($description) foreach($description as $row) { if($row['type'] == 1){ ?>
														<br>
														<a class="accordion p-2 bg-light float-right">
															<?php echo $row['description']; ?>
															<span class="badge badge-pill" id="description_<?php echo $row['ID']; ?>"></span>
															<?php //if($ID && $invoice_list['total_description'] >= 1) { ?>
																<!-- <span class="badge badge-pill badge-danger"><?php //echo $invoice_list['total_description']; ?></span> -->
															<?php //} ?>
														</a>

														<div class="col-12 panel">
															<br>
															<?php if($mode != 'view'){ ?>
																<div class="card-header-action d-print-none d-none d-sm-block">
																	<div class="form-row float-right">
																		<button type="button" class="btn btn-sm btn-primary"
																			data-descid="<?php echo $row['ID']; ?>"
																			data-description="<?php echo $row['description']; ?>"
																			onclick="open_modal('new_invoice_disbursement', this)">
																			Add New <?php echo $row['description']; ?>
																		</button>
																	</div>
																	<br>
																</div>
															<?php } ?>
															<br>
															<div class="table-responsive">
																<table id="table_invoice_disbursement_<?php echo $row['ID']; ?>" class="table table-hover table-striped ">
																	<thead align="center"> 
																		<tr>
																			<!-- <td>#</td> -->
																			<?php echo ((strtolower($row['description']) == 'others') || (strtolower($row['description']) == 'other'))?'<td>Description</td>':'';?>
																			<td>Amount</td>
																			<?php if($mode != 'view'){ ?>
																				<td>Action</td>
																			<?php } ?>	
																		</tr>
																	</thead>
																	<tbody>
																		<?php if($invoice_list['total_description'] > 0){ 
																			foreach($description_id as $desc_key => $desc_id)
																			{
																				if($desc_id == $row['ID'])
																				{
																					$btn_edit = '<button type="button" class="btn btn-sm btn-warning" title="Edit"  data-descid="'.$desc_id.'" data-detailid="'.$detail_id[$desc_key].'" data-description="'.$desc[$desc_key].'" data-remark="'.$description_remark[$desc_key].'" data-amount="'.$description_amount[$desc_key].'" onclick="open_modal('."'update_invoice_disbursement'".', this)"><i class="fas fa-edit"></i></button>';
																					$btn_delete = '<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ID="'.$detail_id[$desc_key].'" data-updatedBY="'.$_SESSION['user']['id'].'" data-updatedTS="'.date('Y-m-d H:i:s').'" data-rowid="disbursement_row_'.$detail_id[$desc_key].'" data-tableid="table_invoice_disbursement_'.$row['ID'].'" onclick="delete_row('."'delete_invoice_disbursement'".','."'sv__invoice_description'".',['."'ID'".','."'updatedBY'".','."'updatedTS'".'], this)" ><i class="fas fa-trash"></i></button>';
																					$btn = $btn_edit.' '.$btn_delete;
																						echo '<tr id="disbursement_row_'.$detail_id[$desc_key].'">';
																							echo ((strtolower($row['description']) == 'others') || (strtolower($row['description']) == 'other'))?'<td>'.$description_remark[$desc_key].'</td>':'';
																							echo '<td>'.number_format($description_amount[$desc_key],2).'</td>';
																					if($mode != 'view'){	
																							echo '<td class="text-center"><div class="btn-group btn-group-sm" role="group">'.$btn.'</div></td>';
																					}
																						echo '</tr>';
																				}
																			}
																		} ?>
																	</tbody>
																</table>
															</div>
														</div>
													<?php } } ?>
												</div>
											</div>
											
											<div class="form-row py-3">
												<?php
													$sub_total = 0;
													$sst = 0;
													$total = 0;
													$checked = false;

													if($ID && isset($description_amount)) foreach($description_amount as $amount_key => $amount) 
													{
														if(strtolower($desc[$amount_key]) == 'sst')
														{
															$checked += true;
															$sub_total += 0;
														}else
														{
															$checked += false; 
															$sub_total += $amount;
														}
													}

													if($business_entity_detail['is_sst'] == 1) $sst += ($business_entity_detail['tax_amount'] * $sub_total);
													$total += ($checked == true)?($sub_total + $sst):$sub_total;
												?>

												<div class="col-6">
													<label for="sub_total"><strong>Sub Total</strong></label>
												</div>
												<div class="col-6">
													<input type="text" class="form-control" name="sub_total_invoice" id="sub_total_invoice" value="<?php echo  number_format($sub_total,2); ?>" required readonly>
												</div>
												<br><br>
												<div class="col-5">
													<label for="sst"><strong>SST</strong></label>
												</div>
												<div class="col-1">
													<?php if($mode != 'view'){ ?>
														<input type="checkbox" name="sst_checkbox" id="sst_checkbox" <?php echo ($business_entity_detail['is_sst'] == 1)?(($checked == true)?'checked':''):'disabled'; ?> style="width: 18px; height: 18px; margin-left: 69px; margin-top: 9px;" onclick="update_total('sst_checkbox', <?php echo $sub_total; ?>, <?php echo $sst; ?>)">
													<?php }else{ ?>
														<input type="checkbox" name="sst_checkbox" id="sst_checkbox" <?php echo ($business_entity_detail['is_sst'] == 1)?(($checked == true)?'checked disabled':' disabled'):'disabled'; ?> style="width: 18px; height: 18px; margin-left: 69px; margin-top: 9px;" onclick="update_total('sst_checkbox', <?php echo $sub_total; ?>, <?php echo $sst; ?>)">
													<?php } ?>
												</div>
												<div class="col-6">
														<input type="text" class="form-control" name="sst_amount" id="sst_amount" <?php echo (($business_entity_detail['is_sst'] == 1) && ($checked == true))?'value="'.number_format($sst,2).'"':'value="N/A"'; ?> readonly>
												</div>
												<br><br>
												<div class="col-6">
													<label for="total"><strong>Total</strong></label>
												</div>
												<div class="col-6">
													<input type="text" class="form-control" name="total_invoice" id="total_invoice" required value="<?php echo ($ID && $invoice_list['total'] > 0)?number_format($total,2):0.00; ?>" readonly>
												</div>
											</div>

											<div class="form-row">
												<div class="col-12">
													<div class="form-group">
														<h5>
															<b>
																Approved By
																<i class="text-danger" style="font-size: 14.5px;">*Please choose only two(2) manager to approve this invoice.</i>
															</b>
														</h5>
														<hr>
														<div class="form-row">
															<?php if($invoice_list['approval_status'] > 0){ ?>
																<?php if($mode == 'view'){ ?>
																	<?php if($_SESSION['user']['id'] == $invoice_list['createdBY'] || $finance_division){ ?>
																		<div class="col-12 col-sm-6">
																			<div class="form-group">
																				<label>Approver Name</label>
																				<input type="text" class="form-control" name="approver_name" id="approver_name" value="<?php echo $invoice_list['approved_by_name']; ?>" readonly>	
																			</div>
																		</div>

																		<div class="col-12 col-sm-6">
																			<div class="form-group">
																				<label>Approval Date</label>
																				<input type="text" class="form-control" name="approver_date" id="approver_date" value="<?php echo date("d-m-Y h:iA",strtotime($invoice_list['approvedTS'])); ?>" readonly>	
																			</div>
																		</div>

																		<div class="col-12 col-sm-6">
																			<div class="form-group">
																				<label>Approval Status</label>
																				<input type="text" class="form-control" name="approver_status" id="approver_status" value="<?php echo ($invoice_list['approval_status'] == 1)?'Approved':'Rejected'; ?>" readonly>	
																			</div>
																		</div>

																		<div class="col-12 col-sm-6">
																			<div class="form-group">
																				<label>Approval Remark</label>
																				<input type="text" class="form-control" name="approver_remark" id="approver_remark" value="<?php echo $invoice_list['approval_remark']; ?>" readonly>	
																			</div>
																		</div>
																	<?php } else { ?>
																		<div class="col-12">
																			<div class="form-group">
																				<label>Name</label>
																				<select class="form-control selectpicker" name="mgr_approval[]" id="mgr_approval" required multiple onchange="check_total_selected('mgr_approval')" <?php echo ($mode != 'view')?'':'disabled'; ?>>
																					<option value="-1" disabled>-- Please Select --</option>
																					<?php if($approver) foreach($approver as $appr){ ?>
																						<option value="<?php echo $appr['id']; ?>"><?php echo $appr['name']; ?></option>
																					<?php } ?>
																				</select>
																			</div>
																		</div>
																	<?php } ?>
																<?php } ?>
															<?php } else { ?>
																<div class="col-12">
																	<div class="form-group">
																		<label>Name</label>
																		<select class="form-control selectpicker" name="mgr_approval[]" id="mgr_approval" required multiple onchange="check_total_selected('mgr_approval')" <?php echo ($mode != 'view')?'':'disabled'; ?>>
																			<option value="-1" disabled>-- Please Select --</option>
																			<?php if($approver) foreach($approver as $appr){ ?>
																				<option value="<?php echo $appr['id']; ?>"><?php echo $appr['name']; ?></option>
																			<?php } ?>
																		</select>
																	</div>
																</div>
															<?php } ?>														
														</div>
													</div>
												</div>
											</div>

											<div class="form-row">
												<div class="col-12">
													<div class="form-group">
														<h5><b>Prepared By</b></h5>
														<hr>
														<div class="form-row">
															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label>Name</label>
																	<input type="text" class="form-control" name="request_name" id="request_name" value="<?php echo ($ID)?$invoice_list['requester_name']:$_SESSION['user']['name']; ?>" readonly>	
																	<input type="text" class="form-control" name="request_name_id" id="request_name_id" value="<?php echo ($ID)?$invoice_list['requester_id']:$_SESSION['user']['id']; ?>" hidden>
																</div>
															</div>

															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label for="email">Email Address</label>
																	<input type="text" class="form-control" name="request_email" id="request_email" value="<?php echo ($ID)?$invoice_list['requester_email']:$_SESSION['user']['email']; ?>" readonly>
																</div>
															</div>

															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label for="department">Department</label>
																	<input type="text" class="form-control" name="request_dept" id="request_dept" value="<?php echo ($ID)?$invoice_list['dept_name'].' ['.$invoice_list['branchName'].']':$_SESSION['user']['department_name'].' ['.$_SESSION['user']['branch_name'].']'; ?>" readonly>	
																	<input type="text" class="form-control" name="request_dept_id" id="request_dept_id" value="<?php echo ($ID)?$invoice_list['department_id']:$_SESSION['user']['department_id']; ?>" hidden>
																</div>
															</div>

															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label for="datereq">Date Request</label>
																	<input type="text" class="form-control" name="datereq" id="datereq" value="<?php echo ($ID)?date("d-m-Y",strtotime($invoice_list['createdTS'])):date("d-m-Y"); ?>" readonly>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>

											<div class="form-row">
												<div class="col-12">
													<p>
														Kindly Take Note of the followings:-<br>
														i)	Kindly indicate in detail job undertake<br>
														ii)	Kindly ensure amount is in accordance to proposal or quotation issued.<br>
														iii)	Check for major variation from previous invoice(s) issued<br>
														iv)	This form is to be approved by Manager above<br>
													</p> 
												</div>
											</div>

											<div class="form-row" <?php echo (isset($mode) && ($mode == 'view'))?'style="display: none;"':''; ?>>
												<div class="col-12" style="padding-top: 2rem;">
													<div class="float-left <?php echo ($ID)?'d-none':''; ?>">
														<table>
															<tbody>
																<tr>
																	<td class="text-center">
																		<label class="switch" data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Send me a copy of this form">
																			<input type="checkbox" name="send_email_checkbox">
																			<span class="slider round"></span>
																		</label>
																	</td>
																	<td class="p-3 py-1"><b><h6 style="">Send me a copy of this form</h6></b></td>
																</tr>
															</tbody>
														</table>
													</div> 
													<div class="float-right">
														<a class="btn btn-light" href="<?php echo base_url('hr/serviceform/invoice_list/'); ?>">Cancel</a>
														<button type="submit" id="submitBtn" class="btn btn-primary"><?php echo 'submit';//($ID)?'Update':'Submit'; ?></button>
													</div> 
												</div>
											</div>
										</form>
									</form>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</section>

<!-- manager approval -->
<?php if($dept_manager){ ?>
	<section class="container" style="padding-bottom: 2rem;">
		<div class="row">
			<div class="col-sm-12">
				<div class="tab-content" id="tabContent">
					<div class="tab-pane fade show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
						<div class="card bg-light-transparent">
							<div class="card-header bg-light">
								<h4 class="card-title">Approved By</h4>
							</div>
							<div class="card-body">
								<div class="card no-shadow">
									<div class="card-body">
										<form id="invoiceApprovedForm" class="form" action="<?php echo base_url('hr/Serviceform/invoice_approved/manager') ?>" method="POST">
											<input type="text" class="form-control" name="invoiceID" id="invoiceID" value="<?php echo $ID; ?>" hidden>
											<div class="form-row py-3">
												<div class="col-12">
													<div class="form-group">
														<div class="form-row">
															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label>Name</label>
																	<input type="text" class="form-control" name="approve_name" id="approve_name" value="<?php echo ($ID)?(($invoice_list['approval_status'] > 0)?$invoice_list['approved_by_name']:$_SESSION['user']['name']):''; ?>" readonly>	
																	<input type="text" class="form-control" name="approve_name_id" id="approve_name_id" value="<?php echo ($ID)?(($invoice_list['approval_status'] > 0)?$invoice_list['approved_by_staff_id']:$_SESSION['user']['id']):''; ?>" hidden>
																</div>
															</div>

															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label for="email">Email Address</label>
																	<input type="text" class="form-control" name="approve_email" id="approve_email" value="<?php echo ($ID)?(($invoice_list['approval_status'] > 0)?$invoice_list['approved_by_email']:$_SESSION['user']['email']):''; ?>" readonly>
																</div>
															</div>

															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label for="dateapprv">Date Approve</label>
																	<input type="text" class="form-control" name="dateapprv" id="dateapprv" value="<?php echo ($ID)?(($invoice_list['approval_status'] > 0)?date("d-m-Y h:iA",strtotime($invoice_list['approvedTS'])):date("d-m-Y h:iA")):''; ?>" readonly>
																</div>
															</div>

															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label for="approval_remark">Remark</label>
																	<input type="text" class="form-control" name="approval_remark" id="approval_remark" value="<?php echo ($ID)?(($invoice_list['approval_status'] > 0)?$invoice_list['approval_remark']:''):''; ?>" <?php echo ($invoice_list['prepared_status'] > 0)?'readonly':''; ?>>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
											<div class="col-12" <?php echo ($ID && $invoice_list['prepared_status'] > 0)?'style="display: none;"':''; ?>>
												<div class="float-right">
													<button type="submit" class="btn btn-danger" name="approveBtn" id="rejectBtn" value="2" onclick="">Reject</button>
													<button type="submit" class="btn btn-success" name="approveBtn" id="approveBtn" value="1" onclick="">Approved</button>
												</div> 
											</div>
										</form>									
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</section>
<?php } ?>

<!-- for finance use -->
<?php if($ID && $invoice_list['approval_status'] > 0 && $invoice_list['approval_status'] == 1 && $finance_division){ ?>
	<section class="container" style="padding-bottom: 2rem;">
		<div class="row">
			<div class="col-sm-12">
				<div class="tab-content" id="tabContent">
					<div class="tab-pane fade show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
						<div class="card bg-light-transparent">
							<div class="card-header bg-light">
								<h4 class="card-title">For Finance Division Use Only</h4>
							</div>
							<div class="card-body">
								<div class="card no-shadow">
									<div class="card-body">
										<form id="invoiceApprovedForm" class="form" action="<?php echo base_url('hr/Serviceform/invoice_approved/finance') ?>" method="POST">
											<input type="text" class="form-control" name="invoiceID" id="invoiceID" value="<?php echo $ID; ?>" hidden>
											<div class="form-row py-3">
												<div class="col-12">
													<div class="form-group">
														<div class="form-row">
															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label>Name</label>
																	<input type="text" class="form-control" name="finance_name" id="finance_name" value="<?php echo ($ID)?(($invoice_list['prepared_status'] > 0)?$invoice_list['prepared_by_name']:$_SESSION['user']['name']):''; ?>" readonly>	
																	<input type="text" class="form-control" name="finance_name_id" id="finance_name_id" value="<?php echo ($ID)?(($invoice_list['prepared_status'] > 0)?$invoice_list['prepared_by_staff_id']:$_SESSION['user']['id']):''; ?>" hidden>
																</div>
															</div>

															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label for="email">Email Address</label>
																	<input type="text" class="form-control" name="finance_email" id="finance_email" value="<?php echo ($ID)?(($invoice_list['prepared_status'] > 0)?$invoice_list['prepared_by_email']:$_SESSION['user']['email']):''; ?>" readonly>
																</div>
															</div>

															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label for="finance_date">Date Issued</label>
																	<input type="text" class="form-control" name="finance_date" id="finance_date" value="<?php echo ($ID)?(($invoice_list['prepared_status'] > 0)?date("d-m-Y h:iA",strtotime($invoice_list['preparedTS'])):date("d-m-Y h:iA")):''; ?>" readonly>
																</div>
															</div>

															<div class="col-12 col-sm-6">
																<div class="form-group">
																	<label for="finance_inv_no">Invoice No</label>
																	<input type="text" class="form-control" name="finance_inv_no" id="finance_inv_no" value="<?php echo ($ID)?(($invoice_list['prepared_status'] > 0)?$invoice_list['inv_form_no']:''):''; ?>" required>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
											<div class="col-12">
												<div class="float-right">
													<button type="submit" class="btn btn-danger" name="financeCompleteBtn" id="financeDuplicateBtn" value="2">Duplicate</button>
													<button type="submit" class="btn btn-success" name="financeCompleteBtn" id="financeCompleteBtn" value="1">Complete</button>
												</div> 
											</div>
										</form>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</section>
<?php } ?>

<!-- add client info modal -->
<div class="modal fade" id="modal_add_client_info" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="modal_add_client_info_title"></h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>

			<div class="modal-body">
				<div id="modal_add_client_info_content"></div>
				
				<!-- <div class="row p-3">
					<div class="col-12">
						<label>Name</label>
						<input type="text" class="form-control" id="rep_name" name="rep_name" required>
					</div>
				</div>

				<div class="row p-3">
					<div class="col-12">
						<label>Phone</label>
						<input type="text" class="form-control" id="phone_mobile" name="phone_mobile" required>
					</div>
				</div> -->

				<div class="float-right">
					<button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
					<button type="button" id="saveClientInfoBtn" class="btn btn-primary">Save</button>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
	$(document).ready(function()
	{
		var acc = document.getElementsByClassName("accordion");
		var i;

		for (i = 0; i < acc.length; i++) {
			acc[i].addEventListener("click", function() {
			this.classList.toggle("active1");
			var panel = this.nextElementSibling;
			if (panel.style.maxHeight) {
				panel.style.maxHeight = null;
			} else {
				panel.style.maxHeight = panel.scrollHeight + "px";
			} 
			});
		}
	
		var client_id = $('#client_id').val();
		if(client_id > 0)
		{
			$('#addClientPhone').removeAttr('disabled');
			$('#addClientPhone').css('cursor','pointer');
			$('#addClientFax').removeAttr('disabled');
			$('#addClientFax').css('cursor','pointer');
			$('#addClientAddress').removeAttr('disabled');
			$('#addClientAddress').css('cursor','pointer');
			$('#addClientEmail').removeAttr('disabled');
			$('#addClientEmail').css('cursor','pointer');
		}else{
			$('#addClientPhone').attr('disabled','disabled');
			$('#addClientPhone').css('cursor','not-allowed');
			$('#addClientFax').attr('disabled','disabled');
			$('#addClientFax').css('cursor','not-allowed');
			$('#addClientAddress').attr('disabled','disabled');
			$('#addClientAddress').css('cursor','not-allowed');
			$('#addClientEmail').attr('disabled','disabled');
			$('#addClientEmail').css('cursor','not-allowed');
		}

		var job_id = '<?php echo ($ID)?$invoice_list['job_id']:''; ?>';
		
		change_client_input(job_id);
		count_description('<?php echo (isset($count_description))?json_encode($count_description):''; ?>');
		change_manager_input('<?php echo (isset($invoice_list['manager_id']))?($invoice_list['manager_id']):''; ?>');
	});

	function change_client_input(jobID = null)
	{
		if(jobID > 0)	var job_id	= jobID;
		else	var job_id	= $('#job_id').val();

		var group_id 	= '';
		var tel_no 		= '';
		var fax_no 		= '';
		var email 		= '';
		var address 	= '';

		if(job_id > 0)
		{
			// $('#client_id').select2();
			$('#client_id').val('-1');
			$('#job_id').select2();
			$('#job_id').val(job_id);
			$('#job_id').select2({
				placeholder: "-- Please Select --",
				theme: 'bootstrap4',
			});

			$('#client_tel_no').html('');
			$('#client_tel_no').append('<option value="-1" selected disabled>-- Please Select --</option>');
			$('#client_id').select2();
			$('#client_id').select2('destroy');

			$.ajax({
				url:'<?php echo base_url('hr/serviceform/invoice_get_client_detail') ?>',
				data: {
					job_id 		: job_id,
				},
				type: 'post',
				dataType: 'json',
				success: (data) => {
					if(data.status == "success") {
						var job_detail 			= data.job_detail;
						var client_detail 		= data.client_detail;
						var client_contact_no 	= data.client_contact_no;
						var client_address 		= data.client_address;
						var address_temp		= ''; 

						$.each(client_contact_no, function(key,content){
							if(content.phone != '' && content.phone != null)
							{
								if('<?php echo $ID; ?>' > 0)
								{
									if('<?php echo $invoice_list['client_contact']; ?>' == content.phone)
									{
										var selected = 'selected';
									}else{
										var selected = '';
									}
								}
								var tel_temp = '<option value="'+content.phone+'" '+selected+'>'+content.rep_name+' - '+content.phone+'</option>';
								$('#client_tel_no').append(tel_temp);
							}
						});

						if(client_detail.groupName != '' && client_detail.groupName != null) group_id = client_detail.groupName;
						if(client_detail.fax != '' && client_detail.fax != null) fax_no = client_detail.fax;
						if(client_detail.email != '' && client_detail.email != null) email = client_detail.email;
						if(client_detail.address1 != '' && client_detail.address1 != null) address = client_detail.address1+' '+client_detail.address2;

						$('#client_group_id').val(group_id);

						if(('<?php echo $ID; ?>' != '' && '<?php echo $ID; ?>' != null) && (job_detail[0]['customerID'] == '<?php echo $invoice_list['client_id']; ?>'))
						{
							$('#client_fax_no').val('<?php echo ($invoice_list['client_fax'])?$invoice_list['client_fax']:''; ?>');
							// $('#client_address').val(`<?php //echo ($invoice_list['client_address'])?$invoice_list['client_address']:''; ?>`);
						}else{
							$('#client_fax_no').val(fax_no);
							$('#client_email').val(email);
							// $('#client_address').val(address);
						}

						$.each(client_address, function(key,content){
							if(content.address != '' && content.address != null)
							{
								address_temp += '<option></option>';
								if('<?php echo $ID; ?>' > 0)
								{
									if('<?php echo str_replace(array("\n", "\r"), '', $invoice_list['client_address']); ?>' == content.address)
									{
										var selected = 'selected';
									}else{
										var selected = '';
									}
								}
								address_temp += '<option value="'+content.address+'" '+selected+'>'+content.address+'</option>';
							}
						});
						
						$('#client_address').append(address_temp);

						$('#addClientPhone').removeAttr('disabled');
						$('#addClientPhone').css('cursor','pointer');
						$('#addClientFax').removeAttr('disabled');
						$('#addClientFax').css('cursor','pointer');
						$('#addClientAddress').removeAttr('disabled');
						$('#addClientAddress').css('cursor','pointer');
						$('#addClientEmail').removeAttr('disabled');
						$('#addClientEmail').css('cursor','pointer');

						$('#client_id').val(job_detail[0]['customerID']);
						$('#client_id').css('pointer-events','none');
						$('#client_id').attr('readonly','readonly');
						$('#client_id').removeAttr('disabled');

           				change_email_input(job_detail[0]['customerID'],'<?php echo ($ID)?$invoice_list['client_contact']:''; ?>');
						// $('#client_id').select2({
						// placeholder: "-- Please Select --", 	
						// theme: 'bootstrap4',
						// });

						$('#client_address').select2({
							placeholder: "-- Please Select --",
							theme: 'bootstrap4',
						});
					}else{
						$('#client_id').css('pointer-events','none');
						$('#client_id').attr('readonly','readonly');
						$('#client_id').removeAttr('disabled');

						$('#addClientPhone').attr('disabled','disabled');
						$('#addClientPhone').css('cursor','not-allowed');
						$('#addClientFax').attr('disabled','disabled');
						$('#addClientFax').css('cursor','not-allowed');
						$('#addClientAddress').attr('disabled','disabled');
						$('#addClientAddress').css('cursor','not-allowed');
						$('#addClientEmail').attr('disabled','disabled');
						$('#addClientEmail').css('cursor','not-allowed');

						$('#client_fax_no').val(fax_no);
						$('#client_email').val(email);
						// $('#client_address').val(address);

						iziToast.warning({
		                    position: 'bottomRight',
		                    message: 'No Client Detail Found. Please Try Again. Thank You.',
		                    timeout: '3000',
		                });
					}
              	}
           	});
		}else{
			$('#addClientPhone').attr('disabled','disabled');
			$('#addClientPhone').css('cursor','not-allowed');
			$('#addClientFax').attr('disabled','disabled');
			$('#addClientFax').css('cursor','not-allowed');
			$('#addClientAddress').attr('disabled','disabled');
			$('#addClientAddress').css('cursor','not-allowed');
			$('#addClientEmail').attr('disabled','disabled');
			$('#addClientEmail').css('cursor','not-allowed');

			$('#client_tel_no').html('');
			$('#client_tel_no').append('<option value="-1" selected disabled>-- Please Select --</option>');
			$('#client_group_id').val(group_id);
			$('#client_fax_no').val(fax_no);
			$('#client_email').val(email);
			$('#client_address').val(address);
			$('#client_attention_to').val('');
			$('#client_po_no').val('');

			// $('#client_id').val('-1');
			$('#client_id').css('pointer-events','none');
			$('#client_id').attr('disabled','disabled');
			$('#client_id').removeAttr('readonly');
			
			$('#client_id').select2({
				placeholder: "-- Please Select --",
				theme: 'bootstrap4',
			});

			$('#job_id').select2({
				placeholder: "-- Please Select --",
				theme: 'bootstrap4',
			});
		}
	}

	function open_modal(mode, elem)
	{
		var client_id 		 = $('#client_id').val();
		var modal_content 	 = '';
		var modal_title		 = '';
		var input_id		 = [];
		var modal_title_id	 = ''
		var modal_content_id = ''

		$('#modal_add_client_info_title').html('');
		$('#modal_add_client_info_content').html('');
		$('#saveClientInfoBtn').removeAttr('onclick');

		if(client_id > 0)
		{
			if(mode == 'client_phone')
			{
				modal_title = 'Add Client Telephone Number';
				modal_content = 
				'<input type="text" class="form-control" name="client_ID" id="client_ID" hidden>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Name</label>\
						<input type="text" class="form-control" id="rep_name" name="rep_name" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Phone</label>\
						<input type="text" class="form-control" id="phone_mobile" name="phone_mobile" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Fax No</label>\
						<input type="text" class="form-control" id="fax_num" name="fax_num" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Email</label>\
						<input type="text" class="form-control" id="email_address" name="email_address" required>\
					</div>\
				</div>';
				
				modal_title_id		= 'modal_add_client_info_title';
				modal_content_id	= 'modal_add_client_info_content';
				$('#saveClientInfoBtn').attr('onclick','save_client_phone()');
			}else if(mode == 'client_address')
			{
				modal_title = 'Add Client Address';
				modal_content = 
				'<input type="text" class="form-control" id="created_by" name="created_by" value="'+<?php echo $_SESSION['user']['id']; ?>+'" required hidden>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Address 1</label>\
						<input type="text" class="form-control" id="address1" name="address1" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Address 2</label>\
						<input type="text" class="form-control" id="address2" name="address2" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Postcode</label>\
						<input type="text" class="form-control" id="postcode" name="postcode" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>City</label>\
						<input type="text" class="form-control" id="city" name="city" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Country</label>\
						<select class="form-control" id="country_id" name="country_id" required onchange="change_input_state()">\
							<option></option>\
								<?php if($country) foreach($country as $ctr){ ?>\
									<option value="<?php echo $ctr->id; ?>" <?php echo ($ctr->id == 458)?'selected':''; ?>><?php echo $ctr->country; ?></option>\
								<?php } ?>\
						</select>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>State</label>\
						<select class="form-control" id="state_id" name="state_id" required>\
							<option></option>\
						</select>\
					</div>\
				</div>';

				input_id.push('country_id','state_id');

				modal_title_id		= 'modal_add_client_info_title';
				modal_content_id	= 'modal_add_client_info_content';
				$('#saveClientInfoBtn').attr('onclick','save_client_info('+"'client_address',"+"'client_address',"+"['created_by','client_id','address1','address2','postcode','city','country_id','state_id'],"+"'customer__other_address'"+')');
			}else if(mode == 'new_invoice_detail')
			{
				modal_title = 'Add '+$(elem).data('description');
				modal_content = 
				// <label>Description</label>\
				'<div class="row pb-3">\
					<div class="col-12">\
						<input type="text" class="form-control" id="description" name="description" value="'+$(elem).data('description')+'" required readonly>\
						<input type="text" class="form-control" id="description_id" name="description_id" value="'+$(elem).data('descid')+'" required hidden>\
						<input type="text" class="form-control" id="createdBY" name="createdBY" value="'+<?php echo $_SESSION['user']['id']; ?>+'" required hidden>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Service Description</label>\
						<input type="text" class="form-control" id="remark" name="remark" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Year End</label>\
						<input type="text" class="form-control datepicker-yyyy" id="year_end" name="year_end" value="'+<?php echo date('Y'); ?>+'" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Amount</label>\
						<input type="text" class="form-control" id="amount" name="amount" required>\
					</div>\
				</div>';
				
				modal_title_id		= 'modal_add_client_info_title';
				modal_content_id	= 'modal_add_client_info_content';
				$('#saveClientInfoBtn').attr('onclick','save_client_info('+"'new_invoice_detail',"+"'table_invoice_detail_"+$(elem).data('descid')+"',"+"['createdBY','invoiceID','description_id','remark','year_end','amount'],"+"'sv__invoice_description'"+')');
			}else if(mode == 'new_invoice_disbursement')
			{
				modal_title = 'Add '+$(elem).data('description');
				if((($(elem).data('description')).toLowerCase() == 'others') || (($(elem).data('description')).toLowerCase() == 'other'))
				{
					var required 	= 'required';
					var hidden 		= '';
				}else{
					var required 	= '';
					var hidden 		= 'd-none';
				}
				modal_content = 
				// <label>Description</label>\
				'<div class="row pb-3">\
					<div class="col-12">\
						<input type="text" class="form-control" id="description" name="description" value="'+$(elem).data('description')+'" required readonly>\
						<input type="text" class="form-control" id="description_id" name="description_id" value="'+$(elem).data('descid')+'" required hidden>\
						<input type="text" class="form-control" id="createdBY" name="createdBY" value="'+<?php echo $_SESSION['user']['id']; ?>+'" required hidden>\
					</div>\
				</div>\
				<div class="row pb-3 '+hidden+'">\
					<div class="col-12">\
						<label>Description</label>\
						<input type="text" class="form-control" id="remark" name="remark" '+required+'>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Amount</label>\
						<input type="text" class="form-control" id="amount" name="amount" required>\
					</div>\
				</div>';
				
				modal_title_id		= 'modal_add_client_info_title';
				modal_content_id	= 'modal_add_client_info_content';
				$('#saveClientInfoBtn').attr('onclick','save_client_info('+"'new_invoice_disbursement',"+"'table_invoice_disbursement_"+$(elem).data('descid')+"',"+"['createdBY','invoiceID','description_id','remark','amount'],"+"'sv__invoice_description'"+')');
			}else if(mode == 'update_invoice_detail')
			{
				modal_title = 'Add '+$(elem).data('description');
				modal_content = 
				// <label>Description</label>\
				'<div class="row pb-3">\
					<div class="col-12">\
						<input type="text" class="form-control" id="description" name="description" value="'+$(elem).data('description')+'" required readonly>\
						<input type="text" class="form-control" id="description_id" name="description_id" value="'+$(elem).data('descid')+'" required hidden>\
						<input type="text" class="form-control" id="ID" name="ID" value="'+$(elem).data('detailid')+'" required hidden>\
						<input type="text" class="form-control" id="updatedBY" name="updatedBY" value="'+<?php echo $_SESSION['user']['id']; ?>+'" required hidden>\
						<input type="text" class="form-control" id="updatedTS" name="updatedTS" value="'+moment().format('YYYY-MM-DD HH:mm:ss')+'" required hidden>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Service Description</label>\
						<input type="text" class="form-control" id="remark" name="remark" value="'+$(elem).data('remark')+'" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Year End</label>\
						<input type="text" class="form-control datepicker-yyyy" id="year_end" name="year_end" value="'+$(elem).data('yearend')+'" required>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Amount</label>\
						<input type="text" class="form-control" id="amount" name="amount" value="'+$(elem).data('amount')+'" required>\
					</div>\
				</div>';
				
				modal_title_id		= 'modal_add_client_info_title';
				modal_content_id	= 'modal_add_client_info_content';
				$('#saveClientInfoBtn').attr('onclick','update_client_info('+"'update_invoice_detail',"+"'table_invoice_detail_"+$(elem).data('descid')+"',"+"'detail_row_"+$(elem).data('detailid')+"',"+"['updatedBY','updatedTS','ID','description_id','remark','year_end','amount'],"+"'sv__invoice_description'"+')');
			}else if(mode == 'update_invoice_disbursement')
			{
				modal_title = 'Add '+$(elem).data('description');
				if((($(elem).data('description')).toLowerCase() == 'others') || (($(elem).data('description')).toLowerCase() == 'other'))
				{
					var required 	= 'required';
					var hidden 		= '';
				}else{
					var required 	= '';
					var hidden 		= 'd-none';
				}
				modal_content = 
				// <label>Description</label>\
				'<div class="row pb-3">\
					<div class="col-12">\
						<input type="text" class="form-control" id="description" name="description" value="'+$(elem).data('description')+'" required readonly>\
						<input type="text" class="form-control" id="description_id" name="description_id" value="'+$(elem).data('descid')+'" required hidden>\
						<input type="text" class="form-control" id="ID" name="ID" value="'+$(elem).data('detailid')+'" required hidden>\
						<input type="text" class="form-control" id="updatedBY" name="updatedBY" value="'+<?php echo $_SESSION['user']['id']; ?>+'" required hidden>\
						<input type="text" class="form-control" id="updatedTS" name="updatedTS" value="'+moment().format('YYYY-MM-DD HH:mm:ss')+'" required hidden>\
					</div>\
				</div>\
				<div class="row pb-3 '+hidden+'">\
					<div class="col-12">\
						<label>Description</label>\
						<input type="text" class="form-control" id="remark" name="remark" value="'+$(elem).data('remark')+'" '+required+'>\
					</div>\
				</div>\
				<div class="row pb-3">\
					<div class="col-12">\
						<label>Amount</label>\
						<input type="text" class="form-control" id="amount" name="amount" value="'+$(elem).data('amount')+'" required>\
					</div>\
				</div>';
				
				modal_title_id		= 'modal_add_client_info_title';
				modal_content_id	= 'modal_add_client_info_content';
				$('#saveClientInfoBtn').attr('onclick','update_client_info('+"'update_invoice_disbursement',"+"'table_invoice_disbursement_"+$(elem).data('descid')+"',"+"'disbursement_row_"+$(elem).data('detailid')+"',"+"['updatedBY','updatedTS','ID','description_id','remark','amount'],"+"'sv__invoice_description'"+')');
			}

			$('#'+modal_title_id).append(modal_title);
			$('#'+modal_content_id).append(modal_content);
			$('#client_ID').val(client_id);
			$('#modal_add_client_info').modal('show');

			$('.datepicker-yyyy').datepicker({
				format: 'yyyy',
				minViewMode:2
			});

			if(input_id.length > 0)
			{
				change_input_state();
				$.each(input_id, function(key,content){
					$('#'+content).select2({
						placeholder: "-- Please Select --",
						theme: 'bootstrap4',
					});
				});
			}
		}
	}

	function change_email_input(clientID = null, client_contact = null)
	{
		if(client_contact != '' && client_contact != null && client_contact != undefined)
		{
			var contact = client_contact;
		}else{
			var contact = $('#client_email').val();
		}

		if(client_contact != '' && client_contact != null && client_contact != undefined)
		{
			var client_id = clientID;
		}else{
			var client_id = $('#client_id').val();
		}

		$.ajax({
			url:'<?php echo base_url('hr/serviceform/invoice_get_client_detail') ?>',
			data: {
				client_id 		: client_id,
				client_contact 	: client_contact,
			},
			type: 'post',
			dataType: 'json',
			success: (data) => {
				if(data.status == "success") {
					var client_contact_no 	= data.client_contact_no;
					var client_tel_no 		= $('#client_tel_no').val();

					$.each(client_contact_no, function(key,content){
						if(content.phone != '' && content.phone != null)
						{
							if(client_tel_no == content.phone)
							{
								$('#client_fax_no').val(content.fax);
								$('#client_email').val(content.email);
							}

						}
					});
				}
          	}
       	});
	}

	function change_input_state()
	{
		var country_id = $('#country_id').val();
		var state = JSON.parse('<?php echo json_encode($state); ?>');
		var temp_state = '';
		$('#state_id').html('');

		if(country_id > 0)
		{
			temp_state += '<option></option>';

			$.each(state,function(key, content){
				if(content.country_id == country_id)
				{
					temp_state += '<option value="'+content.id+'">'+content.state+'</option>';

				}
			});

			$('#state_id').append(temp_state);
			$('#state_id').trigger('change')
		}
	}

	function save_client_phone()
	{
		$('#modal_add_client_info').modal('hide');

		var client_id 		= $('#client_ID').val();
		var rep_name 		= $('#rep_name').val();
		var phone_mobile 	= $('#phone_mobile').val();
		var fax 			= $('#fax_num').val();
		var email			= $('#email_address').val();

		$.ajax({
			url:'<?php echo base_url('hr/serviceform/invoice_save_client_phone') ?>',
			data: {
				client_id 		: client_id,
				rep_name 		: rep_name,
				phone_mobile 	: phone_mobile,
				fax 			: fax,
				email 			: email,
			},
			type: 'post',
			dataType: 'json',
			success: (data) => {
				if(data.status == "success") {
					iziToast.success({
	                    position: 'bottomRight',
	                    message: data.msg,
	                });

	                $('#client_tel_no').html('');
	                $('#client_fax_no').html('');
	                $('#client_email').html('');

					$('#client_tel_no').append('<option value="-1" selected disabled>-- Please Select --</option>');
					var client_contact_no 	= data.client_contact_no;

					$.each(client_contact_no, function(key,content){
						if(content.phone != '' && content.phone != null)
						{
							if(content.phone == phone_mobile)
							{
								var selected = 'selected';
							}else{
								var selected = '';
							}
							var tel_temp = '<option value="'+content.phone+'" '+selected+'>'+content.rep_name+' - '+content.phone+'</option>';
							$('#client_tel_no').append(tel_temp);
						}
					});

					$('#client_fax_no').val(fax);
					$('#client_email').val(email);
				}else{
					iziToast.warning({
	                    position: 'bottomRight',
	                    message: data.msg
	                });

	                $('#client_tel_no').html('');
					$('#client_tel_no').append('<option value="-1" selected disabled>-- Please Select --</option>');
					var client_contact_no 	= data.client_contact_no;

					$.each(client_contact_no, function(key,content){
						if(content.phone != '' && content.phone != null)
						{
							var tel_temp = '<option value="'+content.phone+'">'+content.rep_name+' - '+content.phone+'</option>';
							$('#client_tel_no').append(tel_temp);
						}
					});
				}
          	}
       	});
	}

	function update_total(mode, existing_value, new_value)
	{
		if('<?php echo $business_entity_detail['is_sst'] ?>' == true) 
		{
			var sst_amount = '<?php echo $business_entity_detail['tax_amount']; ?>';
		}else{
			var sst_amount = 0;
		}

		var total = 0;
		var existing_total = ($('#sub_total_invoice').val()).replace(",", "");

		if(mode == 'sst_checkbox') // applicable when entity is_sst = 1, unchecked sst checkbox
		{
			new_value = ($('#sub_total_invoice').val()).replace(",", "");
			total += (parseFloat(new_value));
		}else{
			total += (parseFloat(new_value) + parseFloat(existing_total - existing_value));
		}

		if(total > 0)
		{
			var sst = total * sst_amount; 
		}else{
			var sst = 0.00;
		}

		if($('#sst_checkbox').is(':checked') == true)
		{
			$('#sub_total_invoice').val(parseFloat(total).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
			$('#sst_amount').val(parseFloat(sst).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
			$('#total_invoice').val(parseFloat(total + sst).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
		}else{
			$('#sub_total_invoice').val(parseFloat(total).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
			$('#sst_amount').val("N/A");
			$('#total_invoice').val(parseFloat(total).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
		}
	}

	function save_client_info(mode, input_id, modal_input_id, table_name)
	{
		var input_key		= {};
		var input_value		= [];
		var existing_value	= $('#'+input_id).val();
		var flag = true;

		$.each(modal_input_id, function(key, row){
			if(row == 'amount')
			{
				if(parseFloat($('#'+row).val()))
				{
					flag = true;
				}else{
					flag = false;
				}
			}

			if(row == 'client_id')
			{
				input_key["customer_id"] = $('#'+row).val();
			}else if(row == 'invoiceID')
			{
				input_key["invoice_id"] = $('#'+row).val();
			}else{
				input_key[row] = $('#'+row).val();
			}
		});

		input_value.push(input_key);

		if(flag == true)
		{
			$.ajax({
				url:'<?php echo base_url('hr/serviceform/invoice_save_client_info/'.$entity_id.'/'.$ID) ?>',
				data: {
					mode 		: mode,
					table_name	: table_name,
					input_value : input_value[0],
				},
				type: 'post',
				dataType: 'json',
				success: (data) => {
					if(data.status == "success") {
						$('#modal_add_client_info').modal('hide');
						
						iziToast.success({
		                    position: 'bottomRight',
		                    message: data.msg,
		                });

			            if(mode == 'new_invoice_detail')
		            	{
		            		var btn_edit 	= '<button type="button" class="btn btn-sm btn-warning" title="Edit" data-descid="'+input_value[0]['description_id']+'" data-detailid="'+data['data']+'" data-description="'+($('#description').val())+'" data-remark="'+input_value[0]['remark']+'" data-yearend="'+input_value[0]['year_end']+'" data-amount="'+input_value[0]['amount']+'" onclick="open_modal('+"'update_invoice_detail'"+', this)"><i class="fas fa-edit"></i></button>';
		            		var btn_delete 	= '<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ID="'+data['data']+'" data-updatedBY="'+<?php echo $_SESSION['user']['id']; ?>+'" data-updatedTS="'+moment().format('YYYY-MM-DD HH:mm:ss')+'" data-rowid="detail_row_'+data['data']+'" data-tableid="table_invoice_detail_'+input_value[0]['description_id']+'" onclick="delete_row('+"'delete_invoice_detail'"+','+"'sv__invoice_description'"+',['+"'ID'"+','+"'updatedBY'"+','+"'updatedTS'"+'], this)"><i class="fas fa-trash"></i></button>';

		            		var btn = btn_edit+btn_delete;
		            		var table = $('#'+input_id).DataTable();
					        // table.clear().draw();
		            		
		            		table.row.add({
	                            0   : input_value[0]['remark'],
	                            1   : input_value[0]['year_end'],
	                            2   : parseFloat(input_value[0]['amount']).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"),
	                            3   : '<div class="text-center"><div class="btn-group btn-group-sm" role="group">'+btn+'</div></div>',
	                        }).node().id = 'detail_row_'+data['data'];
	                        table.draw();

							count_description(data.result2);
		            	}else if(mode == 'new_invoice_disbursement')
		            	{
		            		var btn_edit 	= '<button type="button" class="btn btn-sm btn-warning" title="Edit" data-descid="'+input_value[0]['description_id']+'" data-detailid="'+data['data']+'" data-description="'+($('#description').val())+'" data-remark="'+input_value[0]['remark']+'"data-amount="'+input_value[0]['amount']+'" onclick="open_modal('+"'update_invoice_disbursement'"+', this)"><i class="fas fa-edit"></i></button>';
		            		var btn_delete 	= '<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ID="'+data['data']+'" data-updatedBY="'+<?php echo $_SESSION['user']['id']; ?>+'" data-updatedTS="'+moment().format('YYYY-MM-DD HH:mm:ss')+'" data-rowid="disbursement_row_'+data['data']+'" data-tableid="table_invoice_disbursement_'+input_value[0]['description_id']+'" onclick="delete_row('+"'delete_invoice_disbursement'"+','+"'sv__invoice_description'"+',['+"'ID'"+','+"'updatedBY'"+','+"'updatedTS'"+'], this)"><i class="fas fa-trash"></i></button>';

		            		var btn = btn_edit+btn_delete;
		            		var table = $('#'+input_id).DataTable();
					        // table.clear().draw();

		            		if((input_id.split('_'))[3] == 74)
		            		{
			            		table.row.add({
		                            0   : input_value[0]['remark'],
		                            1   : parseFloat(input_value[0]['amount']).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"),
		                            2   : '<div class="text-center"><div class="btn-group btn-group-sm" role="group">'+btn+'</div></div>',
	    						}).node().id = 'disbursement_row_'+data['data'];
		                        table.draw();
		            		}else{
		            			table.row.add({
		                            0   : parseFloat(input_value[0]['amount']).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"),
		                            1   : '<div class="text-center"><div class="btn-group btn-group-sm" role="group">'+btn+'</div></div>',
		                        }).node().id = 'disbursement_row_'+data['data'];
		                        table.draw();
		            		}

							count_description(data.result2);
		            	}else{
		            		$('#'+input_id).val(data.result);
		            	}
						
					}else{
						iziToast.warning({
		                    position: 'bottomRight',
		                    message: data.msg
		                });

		                $('#'+input_id).val(existing_value);
					}
	          	}
	       	});
		}else{
			alert("Please insert the correct amount.");
		}
	}

	function update_client_info(mode, input_id, table_row_id = null, modal_input_id, table_name)
	{
		var input_key		= {};
		var input_value		= [];
		var existing_value	= $('#'+input_id).val();
		var flag = true;

		$.each(modal_input_id, function(key, row){
			if(row == 'amount' && parseFloat($('#'+row).val()))
			{	
				flag = true;
			}else{
				flag = false;
			}
			
			if(row == 'client_id')
			{
				input_key["customer_id"] = $('#'+row).val();
			}else{
				input_key[row] = $('#'+row).val();
			}
		});
		
		input_value.push(input_key);

		if(flag == true)
		{
	    	$.ajax({
	    		url:'<?php echo base_url('hr/serviceform/invoice_save_client_info/'.$entity_id.'/'.$ID.'/update') ?>',
	    		data: {
	    			mode 		: mode,
	    			table_name	: table_name,
	    			input_value : input_value[0],
	    		},
	    		type: 'post',
	    		dataType: 'json',
	    		success: (data) => {
	    			if(data.status == "success") {
	    				$('#modal_add_client_info').modal('hide');

	    				iziToast.success({
	    					position: 'bottomRight',
	    					message: data.msg,
	    				});

	    				var table = $('#'+input_id).DataTable();
	    				table.row('#'+table_row_id).remove().draw();
	    				// table.clear().draw();

	    				if(mode == 'update_invoice_detail')
	    				{
	    					var btn_edit 	= '<button type="button" class="btn btn-sm btn-warning" title="Edit" data-descid="'+input_value[0]['description_id']+'" data-detailid="'+input_value[0]['ID']+'" data-description="'+($('#description').val())+'" data-remark="'+input_value[0]['remark']+'" data-yearend="'+input_value[0]['year_end']+'" data-amount="'+input_value[0]['amount']+'" onclick="open_modal('+"'update_invoice_detail'"+', this)"><i class="fas fa-edit"></i></button>';
		            		var btn_delete 	= '<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ID="'+input_value[0]['ID']+'" data-updatedBY="'+<?php echo $_SESSION['user']['id']; ?>+'" data-updatedTS="'+moment().format('YYYY-MM-DD HH:mm:ss')+'" data-rowid="detail_row_'+input_value[0]['ID']+'" data-tableid="table_invoice_detail_'+input_value[0]['description_id']+'" onclick="delete_row('+"'delete_invoice_detail'"+','+"'sv__invoice_description'"+',['+"'ID'"+','+"'updatedBY'"+','+"'updatedTS'"+'], this)"><i class="fas fa-trash"></i></button>';

		            		var btn = btn_edit+btn_delete;
	    					var table = $('#'+input_id).DataTable();
	    					// table.clear().draw();

	    					table.row.add({
	    						0   : input_value[0]['remark'],
	    						1   : input_value[0]['year_end'],
	    						2   : parseFloat(input_value[0]['amount']).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"),
	    						3   : '<div class="text-center"><div class="btn-group btn-group-sm" role="group">'+btn+'</div></div>',
	    					}).node().id = 'detail_row_'+input_value[0]['ID'];
	                        table.draw();

	                        update_total(mode, data.result, input_value[0]['amount']);
							count_description(data.result2);
	    				}else if(mode == 'update_invoice_disbursement')
	    				{
	    					var btn_edit 	= '<button type="button" class="btn btn-sm btn-warning" title="Edit" data-descid="'+input_value[0]['description_id']+'" data-detailid="'+input_value[0]['ID']+'" data-description="'+($('#description').val())+'" data-remark="'+input_value[0]['remark']+'"data-amount="'+input_value[0]['amount']+'" onclick="open_modal('+"'update_invoice_disbursement'"+', this)"><i class="fas fa-edit"></i></button>';
		            		var btn_delete 	= '<button type="button" class="btn btn-sm btn-danger" title="Delete" data-ID="'+input_value[0]['ID']+'" data-updatedBY="'+<?php echo $_SESSION['user']['id']; ?>+'" data-updatedTS="'+moment().format('YYYY-MM-DD HH:mm:ss')+'" data-rowid="disbursement_row_'+input_value[0]['ID']+'" data-tableid="table_invoice_disbursement_'+input_value[0]['description_id']+'" onclick="delete_row('+"'delete_invoice_disbursement'"+','+"'sv__invoice_description'"+',['+"'ID'"+','+"'updatedBY'"+','+"'updatedTS'"+'], this)"><i class="fas fa-trash"></i></button>';

		            		var btn = btn_edit+btn_delete;
	    					var table = $('#'+input_id).DataTable();
		        			// table.clear().draw();
		        			if((input_id.split('_'))[3] == 74)
		        			{
		        				table.row.add({
		        					0   : input_value[0]['remark'],
		        					1   : parseFloat(input_value[0]['amount']).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"),
		        					2   : '<div class="text-center"><div class="btn-group btn-group-sm" role="group">'+btn+'</div></div>',
		        				}).node().id = 'disbursement_row_'+input_value[0]['ID'];
		                        table.draw();
		        			}else{
		        				table.row.add({
		        					0   : parseFloat(input_value[0]['amount']).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"),
		        					1   : '<div class="text-center"><div class="btn-group btn-group-sm" role="group">'+btn+'</div></div>',
		        				}).node().id = 'disbursement_row_'+input_value[0]['ID'];
		                        table.draw();
		        			}
	                        
	                        update_total(mode, data.result, input_value[0]['amount']);
							count_description(data.result2);
		        		}else{
		        			$('#'+input_id).val(data.result);
		        		}
		        	}else{
		        		iziToast.warning({
		        			position: 'bottomRight',
		        			message: data.msg
		        		});

		        		$('#'+input_id).val(existing_value);
		        	}
		        }
		    });
		}else{
			alert("Please insert the correct amount.");
		}
    }

    function delete_row(mode, table_name, dataid, elem)
    {
    	var input_key		= {};
		var input_value		= [];
		var input_id 		= $(elem).data('tableid');
		var table_row_id	= $(elem).data('rowid');

		input_key['is_delete'] = 1;
		$.each(dataid, function(key, row){
			input_key[row] = $(elem).data((row.toLowerCase()));
		});
		
		input_value.push(input_key);
    	$.ajax({
    		url:'<?php echo base_url('hr/serviceform/invoice_save_client_info/'.$entity_id.'/'.$ID.'/update') ?>',
    		data: {
    			mode 		: mode,
    			table_name	: table_name,
    			input_value : input_value[0],
    		},
    		type: 'post',
    		dataType: 'json',
    		success: (data) => {
    			if(data.status == "success") {
    				iziToast.success({
    					position: 'bottomRight',
    					message: data.msg,
    				});

    				var table = $('#'+input_id).DataTable();

    				table.row('#'+table_row_id).remove().draw(false);

                    update_total(mode, data.result, 0);
                    count_description(data.result2);
	        	}else{
	        		iziToast.warning({
	        			position: 'bottomRight',
	        			message: data.msg
	        		});
	        	}
	        }
	    });
    }

    function count_description(count_description)
    {
    	var count_desc = JSON.parse(count_description);

    	$.each(count_desc, function(key, row){
			$('#description_'+row['ID']).removeClass('badge-danger');
			$('#description_'+row['ID']).text('');
			
			if(row['total_description'] > 0)
			{
				$('#description_'+row['ID']).addClass('badge-danger');
				$('#description_'+row['ID']).text(row['total_description']);
			}
		});
    }

    function check_total_selected(input_id)
    {
    	var input_value = $('#'+input_id).val();
    	// if (!$("select").is(":focus")) isFocused = 'true';

    	if(input_value.length == 1)
    	{
    		iziToast.warning({
				position: 'bottomRight',
				// title: localStorage.getItem("status"),
				message: "Please select one more manager."
			});
    	}
    	else if(input_value.length == 2)
    	{
    		iziToast.success({
				position: 'bottomRight',
				// title: localStorage.getItem("status"),
				message: "Success."
			});
    	}
    	else
    	{
    		iziToast.warning({
				position: 'bottomRight',
				title: "warning",
				message: "Maximum selected manager is two(2)."
			});	
    	}    	
    }

    function change_manager_input(manager_id)
	{
		var manager_id = manager_id.split(',');
		$('#mgr_approval').selectpicker('val', manager_id);;
	}
</script>