<style>
	.accordion {
		background-color: #eee;
		color: #444;
		cursor: pointer;
		/*padding: 18px;*/
		width: 100%;
		border: none;
		/*text-align: left;*/
		outline: none;
		/*font-size: 15px;*/
		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="card bg-light-transparent">
				<div class="card-header bg-light">
					<h4 class="card-title float-left"><?php echo (empty($ID))?'New ':'Edit '; ?>CAPEX Request Form <?php echo ($ID)?'#'.str_pad($ID, 5, '0', STR_PAD_LEFT):''; ?></h4>
					<?php if(($this->session->userdata('all_modules_access')[0]['access_lvl'] == 'admin')){ ?>
						<div class="float-right">
							<button type="button" data-toggle="modal" class="btn btn-primary" data-target="#capex_add_more_modal">Add New CAPEX Item</button>
						</div>
					<?php } ?>
				</div>

				<div class="card-body">
					<div class="card no-shadow">
						<div class="card-body">
							<form id="capexForm" class="form" action="<?php echo ($ID)?base_url('hr/Serviceform/capex_request_edit'):base_url('hr/Serviceform/capex_request_save'); ?>" method="POST" <?php echo ($ID)?'onsubmit="return confirm('."'Do you really want to submit the form?'".')"':''; ?>>
								<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="reqName" id="reqName" value="<?php echo ($ID)?$capexRequestDetail['created_name']:$_SESSION['user']['name']; ?>" readonly>
											<input type="text" class="form-control" name="reqName_id" id="reqName_id" value="<?php echo ($ID)?$capexRequestDetail['createdBY']:$_SESSION['user']['id']; ?>" hidden>
										</div>
									</div>

									<div class="col-12 col-sm-6">
										<div class="form-group">
											<label>Email</label>
											<input type="" class="form-control" name="email" id="email" value="<?php echo (!empty($ID))?$capexRequestDetail['created_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="department" id="department" value="<?php echo ($ID)?$capexRequestDetail['created_dept_name'].' ['.$capexRequestDetail['created_branch_name'].']':$_SESSION['user']['department_name'].' ['.$_SESSION['user']['branch_name'].']'; ?>" readonly>
											<input type="text" class="form-control" name="department_id" id="department_id" value="<?php echo ($ID)?$capexRequestDetail['created_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="reqDate" id="reqDate" value="<?php echo (!empty($ID))?date('d-m-Y',strtotime($capexRequestDetail['createdTS'])):date('d-m-Y'); ?>" readonly>
										</div>
									</div>

									<div class="col-12 col-sm-6">
										<div class="form-group">
											<label>Purpose</label>
											<input type="text" class="form-control" name="purpose" id="purpose" value="<?php echo (!empty($ID))?$capexRequestDetail['purpose']:''; ?>" required>
										</div>
									</div>

									<?php if(empty($ID)) { ?>
										<div class="col-12 col-sm-6" style="line-height: 6;">
											<div class="form-group float-right">
												<a class="btn btn-light" href="<?php echo base_url('hr/serviceform/capex_request_list/'); ?>">Cancel</a>
												<button type="submit" class="btn btn-primary">Submit</button>
											</div>
										</div>
									<?php } ?>
								</div>

								<?php if(!empty($ID)) { ?>
									<input type="text" class="form-control" name="capexID" id="capexID" value="<?php echo $ID; ?>" hidden>

									<hr>

									<div class="form-row">
										<div class="col-12">
											<label for="capex"><h5><strong>Capex Lists</strong></h5></label>
											<br>
											<?php if($capexCategoryItemDetail) { ?>
												<?php foreach($capexCategoryItemDetail as $row) { ?>
													<br>
													<a class="accordion p-2 bg-light float-right">
														<?php echo $row['category']; ?>
														<?php if(sizeof($row['item']) >=  1) {?>
															<span class="badge badge-pill badge-danger"><?php echo sizeof($row['item']); ?></span>
														<?php } ?>
													</a>

													<div class="col-12 panel">
														<?php if($ID && $mode != 'view'){ ?>
															<?php if($_SESSION['user']['id'] == $capexRequestDetail['createdBY']){ ?>
																<br>
																<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-primary btn-sm" data-trigger="hover" title="Add New <?php echo ucwords(strtolower($row['category'])); ?>"
																			data-tooltip="tooltip"
																			data-category="<?php echo $row['category']; ?>" 
																			data-categoryid="<?php echo $row['ID']; ?>" 
																			data-capexid="<?php echo $ID; ?>" 
																			onclick="open_modal('add_capex_detail',['category','category_id','capex_id'],this)">Add New <?php echo ucwords(strtolower($row['category'])); ?>
																		</button>
																	</div>
																</div>
																<br>
															<?php } ?>
														<?php } ?>

														<br>

														<div class="table-responsive">
															<table id="qwerty" class="table table-hover table-striped ">
																<thead align="center"> 
																	<tr>
																		<td>#</td>
																		<td>Capex Item</td>
																		<td>Quantity</td>
																		<?php if($ID && $mode != 'view' && $_SESSION['user']['id'] == $capexRequestDetail['createdBY']){ ?>
																			<td>Action</td>
																		<?php } ?>	
																	</tr>
																</thead>
																<tbody align="center">
																	<?php $i = 1; if($row['item']) foreach($row['item'] as $rowItem) if($rowItem['quantity'] > 0){  ?>
																		<?php if(($rowItem['capex_id'] == $ID)){ ?>
																			<tr>
																				<td><?php echo $i++; ?></td>
																				<td class="text-left"><?php echo $rowItem['item']; ?></td>
																				<td><?php echo $rowItem['quantity']; ?></td>
																				<?php if(($ID) && ($mode != 'view') && (($_SESSION['user']['id'] == $rowItem['createdBY']) || ($_SESSION['user']['id'] == $rowItem['requester_id']))){ ?>			
																					<td class="text-center">
																						<div class="btn-group btn-group-sm" role="group">
																							<button type="button" class="btn btn-outline-dark" data-trigger="hover" title="Edit <?php echo $rowItem['item']; ?>"
																								data-tooltip="tooltip" 
																								data-capexid="<?php echo $ID; ?>" 
																								data-category="<?php echo $row['category']; ?>" 
																								data-categoryid="<?php echo $row['ID']; ?>"
																								data-id="<?php echo $rowItem['capex_detail_id']; ?>"
																								data-itemid="<?php echo $rowItem['item_id']; ?>" 
																								data-item="<?php echo $rowItem['item']; ?>" 
																								data-quantity="<?php echo $rowItem['quantity']; ?>"
																								onclick="open_modal('update_capex_detail',['capex_id','category','category_id','ID','item_id','item','quantity'],this)">
																								<i class="far fa-edit"></i>
																							</button>
																							<button type="button" class="btn btn-outline-dark" data-trigger="hover" id="deleteBtnItem_<?php echo $rowItem['capex_detail_id']; ?>" data-tooltip="tooltip" title="Delete <?php echo $rowItem['item']; ?>"
																								data-capexid="<?php echo $ID; ?>" 
																								data-id="<?php echo $rowItem['capex_detail_id']; ?>"
																								data-item="<?php echo $rowItem['item']; ?>"
																								onclick="deleteCapex('delete_capex_detail',['capex_id','ID','item'],this)">
																								<i class="far fa-trash-alt"></i>
																							</button>
																						</div>
																					</td>
																				<?php } ?>
																			</tr>
																		<?php } ?>
																	<?php } ?> 
																</tbody>
															</table>
														</div>
													</div>
												<?php } ?>
											<?php } ?>
										</div>
									</div>

									<?php if($ID && $mode != 'view' && $_SESSION['user']['id'] == $capexRequestDetail['createdBY']){ ?>
										<hr>
										<div class="form-row">
											<div class="col-12">
												<div class="float-right" style="padding-top: 1rem; padding-bottom: 1rem;">
													<a class="btn btn-light" href="<?php echo base_url('hr/serviceform/capex_list/'); ?>">Cancel</a>
													<button type="submit" class="btn btn-primary">Update</button>
												</div> 
											</div>
										</div>
									<?php } ?>
								<?php } ?>
							</form>
						</div>
					</div>	
				</div>
			</div>
		</div>
	</div>
</section>

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

<div class="modal fade" id="capex_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg" role="document"  id="capex_modal_size">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title" id="capex_modal_title"></h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>

			<div class="modal-body">
				<form id="capexForm_modal" class="form">
					<div id="capex_modal_content"></div>

					<div class="float-right">
						<button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
						<button type="submit" class="btn btn-primary" id="capexSaveBtn">Submit</button>
					</div> 
				</form>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="capex_add_more_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title" id="add_more_title_modal">Add New Details Package</h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>

			<div class="modal-body">
				<form action="<?php echo base_url('hr/Serviceform/capex_new_details_save')?>" method="post">
					<input type="text" class="form-control" name="new_detail_capex_id" id="new_detail_capex_id" value="<?php echo $ID; ?>" hidden>
					<div class="row">
						<div class="col-12 mb-6">
							<label>Category</label>
							<select class="form-control" id="new_detail_category" name="new_detail_category" required>
								<option value="-1">-- Please Select --</option>
								<?php if($capexCategoryItemDetail) { //die(debug($capexCategoryItemDetail)); ?>
									<?php foreach($capexCategoryItemDetail as $row) { ?>
										<option value="<?php echo $row['ID']; ?>"><?php echo $row['category']; ?></option>
									<?php } ?>
								<?php } ?>
							</select>
						</div>
					</div><br>

					<div class="row" style="padding-bottom: 4rem;">
						<div class="col-12">
							<label>Type</label>
							<input class="form-control" type="text" id="new_detail_type" name="new_detail_type" required>
						</div>
					</div>

					<div class="float-right">
						<button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
						<button type="submit" class="btn btn-primary">Submit</button>
					</div> 
				</form>
			</div>
		</div>
	</div>
</div>	

<script>
	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";
			} 
		});
	}

	function open_modal(mode,input_id,elem)
	{
		var temp_content 	= '';
		var input_key		= {};
		var input_value		= [];
		var url 			= '';
		var str 			= ''; 
		var i 				= 0;

		str = (mode.replaceAll('_',' ')).toLowerCase().replace(/\b[a-z]/g, function(letter) {
			return letter.toUpperCase();
		});

		if(elem != undefined && elem != null)
		{
			$.each(input_id, function(key, row)
			{
				i++;
				input_key[row] = $(elem).data((row.toLowerCase()).replaceAll('_',''));
			});
		}else{
			$.each(input_id, function(key, row){
				if($('#'+row).val() != undefined && $('#'+row).val() != '')
				{
					i++;
					input_key[row] = $('#'+row).val();
				}
			});
		}

		input_value.push(input_key);

		$('#capex_modal_content').html('');

		$.ajax({
			url: '<?php echo base_url('hr/serviceform/get_capex_detail') ?>',
			type: 'POST',
			data:{
				mode 			: mode,
				input_value		: input_value[0],
			},
			dataType: 'JSON',
			success: function(data){
				if(data.status == 'Success')
				{
					var details = data.query;
					
					if(mode == 'add_capex_detail')
					{	
						temp_content = 
						'<div class="form-row">\
							<div class="col-12 col-sm-6">\
								<label>Category</label>\
								<input type="text" class="form-control" name="capex_id" id="capex_id" value="'+input_value[0].capex_id+'" hidden>\
								<input type="text" class="form-control" value="'+input_value[0].category+'" readonly>\
							</div>\
							<div class="col-12 col-sm-6">\
								<label>Item</label>\
								<select class="form-control" name="item_id" id="item_id" required>\
								<option value="-1" selected disabled>-- Please Select --</option>\
								</select>\
							</div>\
							<div class="col-12 col-sm-6">\
								<label>Quantity</label>\
								<input type="number" min="1" class="form-control" name="quantity" id="quantity" required>\
							</div>\
						</div>';

						$('#capex_modal_content').append(temp_content);
						$('#capexForm_modal').attr({
							'action'	: '<?php echo base_url('hr/Serviceform/capex_request_save/item'); ?>', 
							'method'	: 'post', 
							'onsubmit'	: 'return confirm("Do you really want to add new item?")'
						});

						if(details != null)
						{
							$.each(details,function(key,content){
								var select_template = `<option value="${content.ID}" >${content.item}</option>`;
								$('#item_id').append(select_template);
							});
						}
					}else if(mode == 'update_capex_detail')
					{
						temp_content = 
						'<div class="form-row">\
						<div class="col-12 col-sm-6">\
						<label>Category</label>\
						<input type="text" class="form-control" name="capex_id" id="capex_id" value="'+input_value[0].capex_id+'" hidden>\
						<input type="text" class="form-control" name="ID" id="ID" value="'+input_value[0].ID+'" hidden>\
						<input type="text" class="form-control" value="'+input_value[0].category+'" readonly>\
						</div>\
						<div class="col-12 col-sm-6">\
						<label>Item</label>\
						<select class="form-control" name="item_id" id="item_id" required>\
						<option value="-1" selected disabled>-- Please Select --</option>\
						</select>\
						</div>\
						<div class="col-12 col-sm-6">\
						<label>Quantity</label>\
						<input type="number" min="1" class="form-control" name="quantity" id="quantity" required>\
						</div>\
						</div>';

						$('#capex_modal_content').append(temp_content);
						$('#capexForm_modal').attr({
							'action'	: '<?php echo base_url('hr/Serviceform/capex_request_edit/item'); ?>', 
							'method'	: 'post', 
							'onsubmit'	: 'return confirm("Do you really want to update '+input_value[0].category+' detail?")'
						});

						if(details != null)
						{
							$.each(details,function(key,content){
								var select_template = `<option value="${content.ID}" >${content.item}</option>`;
								$('#item_id').append(select_template);
							});
						}

						$('#item_id').val(input_value[0].item_id);
						$('#quantity').val(input_value[0].quantity);
					}
				}
				
				$('#capex_modal_title').html('');
				$('#capex_modal_title').append(str);
				$('#capex_modal_size').css('max-width','60%');
				$('#capex_modal').modal('show');
			},
			error:function(err){
				iziToast.error({
					title: 'Error',
					message: 'Failed to fetch capex details'
				});
			}
		});
	}

	function deleteCapex(mode,input_id,elem)
	{
		var temp_content 	= '';
		var input_key		= {};
		var input_value		= [];
		var url 			= '';
		var str 			= ''; 
		var i 				= 0;

		str = (mode.replaceAll('_',' ')).toLowerCase().replace(/\b[a-z]/g, function(letter) {
			return letter.toUpperCase();
		});

		if(mode == 'delete_capex_detail') input_key['is_delete'] = 1;
		$.each(input_id, function(key, row)
		{
			i++;
			input_key[row] = $(elem).data((row.toLowerCase()).replaceAll('_',''));
		});
		
		input_value.push(input_key);

		validateForm("#deleteBtnItem_"+input_value[0].ID, "Delete "+input_value[0].item+"?", function() {
			$.ajax({
				url:'<?php echo base_url('hr/serviceform/capex_request_delete/item'); ?>',
				data: {
					mode 		: mode,
					input_value	: input_value[0],
				},
				type: 'post',
				dataType: 'json',
				success: (data) => {
					if(data.status == "Success") {

						localStorage.setItem("status", data.status);
						localStorage.setItem("msg", data.msg);

						location.reload();
					}
				}
			});
		});
	}
</script>