<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 '; ?> Job Request Form</h4>
						</div>
						<div class="card-body">
							<div class="card no-shadow">
								<div class="card-body">
									<form id="jobRequestForm" class="form" action="<?php //echo ($ID)?base_url('hr/Serviceform/job_request_edit'):base_url('hr/Serviceform/job_request_save'); ?>" method="POST" onsubmit="//return confirm('Confirm to submit this form?')">

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

										<div class="form-row">
											<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="request_name" id="request_name" value="<?php echo ($ID)?$job_request_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)?$job_request_list['requester_id']:$_SESSION['user']['id']; ?>" hidden>
															</div>
														</div>

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

														<div class="col-12 col-sm-6">
															<div class="form-group">
																<label>Department</label>
																<input type="text" class="form-control" name="request_dept" id="request_dept" value="<?php echo ($ID)?$job_request_list['dept_name'].' ['.$job_request_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)?$job_request_list['department_id']:$_SESSION['user']['department_id']; ?>" hidden>
															</div>
														</div>

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

										<div class="form-row">
											<div class="col-12">
												<div class="form-group">
													<label>Description</label>
													<textarea class="form-control" name="description" id="description" rows="2" required><?php echo ($ID)?$job_request_list['description']:''; ?></textarea>
												</div>
											</div>

											<div class="col-12">
												<div class="form-group">
													<label>Remarks (If Any)</label>
													<textarea class="form-control" name="remarks" id="remarks" rows="2"><?php echo ($ID)?$job_request_list['remarks']:''; ?></textarea>
												</div>
											</div>

											<div class="col-12 col-sm-6">
												<div class="form-group">
													<label>Deadline (If Any)</label>
													<input type="text" class="form-control datepicker" name="deadline" id="deadline" value="<?php echo ($ID)?((strtotime($job_request_list['deadline']) > 0)?date('d-m-Y',strtotime($job_request_list['deadline'])):''):''; ?>">
												</div>
											</div>

											<div class="col-12 col-sm-6">
												<div class="form-group">
													<label>Year End Date (If Any)</label>
													<input type="text" class="form-control datepicker-yyyy" name="yearEndDate" id="yearEndDate" value="<?php echo ($ID)?$job_request_list['yearEndDate']:''; ?>">
												</div>
											</div>
										</div>

										<div class="form-row" id="job_detail">
											<div class="col-12">
												<hr>
												<div class="form-group">
													<h5 class="float-left"><b>Client & Department Details</b></h5>
													<?php if(!isset($mode) && ($mode != 'view')){ ?>	
														<div class="float-right btn-group">
															<button type="button" class="btn btn-outline-dark btn-sm" data-trigger="hover" data-tooltip="tooltip" title="Add New Details" onclick="open_modal('job_detail_modal','job_detail_form','new')"><i class="fas fa-plus"></i> Add New Details</button>
														</div>
													<?php } ?>
													<br><br><br>
													<table class="table table-bordered table-striped table-hover" id="table_job_detail">
														<thead class="text-center">
															<th width="5%">#</th>
															<th width="40%">Client</th>
															<th width="40%">Department</th>
															<th width="15%">Action</th>
														</thead>
														<tbody>
														</tbody>
													</table>
												</div>
											</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/job_request_list/'); ?>">Cancel</a>
													<button type="submit" id="submitBtn" class="btn btn-primary"><?php echo 'submit';//($ID)?'Update':'Submit'; ?></button>
												</div> 
											</div>
										</div>
									</form>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</section>

<!-- job detail modal -->
<div class="modal fade d-print-none" id="job_detail_modal" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="job_detail_modal_title">Client & Department Details</h5>&emsp;
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<form class="form" id="job_detail_form">
				<div class="modal-body">

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

					<div class="form-row">
						<div class="col-12">
							<label>Company Name</label>
							<select class="form-control select" name="client_id[]" id="client_id" required multiple>
								<?php if($client) foreach($client as $row){ ?>
									<option value="<?php echo $row->customer_id; ?>"><?php echo $row->name; ?></option>
								<?php } ?>
							</select>
						</div>
						
						<div style="margin-bottom: 6rem;"></div>

						<div class="col-12">
							<label>Department</label>
							<select class="form-control select" name="department_id[]" id="department_id" required multiple>
								<?php if($department) foreach($department as $key => $dept){ ?>
									<option 
										value="<?php echo $dept['id']; ?>"
										 <?php echo ($ID)?'':(($_SESSION['user']['department_id'] == $dept['id'])?'selected':''); ?>
									>
										<?php echo $dept['name'].' ['.$dept['branch_name'].']'; ?>
									</option>
								<?php } ?>
							</select>
						</div>
					</div>
					<br>
					<div class="float-right" style="padding-bottom: 1rem;">
						<button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
						<button type="button" id="submitBtnDetail" class="btn btn-primary" onclick="addClientDepartmentDetail()">add</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>
<!-- job detail modal -->

<?php echo (!empty($approval))?$approval:''; ?>

<script type="text/javascript">
	var jobDetailTable = new Array();

	$(document).ready(function(){
		$('.select').select2({
			theme : 'bootstrap4',
			placeholder : '-- Please Select --',
		});

		if('<?php echo $ID; ?>' > 0 && '<?php echo $ID; ?>' != '')
		{
			$('#submitBtn').attr('onclick','updateJobRequest()');
		}else{
			$('#submitBtn').attr('onclick','createJobRequest()');
		}
	});

	function open_modal(modal_id, modal_form_id, mode, detail_row_id)
	{
		clearForm('#'+modal_form_id);
		var dept_id = $('#request_dept_id').val();

		if(mode == 'new') 
		{
			$('#department_id').val(dept_id).trigger('change');
			$('#submitBtnDetail').attr('onclick','addClientDepartmentDetail()');
		}
		if(mode == 'edit') 
		{
			$('#submitBtnDetail').attr('onclick','addClientDepartmentDetail('+"'edit'"+','+detail_row_id+')');
			editModal(detail_row_id);
		}

		$('.select2-search__field').css({'width':'1000px', 'cursor':'pointer'});
		$('#'+modal_id).modal('show');
	}

	function addClientDepartmentDetail(mode = null, detail_row_id = 0)
	{
		var client_id 		= $('#client_id').val();
		var client_name		= $('#client_id option:selected').toArray().map(item => item.text).join();
		var department_id 	= $('#department_id').val();
		var department_name	= $('#department_id option:selected').toArray().map(item => item.text).join();

		if(client_id.length > 0)
		{
			var table = [{
		        client_id     		: client_id,
		        client_name   		: client_name,
		        department_id     	: department_id,
		        department_name   	: department_name,
		    }];

		    jobDetailTable.push(table);

			$('#job_detail_modal').modal('hide');

		    if(mode == 'edit') removeDetail(detail_row_id);

		    createTable();
		}else{
			alert('Please fill in the blank.');
		}
	}

	function createTable()
	{
		var table   = $('#table_job_detail').DataTable();
		table.clear().draw();

		if(jobDetailTable.length > 0)
		{      
			for (var i = 0; i < jobDetailTable.length; i++) 
			{
				var rowCount = table.data().count();
				table.row.add({
					0   : '<div class="text-center">'+(++rowCount)+'</div>',
					1   : jobDetailTable[i][0].client_name,
					2   : jobDetailTable[i][0].department_name,  
					3   : '<div class="text-center"><div class="btn-group btn-group-sm" role="group">\
								<button type="button" class="btn btn-warning" data-toggle="tooltip" data-placement="top" title="Edit Detail" onclick="open_modal('+"'job_detail_modal'"+','+"'job_detail_form'"+','+"'edit'"+','+rowCount+')"><i class="fas fa-edit"></i></button>\
								<button type="button" class="btn btn-danger" onclick="removeDetail('+rowCount+')" data-toggle="tooltip" data-placement="top" title="Delete Detail"><i class="fas fa-trash"></i></button>\
							</div></div>',
				}).draw();
			};
		}
	}

	function editModal(row) 
	{
		$('#client_id').val(jobDetailTable[row-1][0].client_id).trigger('change');
		$('#department_id').val(jobDetailTable[row-1][0].department_id).trigger('change');
	}

	function removeDetail(row) 
	{
		jobDetailTable.splice(row-1,1);
		createTable();
	}

	function createJobRequest()
	{
		$('#submitBtn').addClass('disabled');
		$('#submitBtn').attr('disabled','disabled');

		event.preventDefault();

	    var request_name_id 	= $('#request_name_id').val();
	    var request_email 		= $('#request_email').val();
	    var request_dept_id 	= $('#pac-request_dept_idt').val();
	    var datereq 			= $('#datereq').val();
	    var description 		= $('#description').val();
	    var remarks 			= $('#remarks').val();
	    var deadline 			= $('#deadline').val();
	    var yearEndDate 		= $('#yearEndDate').val();
	    var detail 				= JSON.stringify(jobDetailTable);

	    var frmData = new FormData();
	    frmData.append("request_name_id",request_name_id);
	    frmData.append("request_email",request_email);
	    frmData.append("request_dept_id",request_dept_id);
	    frmData.append("datereq",datereq);
	    frmData.append("description",description);
	    frmData.append("remarks",remarks);
	    frmData.append("deadline",deadline);
	    frmData.append("yearEndDate",yearEndDate);
	    frmData.append("detail",detail);

	    iziToast.info({
	        title: 'Please wait',
	        message: 'Creating Job Request.'
	     });

	    $.ajax({
	        url:"<?php echo base_url('hr/serviceform/job_request_save'); ?>",
	        type:'post',
	        dataType:'json',
	        data:frmData,
	        processData: false,
	        contentType: false,
	        success:function(data){
	            iziToast.success({
	                title: 'Success',
	                message: 'Successfully created Job Request.'
	            });
	            window.location.replace("<?php echo base_url('hr/serviceform/job_request_list') ?>");
	            
	        },error:function(data){
	            iziToast.error({
	                title: 'Error',
	                message: 'Failed to create Job Request.'
	            });
	        }
	    });
	}
</script>